instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to improve code quality
#!/usr/bin/env python3 import argparse import sys import subprocess import json def check_yt_dlp(): try: subprocess.run(["yt-dlp", "--version"], capture_output=True, check=True) except (subprocess.CalledProcessError, FileNotFoundError): print("yt-dlp not found. Installing...") subprocess.run([sys.executable, "-m", "pip", "install", "--break-system-packages", "yt-dlp"], check=True) def get_video_info(url): result = subprocess.run( ["yt-dlp", "--dump-json", "--no-playlist", url], capture_output=True, text=True, check=True ) return json.loads(result.stdout) def download_video(url, output_path="/mnt/user-data/outputs", quality="best", format_type="mp4", audio_only=False): check_yt_dlp() # Build command cmd = ["yt-dlp"] if audio_only: cmd.extend([ "-x", # Extract audio "--audio-format", "mp3", "--audio-quality", "0", # Best quality ]) else: # Video quality settings if quality == "best": format_string = "bestvideo+bestaudio/best" elif quality == "worst": format_string = "worstvideo+worstaudio/worst" else: # Specific resolution (e.g., 1080p, 720p) height = quality.replace("p", "") format_string = f"bestvideo[height<={height}]+bestaudio/best[height<={height}]" cmd.extend([ "-f", format_string, "--merge-output-format", format_type, ]) # Output template cmd.extend([ "-o", f"{output_path}/%(title)s.%(ext)s", "--no-playlist", # Don't download playlists by default ]) cmd.append(url) print(f"Downloading from: {url}") print(f"Quality: {quality}") print(f"Format: {'mp3 (audio only)' if audio_only else format_type}") print(f"Output: {output_path}\n") try: # Get video info first info = get_video_info(url) print(f"Title: {info.get('title', 'Unknown')}") print(f"Duration: {info.get('duration', 0) // 60}:{info.get('duration', 0) % 60:02d}") print(f"Uploader: {info.get('uploader', 'Unknown')}\n") # Download the video subprocess.run(cmd, check=True) print(f"\n✅ Download complete!") return True except subprocess.CalledProcessError as e: print(f"\n❌ Error downloading video: {e}") return False except Exception as e: print(f"\n❌ Error: {e}") return False def main(): parser = argparse.ArgumentParser( description="Download YouTube videos with customizable quality and format" ) parser.add_argument("url", help="YouTube video URL") parser.add_argument( "-o", "--output", default="/mnt/user-data/outputs", help="Output directory (default: /mnt/user-data/outputs)" ) parser.add_argument( "-q", "--quality", default="best", choices=["best", "1080p", "720p", "480p", "360p", "worst"], help="Video quality (default: best)" ) parser.add_argument( "-f", "--format", default="mp4", choices=["mp4", "webm", "mkv"], help="Video format (default: mp4)" ) parser.add_argument( "-a", "--audio-only", action="store_true", help="Download only audio as MP3" ) args = parser.parse_args() success = download_video( url=args.url, output_path=args.output, quality=args.quality, format_type=args.format, audio_only=args.audio_only ) sys.exit(0 if success else 1) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +""" +YouTube Video Downloader +Downloads videos from YouTube with customizable quality and format options. +""" import argparse import sys @@ -7,6 +11,7 @@ def check_yt_dlp(): + """Check if yt-dlp is installed, install if not.""" try: subprocess.run(["yt-dlp", "--version"], capture_output=True, check=True) except (subprocess.CalledProcessError, FileNotFoundError): @@ -15,6 +20,7 @@ def get_video_info(url): + """Get information about the video without downloading.""" result = subprocess.run( ["yt-dlp", "--dump-json", "--no-playlist", url], capture_output=True, @@ -25,6 +31,16 @@ def download_video(url, output_path="/mnt/user-data/outputs", quality="best", format_type="mp4", audio_only=False): + """ + Download a YouTube video. + + Args: + url: YouTube video URL + output_path: Directory to save the video + quality: Quality setting (best, 1080p, 720p, 480p, 360p, worst) + format_type: Output format (mp4, webm, mkv, etc.) + audio_only: Download only audio (mp3) + """ check_yt_dlp() # Build command
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/video-downloader/scripts/download_video.py
Add clean documentation to messy code
#!/usr/bin/env python3 from PIL import Image, ImageDraw, ImageFont from typing import Optional # Typography scale - proportional sizing system TYPOGRAPHY_SCALE = { 'h1': 60, # Large headers 'h2': 48, # Medium headers 'h3': 36, # Small headers 'title': 50, # Title text 'body': 28, # Body text 'small': 20, # Small text 'tiny': 16, # Tiny text } def get_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont: # Try multiple font paths for cross-platform support font_paths = [ # macOS fonts "/System/Library/Fonts/Helvetica.ttc", "/System/Library/Fonts/SF-Pro.ttf", "/Library/Fonts/Arial Bold.ttf" if bold else "/Library/Fonts/Arial.ttf", # Linux fonts "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", # Windows fonts "C:\\Windows\\Fonts\\arialbd.ttf" if bold else "C:\\Windows\\Fonts\\arial.ttf", ] for font_path in font_paths: try: return ImageFont.truetype(font_path, size) except: continue # Ultimate fallback return ImageFont.load_default() def draw_text_with_outline( frame: Image.Image, text: str, position: tuple[int, int], font_size: int = 40, text_color: tuple[int, int, int] = (255, 255, 255), outline_color: tuple[int, int, int] = (0, 0, 0), outline_width: int = 3, centered: bool = False, bold: bool = True ) -> Image.Image: draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) # Calculate position for centering if centered: bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 position = (x, y) # Draw outline by drawing text multiple times offset in all directions x, y = position for offset_x in range(-outline_width, outline_width + 1): for offset_y in range(-outline_width, outline_width + 1): if offset_x != 0 or offset_y != 0: draw.text((x + offset_x, y + offset_y), text, fill=outline_color, font=font) # Draw main text on top draw.text(position, text, fill=text_color, font=font) return frame def draw_text_with_shadow( frame: Image.Image, text: str, position: tuple[int, int], font_size: int = 40, text_color: tuple[int, int, int] = (255, 255, 255), shadow_color: tuple[int, int, int] = (0, 0, 0), shadow_offset: tuple[int, int] = (3, 3), centered: bool = False, bold: bool = True ) -> Image.Image: draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) # Calculate position for centering if centered: bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 position = (x, y) # Draw shadow shadow_pos = (position[0] + shadow_offset[0], position[1] + shadow_offset[1]) draw.text(shadow_pos, text, fill=shadow_color, font=font) # Draw main text draw.text(position, text, fill=text_color, font=font) return frame def draw_text_with_glow( frame: Image.Image, text: str, position: tuple[int, int], font_size: int = 40, text_color: tuple[int, int, int] = (255, 255, 255), glow_color: tuple[int, int, int] = (255, 200, 0), glow_radius: int = 5, centered: bool = False, bold: bool = True ) -> Image.Image: draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) # Calculate position for centering if centered: bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 position = (x, y) # Draw glow layers with decreasing opacity (simulated with same color at different offsets) x, y = position for radius in range(glow_radius, 0, -1): for offset_x in range(-radius, radius + 1): for offset_y in range(-radius, radius + 1): if offset_x != 0 or offset_y != 0: draw.text((x + offset_x, y + offset_y), text, fill=glow_color, font=font) # Draw main text draw.text(position, text, fill=text_color, font=font) return frame def draw_text_in_box( frame: Image.Image, text: str, position: tuple[int, int], font_size: int = 40, text_color: tuple[int, int, int] = (255, 255, 255), box_color: tuple[int, int, int] = (0, 0, 0), box_alpha: float = 0.7, padding: int = 10, centered: bool = True, bold: bool = True ) -> Image.Image: # Create a separate layer for the box with alpha overlay = Image.new('RGBA', frame.size, (0, 0, 0, 0)) draw_overlay = ImageDraw.Draw(overlay) draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) # Get text dimensions bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] # Calculate box position if centered: box_x = position[0] - (text_width + padding * 2) // 2 box_y = position[1] - (text_height + padding * 2) // 2 text_x = position[0] - text_width // 2 text_y = position[1] - text_height // 2 else: box_x = position[0] - padding box_y = position[1] - padding text_x = position[0] text_y = position[1] # Draw semi-transparent box box_coords = [ box_x, box_y, box_x + text_width + padding * 2, box_y + text_height + padding * 2 ] alpha_value = int(255 * box_alpha) draw_overlay.rectangle(box_coords, fill=(*box_color, alpha_value)) # Composite overlay onto frame frame_rgba = frame.convert('RGBA') frame_rgba = Image.alpha_composite(frame_rgba, overlay) frame = frame_rgba.convert('RGB') # Draw text on top draw = ImageDraw.Draw(frame) draw.text((text_x, text_y), text, fill=text_color, font=font) return frame def get_text_size(text: str, font_size: int, bold: bool = True) -> tuple[int, int]: font = get_font(font_size, bold=bold) # Create temporary image to measure temp_img = Image.new('RGB', (1, 1)) draw = ImageDraw.Draw(temp_img) bbox = draw.textbbox((0, 0), text, font=font) width = bbox[2] - bbox[0] height = bbox[3] - bbox[1] return (width, height) def get_optimal_font_size(text: str, max_width: int, max_height: int, start_size: int = 60) -> int: font_size = start_size while font_size > 10: width, height = get_text_size(text, font_size) if width <= max_width and height <= max_height: return font_size font_size -= 2 return 10 # Minimum font size def scale_font_for_frame(base_size: int, frame_width: int, frame_height: int) -> int: # Use average dimension for scaling avg_dimension = (frame_width + frame_height) / 2 base_dimension = 480 # Reference dimension scale_factor = avg_dimension / base_dimension return max(10, int(base_size * scale_factor))
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +Typography System - Professional text rendering with outlines, shadows, and effects. + +This module provides high-quality text rendering that looks crisp and professional +in GIFs, with outlines for readability and effects for visual impact. +""" from PIL import Image, ImageDraw, ImageFont from typing import Optional @@ -17,6 +23,16 @@ def get_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont: + """ + Get a font with fallback support. + + Args: + size: Font size in pixels + bold: Use bold variant if available + + Returns: + ImageFont object + """ # Try multiple font paths for cross-platform support font_paths = [ # macOS fonts @@ -50,6 +66,26 @@ centered: bool = False, bold: bool = True ) -> Image.Image: + """ + Draw text with outline for maximum readability. + + This is THE most important function for professional-looking text in GIFs. + The outline ensures text is readable on any background. + + Args: + frame: PIL Image to draw on + text: Text to draw + position: (x, y) position + font_size: Font size in pixels + text_color: RGB color for text fill + outline_color: RGB color for outline + outline_width: Width of outline in pixels (2-4 recommended) + centered: If True, center text at position + bold: Use bold font variant + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) @@ -86,6 +122,23 @@ centered: bool = False, bold: bool = True ) -> Image.Image: + """ + Draw text with drop shadow for depth. + + Args: + frame: PIL Image to draw on + text: Text to draw + position: (x, y) position + font_size: Font size in pixels + text_color: RGB color for text + shadow_color: RGB color for shadow + shadow_offset: (x, y) offset for shadow + centered: If True, center text at position + bold: Use bold font variant + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) @@ -119,6 +172,23 @@ centered: bool = False, bold: bool = True ) -> Image.Image: + """ + Draw text with glow effect for emphasis. + + Args: + frame: PIL Image to draw on + text: Text to draw + position: (x, y) position + font_size: Font size in pixels + text_color: RGB color for text + glow_color: RGB color for glow + glow_radius: Radius of glow effect + centered: If True, center text at position + bold: Use bold font variant + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) font = get_font(font_size, bold=bold) @@ -157,6 +227,24 @@ centered: bool = True, bold: bool = True ) -> Image.Image: + """ + Draw text in a semi-transparent box for guaranteed readability. + + Args: + frame: PIL Image to draw on + text: Text to draw + position: (x, y) position + font_size: Font size in pixels + text_color: RGB color for text + box_color: RGB color for background box + box_alpha: Opacity of box (0.0-1.0) + padding: Padding around text in pixels + centered: If True, center at position + bold: Use bold font variant + + Returns: + Modified frame + """ # Create a separate layer for the box with alpha overlay = Image.new('RGBA', frame.size, (0, 0, 0, 0)) draw_overlay = ImageDraw.Draw(overlay) @@ -204,6 +292,17 @@ def get_text_size(text: str, font_size: int, bold: bool = True) -> tuple[int, int]: + """ + Get the dimensions of text without drawing it. + + Args: + text: Text to measure + font_size: Font size in pixels + bold: Use bold font variant + + Returns: + (width, height) tuple + """ font = get_font(font_size, bold=bold) # Create temporary image to measure temp_img = Image.new('RGB', (1, 1)) @@ -216,6 +315,18 @@ def get_optimal_font_size(text: str, max_width: int, max_height: int, start_size: int = 60) -> int: + """ + Find the largest font size that fits within given dimensions. + + Args: + text: Text to size + max_width: Maximum width in pixels + max_height: Maximum height in pixels + start_size: Starting font size to try + + Returns: + Optimal font size + """ font_size = start_size while font_size > 10: width, height = get_text_size(text, font_size) @@ -226,6 +337,19 @@ def scale_font_for_frame(base_size: int, frame_width: int, frame_height: int) -> int: + """ + Scale font size proportionally to frame dimensions. + + Useful for maintaining relative text size across different GIF dimensions. + + Args: + base_size: Base font size for 480x480 frame + frame_width: Actual frame width + frame_height: Actual frame height + + Returns: + Scaled font size + """ # Use average dimension for scaling avg_dimension = (frame_width + frame_height) / 2 base_dimension = 480 # Reference dimension
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/typography.py
Add docstrings to existing functions
#!/usr/bin/env python3 import html import random import shutil import tempfile from datetime import datetime, timezone from pathlib import Path from defusedxml import minidom from ooxml.scripts.pack import pack_document from ooxml.scripts.validation.docx import DOCXSchemaValidator from ooxml.scripts.validation.redlining import RedliningValidator from .utilities import XMLEditor # Path to template files TEMPLATE_DIR = Path(__file__).parent / "templates" class DocxXMLEditor(XMLEditor): def __init__( self, xml_path, rsid: str, author: str = "Claude", initials: str = "C" ): super().__init__(xml_path) self.rsid = rsid self.author = author self.initials = initials def _get_next_change_id(self): max_id = -1 for tag in ("w:ins", "w:del"): elements = self.dom.getElementsByTagName(tag) for elem in elements: change_id = elem.getAttribute("w:id") if change_id: try: max_id = max(max_id, int(change_id)) except ValueError: pass return max_id + 1 def _ensure_w16du_namespace(self): root = self.dom.documentElement if not root.hasAttribute("xmlns:w16du"): # type: ignore root.setAttribute( # type: ignore "xmlns:w16du", "http://schemas.microsoft.com/office/word/2023/wordml/word16du", ) def _ensure_w16cex_namespace(self): root = self.dom.documentElement if not root.hasAttribute("xmlns:w16cex"): # type: ignore root.setAttribute( # type: ignore "xmlns:w16cex", "http://schemas.microsoft.com/office/word/2018/wordml/cex", ) def _ensure_w14_namespace(self): root = self.dom.documentElement if not root.hasAttribute("xmlns:w14"): # type: ignore root.setAttribute( # type: ignore "xmlns:w14", "http://schemas.microsoft.com/office/word/2010/wordml", ) def _inject_attributes_to_nodes(self, nodes): from datetime import datetime, timezone timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def is_inside_deletion(elem): parent = elem.parentNode while parent: if parent.nodeType == parent.ELEMENT_NODE and parent.tagName == "w:del": return True parent = parent.parentNode return False def add_rsid_to_p(elem): if not elem.hasAttribute("w:rsidR"): elem.setAttribute("w:rsidR", self.rsid) if not elem.hasAttribute("w:rsidRDefault"): elem.setAttribute("w:rsidRDefault", self.rsid) if not elem.hasAttribute("w:rsidP"): elem.setAttribute("w:rsidP", self.rsid) # Add w14:paraId and w14:textId if not present if not elem.hasAttribute("w14:paraId"): self._ensure_w14_namespace() elem.setAttribute("w14:paraId", _generate_hex_id()) if not elem.hasAttribute("w14:textId"): self._ensure_w14_namespace() elem.setAttribute("w14:textId", _generate_hex_id()) def add_rsid_to_r(elem): # Use w:rsidDel for <w:r> inside <w:del>, otherwise w:rsidR if is_inside_deletion(elem): if not elem.hasAttribute("w:rsidDel"): elem.setAttribute("w:rsidDel", self.rsid) else: if not elem.hasAttribute("w:rsidR"): elem.setAttribute("w:rsidR", self.rsid) def add_tracked_change_attrs(elem): # Auto-assign w:id if not present if not elem.hasAttribute("w:id"): elem.setAttribute("w:id", str(self._get_next_change_id())) if not elem.hasAttribute("w:author"): elem.setAttribute("w:author", self.author) if not elem.hasAttribute("w:date"): elem.setAttribute("w:date", timestamp) # Add w16du:dateUtc for tracked changes (same as w:date since we generate UTC timestamps) if elem.tagName in ("w:ins", "w:del") and not elem.hasAttribute( "w16du:dateUtc" ): self._ensure_w16du_namespace() elem.setAttribute("w16du:dateUtc", timestamp) def add_comment_attrs(elem): if not elem.hasAttribute("w:author"): elem.setAttribute("w:author", self.author) if not elem.hasAttribute("w:date"): elem.setAttribute("w:date", timestamp) if not elem.hasAttribute("w:initials"): elem.setAttribute("w:initials", self.initials) def add_comment_extensible_date(elem): # Add w16cex:dateUtc for comment extensible elements if not elem.hasAttribute("w16cex:dateUtc"): self._ensure_w16cex_namespace() elem.setAttribute("w16cex:dateUtc", timestamp) def add_xml_space_to_t(elem): # Add xml:space="preserve" to w:t if text has leading/trailing whitespace if ( elem.firstChild and elem.firstChild.nodeType == elem.firstChild.TEXT_NODE ): text = elem.firstChild.data if text and (text[0].isspace() or text[-1].isspace()): if not elem.hasAttribute("xml:space"): elem.setAttribute("xml:space", "preserve") for node in nodes: if node.nodeType != node.ELEMENT_NODE: continue # Handle the node itself if node.tagName == "w:p": add_rsid_to_p(node) elif node.tagName == "w:r": add_rsid_to_r(node) elif node.tagName == "w:t": add_xml_space_to_t(node) elif node.tagName in ("w:ins", "w:del"): add_tracked_change_attrs(node) elif node.tagName == "w:comment": add_comment_attrs(node) elif node.tagName == "w16cex:commentExtensible": add_comment_extensible_date(node) # Process descendants (getElementsByTagName doesn't return the element itself) for elem in node.getElementsByTagName("w:p"): add_rsid_to_p(elem) for elem in node.getElementsByTagName("w:r"): add_rsid_to_r(elem) for elem in node.getElementsByTagName("w:t"): add_xml_space_to_t(elem) for tag in ("w:ins", "w:del"): for elem in node.getElementsByTagName(tag): add_tracked_change_attrs(elem) for elem in node.getElementsByTagName("w:comment"): add_comment_attrs(elem) for elem in node.getElementsByTagName("w16cex:commentExtensible"): add_comment_extensible_date(elem) def replace_node(self, elem, new_content): nodes = super().replace_node(elem, new_content) self._inject_attributes_to_nodes(nodes) return nodes def insert_after(self, elem, xml_content): nodes = super().insert_after(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def insert_before(self, elem, xml_content): nodes = super().insert_before(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def append_to(self, elem, xml_content): nodes = super().append_to(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def revert_insertion(self, elem): # Collect insertions ins_elements = [] if elem.tagName == "w:ins": ins_elements.append(elem) else: ins_elements.extend(elem.getElementsByTagName("w:ins")) # Validate that there are insertions to reject if not ins_elements: raise ValueError( f"revert_insertion requires w:ins elements. " f"The provided element <{elem.tagName}> contains no insertions. " ) # Process all insertions - wrap all children in w:del for ins_elem in ins_elements: runs = list(ins_elem.getElementsByTagName("w:r")) if not runs: continue # Create deletion wrapper del_wrapper = self.dom.createElement("w:del") # Process each run for run in runs: # Convert w:t → w:delText and w:rsidR → w:rsidDel if run.hasAttribute("w:rsidR"): run.setAttribute("w:rsidDel", run.getAttribute("w:rsidR")) run.removeAttribute("w:rsidR") elif not run.hasAttribute("w:rsidDel"): run.setAttribute("w:rsidDel", self.rsid) for t_elem in list(run.getElementsByTagName("w:t")): del_text = self.dom.createElement("w:delText") # Copy ALL child nodes (not just firstChild) to handle entities while t_elem.firstChild: del_text.appendChild(t_elem.firstChild) for i in range(t_elem.attributes.length): attr = t_elem.attributes.item(i) del_text.setAttribute(attr.name, attr.value) t_elem.parentNode.replaceChild(del_text, t_elem) # Move all children from ins to del wrapper while ins_elem.firstChild: del_wrapper.appendChild(ins_elem.firstChild) # Add del wrapper back to ins ins_elem.appendChild(del_wrapper) # Inject attributes to the deletion wrapper self._inject_attributes_to_nodes([del_wrapper]) return [elem] def revert_deletion(self, elem): # Collect deletions FIRST - before we modify the DOM del_elements = [] is_single_del = elem.tagName == "w:del" if is_single_del: del_elements.append(elem) else: del_elements.extend(elem.getElementsByTagName("w:del")) # Validate that there are deletions to reject if not del_elements: raise ValueError( f"revert_deletion requires w:del elements. " f"The provided element <{elem.tagName}> contains no deletions. " ) # Track created insertion (only relevant if elem is a single w:del) created_insertion = None # Process all deletions - create insertions that copy the deleted content for del_elem in del_elements: # Clone the deleted runs and convert them to insertions runs = list(del_elem.getElementsByTagName("w:r")) if not runs: continue # Create insertion wrapper ins_elem = self.dom.createElement("w:ins") for run in runs: # Clone the run new_run = run.cloneNode(True) # Convert w:delText → w:t for del_text in list(new_run.getElementsByTagName("w:delText")): t_elem = self.dom.createElement("w:t") # Copy ALL child nodes (not just firstChild) to handle entities while del_text.firstChild: t_elem.appendChild(del_text.firstChild) for i in range(del_text.attributes.length): attr = del_text.attributes.item(i) t_elem.setAttribute(attr.name, attr.value) del_text.parentNode.replaceChild(t_elem, del_text) # Update run attributes: w:rsidDel → w:rsidR if new_run.hasAttribute("w:rsidDel"): new_run.setAttribute("w:rsidR", new_run.getAttribute("w:rsidDel")) new_run.removeAttribute("w:rsidDel") elif not new_run.hasAttribute("w:rsidR"): new_run.setAttribute("w:rsidR", self.rsid) ins_elem.appendChild(new_run) # Insert the new insertion after the deletion nodes = self.insert_after(del_elem, ins_elem.toxml()) # If processing a single w:del, track the created insertion if is_single_del and nodes: created_insertion = nodes[0] # Return based on input type if is_single_del and created_insertion: return [elem, created_insertion] else: return [elem] @staticmethod def suggest_paragraph(xml_content: str) -> str: wrapper = f'<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{xml_content}</root>' doc = minidom.parseString(wrapper) para = doc.getElementsByTagName("w:p")[0] # Ensure w:pPr exists pPr_list = para.getElementsByTagName("w:pPr") if not pPr_list: pPr = doc.createElement("w:pPr") para.insertBefore( pPr, para.firstChild ) if para.firstChild else para.appendChild(pPr) else: pPr = pPr_list[0] # Ensure w:rPr exists in w:pPr rPr_list = pPr.getElementsByTagName("w:rPr") if not rPr_list: rPr = doc.createElement("w:rPr") pPr.appendChild(rPr) else: rPr = rPr_list[0] # Add <w:ins/> to w:rPr ins_marker = doc.createElement("w:ins") rPr.insertBefore( ins_marker, rPr.firstChild ) if rPr.firstChild else rPr.appendChild(ins_marker) # Wrap all non-pPr children in <w:ins> ins_wrapper = doc.createElement("w:ins") for child in [c for c in para.childNodes if c.nodeName != "w:pPr"]: para.removeChild(child) ins_wrapper.appendChild(child) para.appendChild(ins_wrapper) return para.toxml() def suggest_deletion(self, elem): if elem.nodeName == "w:r": # Check for existing w:delText if elem.getElementsByTagName("w:delText"): raise ValueError("w:r element already contains w:delText") # Convert w:t → w:delText for t_elem in list(elem.getElementsByTagName("w:t")): del_text = self.dom.createElement("w:delText") # Copy ALL child nodes (not just firstChild) to handle entities while t_elem.firstChild: del_text.appendChild(t_elem.firstChild) # Preserve attributes like xml:space for i in range(t_elem.attributes.length): attr = t_elem.attributes.item(i) del_text.setAttribute(attr.name, attr.value) t_elem.parentNode.replaceChild(del_text, t_elem) # Update run attributes: w:rsidR → w:rsidDel if elem.hasAttribute("w:rsidR"): elem.setAttribute("w:rsidDel", elem.getAttribute("w:rsidR")) elem.removeAttribute("w:rsidR") elif not elem.hasAttribute("w:rsidDel"): elem.setAttribute("w:rsidDel", self.rsid) # Wrap in w:del del_wrapper = self.dom.createElement("w:del") parent = elem.parentNode parent.insertBefore(del_wrapper, elem) parent.removeChild(elem) del_wrapper.appendChild(elem) # Inject attributes to the deletion wrapper self._inject_attributes_to_nodes([del_wrapper]) return del_wrapper elif elem.nodeName == "w:p": # Check for existing tracked changes if elem.getElementsByTagName("w:ins") or elem.getElementsByTagName("w:del"): raise ValueError("w:p element already contains tracked changes") # Check if it's a numbered list item pPr_list = elem.getElementsByTagName("w:pPr") is_numbered = pPr_list and pPr_list[0].getElementsByTagName("w:numPr") if is_numbered: # Add <w:del/> to w:rPr in w:pPr pPr = pPr_list[0] rPr_list = pPr.getElementsByTagName("w:rPr") if not rPr_list: rPr = self.dom.createElement("w:rPr") pPr.appendChild(rPr) else: rPr = rPr_list[0] # Add <w:del/> marker del_marker = self.dom.createElement("w:del") rPr.insertBefore( del_marker, rPr.firstChild ) if rPr.firstChild else rPr.appendChild(del_marker) # Convert w:t → w:delText in all runs for t_elem in list(elem.getElementsByTagName("w:t")): del_text = self.dom.createElement("w:delText") # Copy ALL child nodes (not just firstChild) to handle entities while t_elem.firstChild: del_text.appendChild(t_elem.firstChild) # Preserve attributes like xml:space for i in range(t_elem.attributes.length): attr = t_elem.attributes.item(i) del_text.setAttribute(attr.name, attr.value) t_elem.parentNode.replaceChild(del_text, t_elem) # Update run attributes: w:rsidR → w:rsidDel for run in elem.getElementsByTagName("w:r"): if run.hasAttribute("w:rsidR"): run.setAttribute("w:rsidDel", run.getAttribute("w:rsidR")) run.removeAttribute("w:rsidR") elif not run.hasAttribute("w:rsidDel"): run.setAttribute("w:rsidDel", self.rsid) # Wrap all non-pPr children in <w:del> del_wrapper = self.dom.createElement("w:del") for child in [c for c in elem.childNodes if c.nodeName != "w:pPr"]: elem.removeChild(child) del_wrapper.appendChild(child) elem.appendChild(del_wrapper) # Inject attributes to the deletion wrapper self._inject_attributes_to_nodes([del_wrapper]) return elem else: raise ValueError(f"Element must be w:r or w:p, got {elem.nodeName}") def _generate_hex_id() -> str: return f"{random.randint(1, 0x7FFFFFFE):08X}" def _generate_rsid() -> str: return "".join(random.choices("0123456789ABCDEF", k=8)) class Document: def __init__( self, unpacked_dir, rsid=None, track_revisions=False, author="Claude", initials="C", ): self.original_path = Path(unpacked_dir) if not self.original_path.exists() or not self.original_path.is_dir(): raise ValueError(f"Directory not found: {unpacked_dir}") # Create temporary directory with subdirectories for unpacked content and baseline self.temp_dir = tempfile.mkdtemp(prefix="docx_") self.unpacked_path = Path(self.temp_dir) / "unpacked" shutil.copytree(self.original_path, self.unpacked_path) # Pack original directory into temporary .docx for validation baseline (outside unpacked dir) self.original_docx = Path(self.temp_dir) / "original.docx" pack_document(self.original_path, self.original_docx, validate=False) self.word_path = self.unpacked_path / "word" # Generate RSID if not provided self.rsid = rsid if rsid else _generate_rsid() print(f"Using RSID: {self.rsid}") # Set default author and initials self.author = author self.initials = initials # Cache for lazy-loaded editors self._editors = {} # Comment file paths self.comments_path = self.word_path / "comments.xml" self.comments_extended_path = self.word_path / "commentsExtended.xml" self.comments_ids_path = self.word_path / "commentsIds.xml" self.comments_extensible_path = self.word_path / "commentsExtensible.xml" # Load existing comments and determine next ID (before setup modifies files) self.existing_comments = self._load_existing_comments() self.next_comment_id = self._get_next_comment_id() # Convenient access to document.xml editor (semi-private) self._document = self["word/document.xml"] # Setup tracked changes infrastructure self._setup_tracking(track_revisions=track_revisions) # Add author to people.xml self._add_author_to_people(author) def __getitem__(self, xml_path: str) -> DocxXMLEditor: if xml_path not in self._editors: file_path = self.unpacked_path / xml_path if not file_path.exists(): raise ValueError(f"XML file not found: {xml_path}") # Use DocxXMLEditor with RSID, author, and initials for all editors self._editors[xml_path] = DocxXMLEditor( file_path, rsid=self.rsid, author=self.author, initials=self.initials ) return self._editors[xml_path] def add_comment(self, start, end, text: str) -> int: comment_id = self.next_comment_id para_id = _generate_hex_id() durable_id = _generate_hex_id() timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") # Add comment ranges to document.xml immediately self._document.insert_before(start, self._comment_range_start_xml(comment_id)) # If end node is a paragraph, append comment markup inside it # Otherwise insert after it (for run-level anchors) if end.tagName == "w:p": self._document.append_to(end, self._comment_range_end_xml(comment_id)) else: self._document.insert_after(end, self._comment_range_end_xml(comment_id)) # Add to comments.xml immediately self._add_to_comments_xml( comment_id, para_id, text, self.author, self.initials, timestamp ) # Add to commentsExtended.xml immediately self._add_to_comments_extended_xml(para_id, parent_para_id=None) # Add to commentsIds.xml immediately self._add_to_comments_ids_xml(para_id, durable_id) # Add to commentsExtensible.xml immediately self._add_to_comments_extensible_xml(durable_id) # Update existing_comments so replies work self.existing_comments[comment_id] = {"para_id": para_id} self.next_comment_id += 1 return comment_id def reply_to_comment( self, parent_comment_id: int, text: str, ) -> int: if parent_comment_id not in self.existing_comments: raise ValueError(f"Parent comment with id={parent_comment_id} not found") parent_info = self.existing_comments[parent_comment_id] comment_id = self.next_comment_id para_id = _generate_hex_id() durable_id = _generate_hex_id() timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") # Add comment ranges to document.xml immediately parent_start_elem = self._document.get_node( tag="w:commentRangeStart", attrs={"w:id": str(parent_comment_id)} ) parent_ref_elem = self._document.get_node( tag="w:commentReference", attrs={"w:id": str(parent_comment_id)} ) self._document.insert_after( parent_start_elem, self._comment_range_start_xml(comment_id) ) parent_ref_run = parent_ref_elem.parentNode self._document.insert_after( parent_ref_run, f'<w:commentRangeEnd w:id="{comment_id}"/>' ) self._document.insert_after( parent_ref_run, self._comment_ref_run_xml(comment_id) ) # Add to comments.xml immediately self._add_to_comments_xml( comment_id, para_id, text, self.author, self.initials, timestamp ) # Add to commentsExtended.xml immediately (with parent) self._add_to_comments_extended_xml( para_id, parent_para_id=parent_info["para_id"] ) # Add to commentsIds.xml immediately self._add_to_comments_ids_xml(para_id, durable_id) # Add to commentsExtensible.xml immediately self._add_to_comments_extensible_xml(durable_id) # Update existing_comments so replies work self.existing_comments[comment_id] = {"para_id": para_id} self.next_comment_id += 1 return comment_id def __del__(self): if hasattr(self, "temp_dir") and Path(self.temp_dir).exists(): shutil.rmtree(self.temp_dir) def validate(self) -> None: # Create validators with current state schema_validator = DOCXSchemaValidator( self.unpacked_path, self.original_docx, verbose=False ) redlining_validator = RedliningValidator( self.unpacked_path, self.original_docx, verbose=False ) # Run validations if not schema_validator.validate(): raise ValueError("Schema validation failed") if not redlining_validator.validate(): raise ValueError("Redlining validation failed") def save(self, destination=None, validate=True) -> None: # Only ensure comment relationships and content types if comment files exist if self.comments_path.exists(): self._ensure_comment_relationships() self._ensure_comment_content_types() # Save all modified XML files in temp directory for editor in self._editors.values(): editor.save() # Validate by default if validate: self.validate() # Copy contents from temp directory to destination (or original directory) target_path = Path(destination) if destination else self.original_path shutil.copytree(self.unpacked_path, target_path, dirs_exist_ok=True) # ==================== Private: Initialization ==================== def _get_next_comment_id(self): if not self.comments_path.exists(): return 0 editor = self["word/comments.xml"] max_id = -1 for comment_elem in editor.dom.getElementsByTagName("w:comment"): comment_id = comment_elem.getAttribute("w:id") if comment_id: try: max_id = max(max_id, int(comment_id)) except ValueError: pass return max_id + 1 def _load_existing_comments(self): if not self.comments_path.exists(): return {} editor = self["word/comments.xml"] existing = {} for comment_elem in editor.dom.getElementsByTagName("w:comment"): comment_id = comment_elem.getAttribute("w:id") if not comment_id: continue # Find para_id from the w:p element within the comment para_id = None for p_elem in comment_elem.getElementsByTagName("w:p"): para_id = p_elem.getAttribute("w14:paraId") if para_id: break if not para_id: continue existing[int(comment_id)] = {"para_id": para_id} return existing # ==================== Private: Setup Methods ==================== def _setup_tracking(self, track_revisions=False): # Create or update word/people.xml people_file = self.word_path / "people.xml" self._update_people_xml(people_file) # Update XML files self._add_content_type_for_people(self.unpacked_path / "[Content_Types].xml") self._add_relationship_for_people( self.word_path / "_rels" / "document.xml.rels" ) # Always add RSID to settings.xml, optionally enable trackRevisions self._update_settings( self.word_path / "settings.xml", track_revisions=track_revisions ) def _update_people_xml(self, path): if not path.exists(): # Copy from template shutil.copy(TEMPLATE_DIR / "people.xml", path) def _add_content_type_for_people(self, path): editor = self["[Content_Types].xml"] if self._has_override(editor, "/word/people.xml"): return # Add Override element root = editor.dom.documentElement override_xml = '<Override PartName="/word/people.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.people+xml"/>' editor.append_to(root, override_xml) def _add_relationship_for_people(self, path): editor = self["word/_rels/document.xml.rels"] if self._has_relationship(editor, "people.xml"): return root = editor.dom.documentElement root_tag = root.tagName # type: ignore prefix = root_tag.split(":")[0] + ":" if ":" in root_tag else "" next_rid = editor.get_next_rid() # Create the relationship entry rel_xml = f'<{prefix}Relationship Id="{next_rid}" Type="http://schemas.microsoft.com/office/2011/relationships/people" Target="people.xml"/>' editor.append_to(root, rel_xml) def _update_settings(self, path, track_revisions=False): editor = self["word/settings.xml"] root = editor.get_node(tag="w:settings") prefix = root.tagName.split(":")[0] if ":" in root.tagName else "w" # Conditionally add trackRevisions if requested if track_revisions: track_revisions_exists = any( elem.tagName == f"{prefix}:trackRevisions" for elem in editor.dom.getElementsByTagName(f"{prefix}:trackRevisions") ) if not track_revisions_exists: track_rev_xml = f"<{prefix}:trackRevisions/>" # Try to insert before documentProtection, defaultTabStop, or at start inserted = False for tag in [f"{prefix}:documentProtection", f"{prefix}:defaultTabStop"]: elements = editor.dom.getElementsByTagName(tag) if elements: editor.insert_before(elements[0], track_rev_xml) inserted = True break if not inserted: # Insert as first child of settings if root.firstChild: editor.insert_before(root.firstChild, track_rev_xml) else: editor.append_to(root, track_rev_xml) # Always check if rsids section exists rsids_elements = editor.dom.getElementsByTagName(f"{prefix}:rsids") if not rsids_elements: # Add new rsids section rsids_xml = f'''<{prefix}:rsids> <{prefix}:rsidRoot {prefix}:val="{self.rsid}"/> <{prefix}:rsid {prefix}:val="{self.rsid}"/> </{prefix}:rsids>''' # Try to insert after compat, before clrSchemeMapping, or before closing tag inserted = False compat_elements = editor.dom.getElementsByTagName(f"{prefix}:compat") if compat_elements: editor.insert_after(compat_elements[0], rsids_xml) inserted = True if not inserted: clr_elements = editor.dom.getElementsByTagName( f"{prefix}:clrSchemeMapping" ) if clr_elements: editor.insert_before(clr_elements[0], rsids_xml) inserted = True if not inserted: editor.append_to(root, rsids_xml) else: # Check if this rsid already exists rsids_elem = rsids_elements[0] rsid_exists = any( elem.getAttribute(f"{prefix}:val") == self.rsid for elem in rsids_elem.getElementsByTagName(f"{prefix}:rsid") ) if not rsid_exists: rsid_xml = f'<{prefix}:rsid {prefix}:val="{self.rsid}"/>' editor.append_to(rsids_elem, rsid_xml) # ==================== Private: XML File Creation ==================== def _add_to_comments_xml( self, comment_id, para_id, text, author, initials, timestamp ): if not self.comments_path.exists(): shutil.copy(TEMPLATE_DIR / "comments.xml", self.comments_path) editor = self["word/comments.xml"] root = editor.get_node(tag="w:comments") escaped_text = ( text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") ) # Note: w:rsidR, w:rsidRDefault, w:rsidP on w:p, w:rsidR on w:r, # and w:author, w:date, w:initials on w:comment are automatically added by DocxXMLEditor comment_xml = f'''<w:comment w:id="{comment_id}"> <w:p w14:paraId="{para_id}" w14:textId="77777777"> <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:annotationRef/></w:r> <w:r><w:rPr><w:color w:val="000000"/><w:sz w:val="20"/><w:szCs w:val="20"/></w:rPr><w:t>{escaped_text}</w:t></w:r> </w:p> </w:comment>''' editor.append_to(root, comment_xml) def _add_to_comments_extended_xml(self, para_id, parent_para_id): if not self.comments_extended_path.exists(): shutil.copy( TEMPLATE_DIR / "commentsExtended.xml", self.comments_extended_path ) editor = self["word/commentsExtended.xml"] root = editor.get_node(tag="w15:commentsEx") if parent_para_id: xml = f'<w15:commentEx w15:paraId="{para_id}" w15:paraIdParent="{parent_para_id}" w15:done="0"/>' else: xml = f'<w15:commentEx w15:paraId="{para_id}" w15:done="0"/>' editor.append_to(root, xml) def _add_to_comments_ids_xml(self, para_id, durable_id): if not self.comments_ids_path.exists(): shutil.copy(TEMPLATE_DIR / "commentsIds.xml", self.comments_ids_path) editor = self["word/commentsIds.xml"] root = editor.get_node(tag="w16cid:commentsIds") xml = f'<w16cid:commentId w16cid:paraId="{para_id}" w16cid:durableId="{durable_id}"/>' editor.append_to(root, xml) def _add_to_comments_extensible_xml(self, durable_id): if not self.comments_extensible_path.exists(): shutil.copy( TEMPLATE_DIR / "commentsExtensible.xml", self.comments_extensible_path ) editor = self["word/commentsExtensible.xml"] root = editor.get_node(tag="w16cex:commentsExtensible") xml = f'<w16cex:commentExtensible w16cex:durableId="{durable_id}"/>' editor.append_to(root, xml) # ==================== Private: XML Fragments ==================== def _comment_range_start_xml(self, comment_id): return f'<w:commentRangeStart w:id="{comment_id}"/>' def _comment_range_end_xml(self, comment_id): return f'''<w:commentRangeEnd w:id="{comment_id}"/> <w:r> <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> <w:commentReference w:id="{comment_id}"/> </w:r>''' def _comment_ref_run_xml(self, comment_id): return f'''<w:r> <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> <w:commentReference w:id="{comment_id}"/> </w:r>''' # ==================== Private: Metadata Updates ==================== def _has_relationship(self, editor, target): for rel_elem in editor.dom.getElementsByTagName("Relationship"): if rel_elem.getAttribute("Target") == target: return True return False def _has_override(self, editor, part_name): for override_elem in editor.dom.getElementsByTagName("Override"): if override_elem.getAttribute("PartName") == part_name: return True return False def _has_author(self, editor, author): for person_elem in editor.dom.getElementsByTagName("w15:person"): if person_elem.getAttribute("w15:author") == author: return True return False def _add_author_to_people(self, author): people_path = self.word_path / "people.xml" # people.xml should already exist from _setup_tracking if not people_path.exists(): raise ValueError("people.xml should exist after _setup_tracking") editor = self["word/people.xml"] root = editor.get_node(tag="w15:people") # Check if author already exists if self._has_author(editor, author): return # Add author with proper XML escaping to prevent injection escaped_author = html.escape(author, quote=True) person_xml = f'''<w15:person w15:author="{escaped_author}"> <w15:presenceInfo w15:providerId="None" w15:userId="{escaped_author}"/> </w15:person>''' editor.append_to(root, person_xml) def _ensure_comment_relationships(self): editor = self["word/_rels/document.xml.rels"] if self._has_relationship(editor, "comments.xml"): return root = editor.dom.documentElement root_tag = root.tagName # type: ignore prefix = root_tag.split(":")[0] + ":" if ":" in root_tag else "" next_rid_num = int(editor.get_next_rid()[3:]) # Add relationship elements rels = [ ( next_rid_num, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", "comments.xml", ), ( next_rid_num + 1, "http://schemas.microsoft.com/office/2011/relationships/commentsExtended", "commentsExtended.xml", ), ( next_rid_num + 2, "http://schemas.microsoft.com/office/2016/09/relationships/commentsIds", "commentsIds.xml", ), ( next_rid_num + 3, "http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible", "commentsExtensible.xml", ), ] for rel_id, rel_type, target in rels: rel_xml = f'<{prefix}Relationship Id="rId{rel_id}" Type="{rel_type}" Target="{target}"/>' editor.append_to(root, rel_xml) def _ensure_comment_content_types(self): editor = self["[Content_Types].xml"] if self._has_override(editor, "/word/comments.xml"): return root = editor.dom.documentElement # Add Override elements overrides = [ ( "/word/comments.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml", ), ( "/word/commentsExtended.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml", ), ( "/word/commentsIds.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml", ), ( "/word/commentsExtensible.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml", ), ] for part_name, content_type in overrides: override_xml = ( f'<Override PartName="{part_name}" ContentType="{content_type}"/>' ) editor.append_to(root, override_xml)
--- +++ @@ -1,4 +1,30 @@ #!/usr/bin/env python3 +""" +Library for working with Word documents: comments, tracked changes, and editing. + +Usage: + from skills.docx.scripts.document import Document + + # Initialize + doc = Document('workspace/unpacked') + doc = Document('workspace/unpacked', author="John Doe", initials="JD") + + # Find nodes + node = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "1"}) + node = doc["word/document.xml"].get_node(tag="w:p", line_number=10) + + # Add comments + doc.add_comment(start=node, end=node, text="Comment text") + doc.reply_to_comment(parent_comment_id=0, text="Reply text") + + # Suggest tracked changes + doc["word/document.xml"].suggest_deletion(node) # Delete content + doc["word/document.xml"].revert_insertion(ins_node) # Reject insertion + doc["word/document.xml"].revert_deletion(del_node) # Reject deletion + + # Save + doc.save() +""" import html import random @@ -19,16 +45,35 @@ class DocxXMLEditor(XMLEditor): + """XMLEditor that automatically applies RSID, author, and date to new elements. + + Automatically adds attributes to elements that support them when inserting new content: + - w:rsidR, w:rsidRDefault, w:rsidP (for w:p and w:r elements) + - w:author and w:date (for w:ins, w:del, w:comment elements) + - w:id (for w:ins and w:del elements) + + Attributes: + dom (defusedxml.minidom.Document): The DOM document for direct manipulation + """ def __init__( self, xml_path, rsid: str, author: str = "Claude", initials: str = "C" ): + """Initialize with required RSID and optional author. + + Args: + xml_path: Path to XML file to edit + rsid: RSID to automatically apply to new elements + author: Author name for tracked changes and comments (default: "Claude") + initials: Author initials (default: "C") + """ super().__init__(xml_path) self.rsid = rsid self.author = author self.initials = initials def _get_next_change_id(self): + """Get the next available change ID by checking all tracked change elements.""" max_id = -1 for tag in ("w:ins", "w:del"): elements = self.dom.getElementsByTagName(tag) @@ -42,6 +87,7 @@ return max_id + 1 def _ensure_w16du_namespace(self): + """Ensure w16du namespace is declared on the root element.""" root = self.dom.documentElement if not root.hasAttribute("xmlns:w16du"): # type: ignore root.setAttribute( # type: ignore @@ -50,6 +96,7 @@ ) def _ensure_w16cex_namespace(self): + """Ensure w16cex namespace is declared on the root element.""" root = self.dom.documentElement if not root.hasAttribute("xmlns:w16cex"): # type: ignore root.setAttribute( # type: ignore @@ -58,6 +105,7 @@ ) def _ensure_w14_namespace(self): + """Ensure w14 namespace is declared on the root element.""" root = self.dom.documentElement if not root.hasAttribute("xmlns:w14"): # type: ignore root.setAttribute( # type: ignore @@ -66,11 +114,25 @@ ) def _inject_attributes_to_nodes(self, nodes): + """Inject RSID, author, and date attributes into DOM nodes where applicable. + + Adds attributes to elements that support them: + - w:r: gets w:rsidR (or w:rsidDel if inside w:del) + - w:p: gets w:rsidR, w:rsidRDefault, w:rsidP, w14:paraId, w14:textId + - w:t: gets xml:space="preserve" if text has leading/trailing whitespace + - w:ins, w:del: get w:id, w:author, w:date, w16du:dateUtc + - w:comment: gets w:author, w:date, w:initials + - w16cex:commentExtensible: gets w16cex:dateUtc + + Args: + nodes: List of DOM nodes to process + """ from datetime import datetime, timezone timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def is_inside_deletion(elem): + """Check if element is inside a w:del element.""" parent = elem.parentNode while parent: if parent.nodeType == parent.ELEMENT_NODE and parent.tagName == "w:del": @@ -176,26 +238,53 @@ add_comment_extensible_date(elem) def replace_node(self, elem, new_content): + """Replace node with automatic attribute injection.""" nodes = super().replace_node(elem, new_content) self._inject_attributes_to_nodes(nodes) return nodes def insert_after(self, elem, xml_content): + """Insert after with automatic attribute injection.""" nodes = super().insert_after(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def insert_before(self, elem, xml_content): + """Insert before with automatic attribute injection.""" nodes = super().insert_before(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def append_to(self, elem, xml_content): + """Append to with automatic attribute injection.""" nodes = super().append_to(elem, xml_content) self._inject_attributes_to_nodes(nodes) return nodes def revert_insertion(self, elem): + """Reject an insertion by wrapping its content in a deletion. + + Wraps all runs inside w:ins in w:del, converting w:t to w:delText. + Can process a single w:ins element or a container element with multiple w:ins. + + Args: + elem: Element to process (w:ins, w:p, w:body, etc.) + + Returns: + list: List containing the processed element(s) + + Raises: + ValueError: If the element contains no w:ins elements + + Example: + # Reject a single insertion + ins = doc["word/document.xml"].get_node(tag="w:ins", attrs={"w:id": "5"}) + doc["word/document.xml"].revert_insertion(ins) + + # Reject all insertions in a paragraph + para = doc["word/document.xml"].get_node(tag="w:p", line_number=42) + doc["word/document.xml"].revert_insertion(para) + """ # Collect insertions ins_elements = [] if elem.tagName == "w:ins": @@ -251,6 +340,30 @@ return [elem] def revert_deletion(self, elem): + """Reject a deletion by re-inserting the deleted content. + + Creates w:ins elements after each w:del, copying deleted content and + converting w:delText back to w:t. + Can process a single w:del element or a container element with multiple w:del. + + Args: + elem: Element to process (w:del, w:p, w:body, etc.) + + Returns: + list: If elem is w:del, returns [elem, new_ins]. Otherwise returns [elem]. + + Raises: + ValueError: If the element contains no w:del elements + + Example: + # Reject a single deletion - returns [w:del, w:ins] + del_elem = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "3"}) + nodes = doc["word/document.xml"].revert_deletion(del_elem) + + # Reject all deletions in a paragraph - returns [para] + para = doc["word/document.xml"].get_node(tag="w:p", line_number=42) + nodes = doc["word/document.xml"].revert_deletion(para) + """ # Collect deletions FIRST - before we modify the DOM del_elements = [] is_single_del = elem.tagName == "w:del" @@ -319,6 +432,16 @@ @staticmethod def suggest_paragraph(xml_content: str) -> str: + """Transform paragraph XML to add tracked change wrapping for insertion. + + Wraps runs in <w:ins> and adds <w:ins/> to w:rPr in w:pPr for numbered lists. + + Args: + xml_content: XML string containing a <w:p> element + + Returns: + str: Transformed XML with tracked change wrapping + """ wrapper = f'<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{xml_content}</root>' doc = minidom.parseString(wrapper) para = doc.getElementsByTagName("w:p")[0] @@ -357,6 +480,21 @@ return para.toxml() def suggest_deletion(self, elem): + """Mark a w:r or w:p element as deleted with tracked changes (in-place DOM manipulation). + + For w:r: wraps in <w:del>, converts <w:t> to <w:delText>, preserves w:rPr + For w:p (regular): wraps content in <w:del>, converts <w:t> to <w:delText> + For w:p (numbered list): adds <w:del/> to w:rPr in w:pPr, wraps content in <w:del> + + Args: + elem: A w:r or w:p DOM element without existing tracked changes + + Returns: + Element: The modified element + + Raises: + ValueError: If element has existing tracked changes or invalid structure + """ if elem.nodeName == "w:r": # Check for existing w:delText if elem.getElementsByTagName("w:delText"): @@ -456,14 +594,23 @@ def _generate_hex_id() -> str: + """Generate random 8-character hex ID for para/durable IDs. + + Values are constrained to be less than 0x7FFFFFFF per OOXML spec: + - paraId must be < 0x80000000 + - durableId must be < 0x7FFFFFFF + We use the stricter constraint (0x7FFFFFFF) for both. + """ return f"{random.randint(1, 0x7FFFFFFE):08X}" def _generate_rsid() -> str: + """Generate random 8-character hex RSID.""" return "".join(random.choices("0123456789ABCDEF", k=8)) class Document: + """Manages comments in unpacked Word documents.""" def __init__( self, @@ -473,6 +620,17 @@ author="Claude", initials="C", ): + """ + Initialize with path to unpacked Word document directory. + Automatically sets up comment infrastructure (people.xml, RSIDs). + + Args: + unpacked_dir: Path to unpacked DOCX directory (must contain word/ subdirectory) + rsid: Optional RSID to use for all comment elements. If not provided, one will be generated. + track_revisions: If True, enables track revisions in settings.xml (default: False) + author: Default author name for comments (default: "Claude") + initials: Default author initials for comments (default: "C") + """ self.original_path = Path(unpacked_dir) if not self.original_path.exists() or not self.original_path.is_dir(): @@ -520,6 +678,28 @@ self._add_author_to_people(author) def __getitem__(self, xml_path: str) -> DocxXMLEditor: + """ + Get or create a DocxXMLEditor for the specified XML file. + + Enables lazy-loaded editors with bracket notation: + node = doc["word/document.xml"].get_node(tag="w:p", line_number=42) + + Args: + xml_path: Relative path to XML file (e.g., "word/document.xml", "word/comments.xml") + + Returns: + DocxXMLEditor instance for the specified file + + Raises: + ValueError: If the file does not exist + + Example: + # Get node from document.xml + node = doc["word/document.xml"].get_node(tag="w:del", attrs={"w:id": "1"}) + + # Get node from comments.xml + comment = doc["word/comments.xml"].get_node(tag="w:comment", attrs={"w:id": "0"}) + """ if xml_path not in self._editors: file_path = self.unpacked_path / xml_path if not file_path.exists(): @@ -531,6 +711,22 @@ return self._editors[xml_path] def add_comment(self, start, end, text: str) -> int: + """ + Add a comment spanning from one element to another. + + Args: + start: DOM element for the starting point + end: DOM element for the ending point + text: Comment content + + Returns: + The comment ID that was created + + Example: + start_node = cm.get_document_node(tag="w:del", id="1") + end_node = cm.get_document_node(tag="w:ins", id="2") + cm.add_comment(start=start_node, end=end_node, text="Explanation") + """ comment_id = self.next_comment_id para_id = _generate_hex_id() durable_id = _generate_hex_id() @@ -571,6 +767,19 @@ parent_comment_id: int, text: str, ) -> int: + """ + Add a reply to an existing comment. + + Args: + parent_comment_id: The w:id of the parent comment to reply to + text: Reply text + + Returns: + The comment ID that was created for the reply + + Example: + cm.reply_to_comment(parent_comment_id=0, text="I agree with this change") + """ if parent_comment_id not in self.existing_comments: raise ValueError(f"Parent comment with id={parent_comment_id} not found") @@ -622,10 +831,17 @@ return comment_id def __del__(self): + """Clean up temporary directory on deletion.""" if hasattr(self, "temp_dir") and Path(self.temp_dir).exists(): shutil.rmtree(self.temp_dir) def validate(self) -> None: + """ + Validate the document against XSD schema and redlining rules. + + Raises: + ValueError: If validation fails. + """ # Create validators with current state schema_validator = DOCXSchemaValidator( self.unpacked_path, self.original_docx, verbose=False @@ -641,6 +857,15 @@ raise ValueError("Redlining validation failed") def save(self, destination=None, validate=True) -> None: + """ + Save all modified XML files to disk and copy to destination directory. + + This persists all changes made via add_comment() and reply_to_comment(). + + Args: + destination: Optional path to save to. If None, saves back to original directory. + validate: If True, validates document before saving (default: True). + """ # Only ensure comment relationships and content types if comment files exist if self.comments_path.exists(): self._ensure_comment_relationships() @@ -661,6 +886,7 @@ # ==================== Private: Initialization ==================== def _get_next_comment_id(self): + """Get the next available comment ID.""" if not self.comments_path.exists(): return 0 @@ -676,6 +902,7 @@ return max_id + 1 def _load_existing_comments(self): + """Load existing comments from files to enable replies.""" if not self.comments_path.exists(): return {} @@ -704,6 +931,11 @@ # ==================== Private: Setup Methods ==================== def _setup_tracking(self, track_revisions=False): + """Set up comment infrastructure in unpacked directory. + + Args: + track_revisions: If True, enables track revisions in settings.xml + """ # Create or update word/people.xml people_file = self.word_path / "people.xml" self._update_people_xml(people_file) @@ -720,11 +952,13 @@ ) def _update_people_xml(self, path): + """Create people.xml if it doesn't exist.""" if not path.exists(): # Copy from template shutil.copy(TEMPLATE_DIR / "people.xml", path) def _add_content_type_for_people(self, path): + """Add people.xml content type to [Content_Types].xml if not already present.""" editor = self["[Content_Types].xml"] if self._has_override(editor, "/word/people.xml"): @@ -736,6 +970,7 @@ editor.append_to(root, override_xml) def _add_relationship_for_people(self, path): + """Add people.xml relationship to document.xml.rels if not already present.""" editor = self["word/_rels/document.xml.rels"] if self._has_relationship(editor, "people.xml"): @@ -751,6 +986,16 @@ editor.append_to(root, rel_xml) def _update_settings(self, path, track_revisions=False): + """Add RSID and optionally enable track revisions in settings.xml. + + Args: + path: Path to settings.xml + track_revisions: If True, adds trackRevisions element + + Places elements per OOXML schema order: + - trackRevisions: early (before defaultTabStop) + - rsids: late (after compat) + """ editor = self["word/settings.xml"] root = editor.get_node(tag="w:settings") prefix = root.tagName.split(":")[0] if ":" in root.tagName else "w" @@ -823,6 +1068,7 @@ def _add_to_comments_xml( self, comment_id, para_id, text, author, initials, timestamp ): + """Add a single comment to comments.xml.""" if not self.comments_path.exists(): shutil.copy(TEMPLATE_DIR / "comments.xml", self.comments_path) @@ -843,6 +1089,7 @@ editor.append_to(root, comment_xml) def _add_to_comments_extended_xml(self, para_id, parent_para_id): + """Add a single comment to commentsExtended.xml.""" if not self.comments_extended_path.exists(): shutil.copy( TEMPLATE_DIR / "commentsExtended.xml", self.comments_extended_path @@ -858,6 +1105,7 @@ editor.append_to(root, xml) def _add_to_comments_ids_xml(self, para_id, durable_id): + """Add a single comment to commentsIds.xml.""" if not self.comments_ids_path.exists(): shutil.copy(TEMPLATE_DIR / "commentsIds.xml", self.comments_ids_path) @@ -868,6 +1116,7 @@ editor.append_to(root, xml) def _add_to_comments_extensible_xml(self, durable_id): + """Add a single comment to commentsExtensible.xml.""" if not self.comments_extensible_path.exists(): shutil.copy( TEMPLATE_DIR / "commentsExtensible.xml", self.comments_extensible_path @@ -882,9 +1131,14 @@ # ==================== Private: XML Fragments ==================== def _comment_range_start_xml(self, comment_id): + """Generate XML for comment range start.""" return f'<w:commentRangeStart w:id="{comment_id}"/>' def _comment_range_end_xml(self, comment_id): + """Generate XML for comment range end with reference run. + + Note: w:rsidR is automatically added by DocxXMLEditor. + """ return f'''<w:commentRangeEnd w:id="{comment_id}"/> <w:r> <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> @@ -892,6 +1146,10 @@ </w:r>''' def _comment_ref_run_xml(self, comment_id): + """Generate XML for comment reference run. + + Note: w:rsidR is automatically added by DocxXMLEditor. + """ return f'''<w:r> <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> <w:commentReference w:id="{comment_id}"/> @@ -900,24 +1158,28 @@ # ==================== Private: Metadata Updates ==================== def _has_relationship(self, editor, target): + """Check if a relationship with given target exists.""" for rel_elem in editor.dom.getElementsByTagName("Relationship"): if rel_elem.getAttribute("Target") == target: return True return False def _has_override(self, editor, part_name): + """Check if an override with given part name exists.""" for override_elem in editor.dom.getElementsByTagName("Override"): if override_elem.getAttribute("PartName") == part_name: return True return False def _has_author(self, editor, author): + """Check if an author already exists in people.xml.""" for person_elem in editor.dom.getElementsByTagName("w15:person"): if person_elem.getAttribute("w15:author") == author: return True return False def _add_author_to_people(self, author): + """Add author to people.xml (called during initialization).""" people_path = self.word_path / "people.xml" # people.xml should already exist from _setup_tracking @@ -939,6 +1201,7 @@ editor.append_to(root, person_xml) def _ensure_comment_relationships(self): + """Ensure word/_rels/document.xml.rels has comment relationships.""" editor = self["word/_rels/document.xml.rels"] if self._has_relationship(editor, "comments.xml"): @@ -978,6 +1241,7 @@ editor.append_to(root, rel_xml) def _ensure_comment_content_types(self): + """Ensure [Content_Types].xml has comment content types.""" editor = self["[Content_Types].xml"] if self._has_override(editor, "/word/comments.xml"): @@ -1009,4 +1273,4 @@ override_xml = ( f'<Override PartName="{part_name}" ContentType="{content_type}"/>' ) - editor.append_to(root, override_xml)+ editor.append_to(root, override_xml)
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/docx/scripts/document.py
Add docstrings to improve collaboration
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image, ImageFilter from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced from core.easing import interpolate def create_zoom_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 30, zoom_type: str = 'in', # 'in', 'out', 'in_out', 'punch' scale_range: tuple[float, float] = (0.1, 2.0), easing: str = 'ease_out', add_motion_blur: bool = False, center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] # Default object data if object_data is None: if object_type == 'emoji': object_data = {'emoji': '🔍', 'size': 100} base_size = object_data.get('size', 100) if object_type == 'emoji' else object_data.get('font_size', 60) start_scale, end_scale = scale_range for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 # Calculate scale based on zoom type if zoom_type == 'in': scale = interpolate(start_scale, end_scale, t, easing) elif zoom_type == 'out': scale = interpolate(end_scale, start_scale, t, easing) elif zoom_type == 'in_out': if t < 0.5: scale = interpolate(start_scale, end_scale, t * 2, easing) else: scale = interpolate(end_scale, start_scale, (t - 0.5) * 2, easing) elif zoom_type == 'punch': # Quick zoom in with overshoot then settle if t < 0.3: scale = interpolate(start_scale, end_scale * 1.2, t / 0.3, 'ease_out') else: scale = interpolate(end_scale * 1.2, end_scale, (t - 0.3) / 0.7, 'elastic_out') else: scale = interpolate(start_scale, end_scale, t, easing) # Create frame frame = create_blank_frame(frame_width, frame_height, bg_color) if object_type == 'emoji': current_size = int(base_size * scale) # Clamp size to reasonable bounds current_size = max(12, min(current_size, frame_width * 2)) # Create emoji on transparent background canvas_size = max(frame_width, frame_height, current_size) * 2 emoji_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji=object_data['emoji'], position=(canvas_size // 2 - current_size // 2, canvas_size // 2 - current_size // 2), size=current_size, shadow=False ) # Optional motion blur for fast zooms if add_motion_blur and abs(scale - 1.0) > 0.5: blur_amount = min(5, int(abs(scale - 1.0) * 3)) emoji_canvas = emoji_canvas.filter(ImageFilter.GaussianBlur(blur_amount)) # Crop to frame size centered left = (canvas_size - frame_width) // 2 top = (canvas_size - frame_height) // 2 emoji_cropped = emoji_canvas.crop((left, top, left + frame_width, top + frame_height)) # Composite frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, emoji_cropped) frame = frame.convert('RGB') elif object_type == 'text': from core.typography import draw_text_with_outline current_size = int(base_size * scale) current_size = max(10, min(current_size, 500)) # Create oversized canvas for large text canvas_size = max(frame_width, frame_height, current_size * 10) text_canvas = Image.new('RGB', (canvas_size, canvas_size), bg_color) draw_text_with_outline( text_canvas, text=object_data.get('text', 'ZOOM'), position=(canvas_size // 2, canvas_size // 2), font_size=current_size, text_color=object_data.get('text_color', (0, 0, 0)), outline_color=object_data.get('outline_color', (255, 255, 255)), outline_width=max(2, int(current_size * 0.05)), centered=True ) # Crop to frame left = (canvas_size - frame_width) // 2 top = (canvas_size - frame_height) // 2 frame = text_canvas.crop((left, top, left + frame_width, top + frame_height)) frames.append(frame) return frames def create_explosion_zoom( emoji: str = '💥', num_frames: int = 20, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 # Exponential zoom scale = 0.1 * math.exp(t * 5) # Add rotation for drama angle = t * 360 * 2 frame = create_blank_frame(frame_width, frame_height, bg_color) current_size = int(100 * scale) current_size = max(12, min(current_size, frame_width * 3)) # Create emoji canvas_size = max(frame_width, frame_height, current_size) * 2 emoji_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji=emoji, position=(canvas_size // 2 - current_size // 2, canvas_size // 2 - current_size // 2), size=current_size, shadow=False ) # Rotate emoji_canvas = emoji_canvas.rotate(angle, center=(canvas_size // 2, canvas_size // 2), resample=Image.BICUBIC) # Add motion blur for later frames if t > 0.5: blur_amount = int((t - 0.5) * 10) emoji_canvas = emoji_canvas.filter(ImageFilter.GaussianBlur(blur_amount)) # Crop and composite left = (canvas_size - frame_width) // 2 top = (canvas_size - frame_height) // 2 emoji_cropped = emoji_canvas.crop((left, top, left + frame_width, top + frame_height)) frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, emoji_cropped) frame = frame.convert('RGB') frames.append(frame) return frames def create_mind_blown_zoom( emoji: str = '🤯', num_frames: int = 30, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 # Zoom in then shake if t < 0.5: scale = interpolate(0.3, 1.2, t * 2, 'ease_out') shake_x = 0 shake_y = 0 else: scale = 1.2 # Shake intensifies shake_intensity = (t - 0.5) * 40 shake_x = int(math.sin(t * 50) * shake_intensity) shake_y = int(math.cos(t * 45) * shake_intensity) frame = create_blank_frame(frame_width, frame_height, bg_color) current_size = int(100 * scale) center_x = frame_width // 2 + shake_x center_y = frame_height // 2 + shake_y emoji_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji=emoji, position=(center_x - current_size // 2, center_y - current_size // 2), size=current_size, shadow=False ) frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, emoji_canvas) frame = frame.convert('RGB') frames.append(frame) return frames # Example usage if __name__ == '__main__': print("Creating zoom animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Zoom in frames = create_zoom_animation( object_type='emoji', object_data={'emoji': '🔍', 'size': 100}, num_frames=30, zoom_type='in', scale_range=(0.1, 1.5), easing='ease_out' ) builder.add_frames(frames) builder.save('zoom_in.gif', num_colors=128) # Example 2: Explosion zoom builder.clear() frames = create_explosion_zoom(emoji='💥', num_frames=20) builder.add_frames(frames) builder.save('zoom_explosion.gif', num_colors=128) # Example 3: Mind blown builder.clear() frames = create_mind_blown_zoom(emoji='🤯', num_frames=30) builder.add_frames(frames) builder.save('zoom_mind_blown.gif', num_colors=128) print("Created zoom animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Zoom Animation - Scale objects dramatically for emphasis. + +Creates zoom in, zoom out, and dramatic scaling effects. +""" import sys from pathlib import Path @@ -25,6 +30,25 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create zoom animation. + + Args: + object_type: 'emoji', 'text', 'image' + object_data: Object configuration + num_frames: Number of frames + zoom_type: Type of zoom effect + scale_range: (start_scale, end_scale) tuple + easing: Easing function + add_motion_blur: Add blur for speed effect + center_pos: Center position + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -131,6 +155,19 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create dramatic explosion zoom effect. + + Args: + emoji: Emoji to explode + num_frames: Number of frames + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] for i in range(num_frames): @@ -188,6 +225,19 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create "mind blown" dramatic zoom with shake. + + Args: + emoji: Emoji to use + num_frames: Number of frames + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] for i in range(num_frames): @@ -259,4 +309,4 @@ builder.add_frames(frames) builder.save('zoom_mind_blown.gif', num_colors=128) - print("Created zoom animations!")+ print("Created zoom animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/zoom.py
Write clean docstrings for readability
#!/usr/bin/env python3 import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image import numpy as np from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced, draw_circle from core.easing import interpolate def create_morph_animation( object1_data: dict, object2_data: dict, num_frames: int = 30, morph_type: str = 'crossfade', # 'crossfade', 'scale', 'spin_morph' easing: str = 'ease_in_out', object_type: str = 'emoji', center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 frame = create_blank_frame(frame_width, frame_height, bg_color) if morph_type == 'crossfade': # Simple crossfade between two objects opacity1 = interpolate(1, 0, t, easing) opacity2 = interpolate(0, 1, t, easing) if object_type == 'emoji': # Create first emoji emoji1_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) size1 = object1_data['size'] draw_emoji_enhanced( emoji1_canvas, emoji=object1_data['emoji'], position=(center_pos[0] - size1 // 2, center_pos[1] - size1 // 2), size=size1, shadow=False ) # Apply opacity from templates.fade import apply_opacity emoji1_canvas = apply_opacity(emoji1_canvas, opacity1) # Create second emoji emoji2_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) size2 = object2_data['size'] draw_emoji_enhanced( emoji2_canvas, emoji=object2_data['emoji'], position=(center_pos[0] - size2 // 2, center_pos[1] - size2 // 2), size=size2, shadow=False ) emoji2_canvas = apply_opacity(emoji2_canvas, opacity2) # Composite both frame_rgba = frame.convert('RGBA') frame_rgba = Image.alpha_composite(frame_rgba, emoji1_canvas) frame_rgba = Image.alpha_composite(frame_rgba, emoji2_canvas) frame = frame_rgba.convert('RGB') elif object_type == 'circle': # Morph between two circles radius1 = object1_data['radius'] radius2 = object2_data['radius'] color1 = object1_data['color'] color2 = object2_data['color'] # Interpolate properties current_radius = int(interpolate(radius1, radius2, t, easing)) current_color = tuple( int(interpolate(color1[i], color2[i], t, easing)) for i in range(3) ) draw_circle(frame, center_pos, current_radius, fill_color=current_color) elif morph_type == 'scale': # First object scales down as second scales up if object_type == 'emoji': scale1 = interpolate(1.0, 0.0, t, easing) scale2 = interpolate(0.0, 1.0, t, easing) # Draw first emoji (shrinking) if scale1 > 0.05: size1 = int(object1_data['size'] * scale1) size1 = max(12, size1) emoji1_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) draw_emoji_enhanced( emoji1_canvas, emoji=object1_data['emoji'], position=(center_pos[0] - size1 // 2, center_pos[1] - size1 // 2), size=size1, shadow=False ) frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, emoji1_canvas) frame = frame.convert('RGB') # Draw second emoji (growing) if scale2 > 0.05: size2 = int(object2_data['size'] * scale2) size2 = max(12, size2) emoji2_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) draw_emoji_enhanced( emoji2_canvas, emoji=object2_data['emoji'], position=(center_pos[0] - size2 // 2, center_pos[1] - size2 // 2), size=size2, shadow=False ) frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, emoji2_canvas) frame = frame.convert('RGB') elif morph_type == 'spin_morph': # Spin while morphing (flip-like) import math # Calculate rotation (0 to 180 degrees) angle = interpolate(0, 180, t, easing) scale_factor = abs(math.cos(math.radians(angle))) # Determine which object to show if angle < 90: current_object = object1_data else: current_object = object2_data # Skip when edge-on if scale_factor < 0.05: frames.append(frame) continue if object_type == 'emoji': size = current_object['size'] canvas_size = size * 2 emoji_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji=current_object['emoji'], position=(canvas_size // 2 - size // 2, canvas_size // 2 - size // 2), size=size, shadow=False ) # Scale horizontally for spin effect new_width = max(1, int(canvas_size * scale_factor)) emoji_scaled = emoji_canvas.resize((new_width, canvas_size), Image.LANCZOS) paste_x = center_pos[0] - new_width // 2 paste_y = center_pos[1] - canvas_size // 2 frame_rgba = frame.convert('RGBA') frame_rgba.paste(emoji_scaled, (paste_x, paste_y), emoji_scaled) frame = frame_rgba.convert('RGB') frames.append(frame) return frames def create_reaction_morph( emoji_start: str, emoji_end: str, num_frames: int = 20, frame_size: int = 128 ) -> list[Image.Image]: return create_morph_animation( object1_data={'emoji': emoji_start, 'size': 80}, object2_data={'emoji': emoji_end, 'size': 80}, num_frames=num_frames, morph_type='crossfade', easing='ease_in_out', object_type='emoji', center_pos=(frame_size // 2, frame_size // 2), frame_width=frame_size, frame_height=frame_size, bg_color=(255, 255, 255) ) def create_shape_morph( shapes: list[dict], num_frames: int = 60, frames_per_shape: int = 20, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] center = (frame_width // 2, frame_height // 2) for i in range(num_frames): # Determine which shapes we're morphing between cycle_progress = (i % (frames_per_shape * len(shapes))) / frames_per_shape shape_idx = int(cycle_progress) % len(shapes) next_shape_idx = (shape_idx + 1) % len(shapes) # Progress between these two shapes t = cycle_progress - shape_idx shape1 = shapes[shape_idx] shape2 = shapes[next_shape_idx] # Interpolate properties radius = int(interpolate(shape1['radius'], shape2['radius'], t, 'ease_in_out')) color = tuple( int(interpolate(shape1['color'][j], shape2['color'][j], t, 'ease_in_out')) for j in range(3) ) # Draw frame frame = create_blank_frame(frame_width, frame_height, bg_color) draw_circle(frame, center, radius, fill_color=color) frames.append(frame) return frames # Example usage if __name__ == '__main__': print("Creating morph animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Crossfade morph frames = create_morph_animation( object1_data={'emoji': '😊', 'size': 100}, object2_data={'emoji': '😂', 'size': 100}, num_frames=30, morph_type='crossfade', object_type='emoji' ) builder.add_frames(frames) builder.save('morph_crossfade.gif', num_colors=128) # Example 2: Scale morph builder.clear() frames = create_morph_animation( object1_data={'emoji': '🌙', 'size': 100}, object2_data={'emoji': '☀️', 'size': 100}, num_frames=40, morph_type='scale', object_type='emoji' ) builder.add_frames(frames) builder.save('morph_scale.gif', num_colors=128) # Example 3: Shape morph cycle builder.clear() from core.color_palettes import get_palette palette = get_palette('vibrant') shapes = [ {'radius': 60, 'color': palette['primary']}, {'radius': 80, 'color': palette['secondary']}, {'radius': 50, 'color': palette['accent']}, {'radius': 70, 'color': palette['success']} ] frames = create_shape_morph(shapes, num_frames=80, frames_per_shape=20) builder.add_frames(frames) builder.save('morph_shapes.gif', num_colors=64) print("Created morph animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Morph Animation - Transform between different emojis or shapes. + +Creates smooth transitions and transformations. +""" import sys from pathlib import Path @@ -24,6 +29,24 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create morphing animation between two objects. + + Args: + object1_data: First object configuration + object2_data: Second object configuration + num_frames: Number of frames + morph_type: Type of morph effect + easing: Easing function + object_type: Type of objects + center_pos: Center position + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] for i in range(num_frames): @@ -180,6 +203,18 @@ num_frames: int = 20, frame_size: int = 128 ) -> list[Image.Image]: + """ + Create quick emoji reaction morph (for emoji GIFs). + + Args: + emoji_start: Starting emoji + emoji_end: Ending emoji + num_frames: Number of frames + frame_size: Frame size (square) + + Returns: + List of frames + """ return create_morph_animation( object1_data={'emoji': emoji_start, 'size': 80}, object2_data={'emoji': emoji_end, 'size': 80}, @@ -202,6 +237,20 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Morph through a sequence of shapes. + + Args: + shapes: List of shape dicts with 'radius' and 'color' + num_frames: Total number of frames + frames_per_shape: Frames to spend on each morph + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] center = (frame_width // 2, frame_height // 2) @@ -277,4 +326,4 @@ builder.add_frames(frames) builder.save('morph_shapes.gif', num_colors=64) - print("Created morph animations!")+ print("Created morph animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/morph.py
Improve documentation using docstrings
#!/usr/bin/env python3 import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced from core.easing import interpolate def create_slide_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 30, direction: str = 'left', # 'left', 'right', 'top', 'bottom' slide_type: str = 'in', # 'in', 'out', 'across' easing: str = 'ease_out', overshoot: bool = False, final_pos: tuple[int, int] | None = None, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] # Default object data if object_data is None: if object_type == 'emoji': object_data = {'emoji': '➡️', 'size': 100} if final_pos is None: final_pos = (frame_width // 2, frame_height // 2) # Calculate start and end positions based on direction size = object_data.get('size', 100) if object_type == 'emoji' else 100 margin = size if direction == 'left': start_pos = (-margin, final_pos[1]) end_pos = final_pos if slide_type == 'in' else (frame_width + margin, final_pos[1]) elif direction == 'right': start_pos = (frame_width + margin, final_pos[1]) end_pos = final_pos if slide_type == 'in' else (-margin, final_pos[1]) elif direction == 'top': start_pos = (final_pos[0], -margin) end_pos = final_pos if slide_type == 'in' else (final_pos[0], frame_height + margin) elif direction == 'bottom': start_pos = (final_pos[0], frame_height + margin) end_pos = final_pos if slide_type == 'in' else (final_pos[0], -margin) else: start_pos = (-margin, final_pos[1]) end_pos = final_pos # For 'out' type, swap start and end if slide_type == 'out': start_pos, end_pos = final_pos, end_pos elif slide_type == 'across': # Slide all the way across if direction == 'left': start_pos = (-margin, final_pos[1]) end_pos = (frame_width + margin, final_pos[1]) elif direction == 'right': start_pos = (frame_width + margin, final_pos[1]) end_pos = (-margin, final_pos[1]) elif direction == 'top': start_pos = (final_pos[0], -margin) end_pos = (final_pos[0], frame_height + margin) elif direction == 'bottom': start_pos = (final_pos[0], frame_height + margin) end_pos = (final_pos[0], -margin) # Use overshoot easing if requested if overshoot and slide_type == 'in': easing = 'back_out' for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 frame = create_blank_frame(frame_width, frame_height, bg_color) # Calculate current position x = int(interpolate(start_pos[0], end_pos[0], t, easing)) y = int(interpolate(start_pos[1], end_pos[1], t, easing)) # Draw object if object_type == 'emoji': size = object_data['size'] draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(x - size // 2, y - size // 2), size=size, shadow=object_data.get('shadow', True) ) elif object_type == 'text': from core.typography import draw_text_with_outline draw_text_with_outline( frame, text=object_data.get('text', 'SLIDE'), position=(x, y), font_size=object_data.get('font_size', 50), text_color=object_data.get('text_color', (0, 0, 0)), outline_color=object_data.get('outline_color', (255, 255, 255)), outline_width=3, centered=True ) frames.append(frame) return frames def create_multi_slide( objects: list[dict], num_frames: int = 30, stagger_delay: int = 3, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] for i in range(num_frames): frame = create_blank_frame(frame_width, frame_height, bg_color) for idx, obj in enumerate(objects): # Calculate when this object starts moving start_frame = idx * stagger_delay if i < start_frame: continue # Object hasn't started yet # Calculate progress for this object obj_frame = i - start_frame obj_duration = num_frames - start_frame if obj_duration <= 0: continue t = obj_frame / obj_duration # Get object properties obj_type = obj.get('type', 'emoji') obj_data = obj.get('data', {'emoji': '➡️', 'size': 80}) direction = obj.get('direction', 'left') final_pos = obj.get('final_pos', (frame_width // 2, frame_height // 2)) easing = obj.get('easing', 'back_out') # Calculate position size = obj_data.get('size', 80) margin = size if direction == 'left': start_x = -margin end_x = final_pos[0] y = final_pos[1] elif direction == 'right': start_x = frame_width + margin end_x = final_pos[0] y = final_pos[1] elif direction == 'top': x = final_pos[0] start_y = -margin end_y = final_pos[1] elif direction == 'bottom': x = final_pos[0] start_y = frame_height + margin end_y = final_pos[1] else: start_x = -margin end_x = final_pos[0] y = final_pos[1] # Interpolate position if direction in ['left', 'right']: x = int(interpolate(start_x, end_x, t, easing)) else: y = int(interpolate(start_y, end_y, t, easing)) # Draw object if obj_type == 'emoji': draw_emoji_enhanced( frame, emoji=obj_data['emoji'], position=(x - size // 2, y - size // 2), size=size, shadow=False ) frames.append(frame) return frames # Example usage if __name__ == '__main__': print("Creating slide animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Slide in from left with overshoot frames = create_slide_animation( object_type='emoji', object_data={'emoji': '➡️', 'size': 100}, num_frames=30, direction='left', slide_type='in', overshoot=True ) builder.add_frames(frames) builder.save('slide_in_left.gif', num_colors=128) # Example 2: Slide across builder.clear() frames = create_slide_animation( object_type='emoji', object_data={'emoji': '🚀', 'size': 80}, num_frames=40, direction='left', slide_type='across', easing='ease_in_out' ) builder.add_frames(frames) builder.save('slide_across.gif', num_colors=128) # Example 3: Multiple objects sliding in builder.clear() objects = [ { 'type': 'emoji', 'data': {'emoji': '🎯', 'size': 60}, 'direction': 'left', 'final_pos': (120, 240) }, { 'type': 'emoji', 'data': {'emoji': '🎪', 'size': 60}, 'direction': 'right', 'final_pos': (240, 240) }, { 'type': 'emoji', 'data': {'emoji': '🎨', 'size': 60}, 'direction': 'top', 'final_pos': (360, 240) } ] frames = create_multi_slide(objects, num_frames=50, stagger_delay=5) builder.add_frames(frames) builder.save('slide_multi.gif', num_colors=128) print("Created slide animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Slide Animation - Slide elements in from edges with overshoot/bounce. + +Creates smooth entrance and exit animations. +""" import sys from pathlib import Path @@ -24,6 +29,25 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create slide animation. + + Args: + object_type: 'emoji', 'text' + object_data: Object configuration + num_frames: Number of frames + direction: Direction of slide + slide_type: Type of slide (in/out/across) + easing: Easing function + overshoot: Add overshoot/bounce at end + final_pos: Final position (None = center) + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -121,6 +145,20 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create animation with multiple objects sliding in sequence. + + Args: + objects: List of object configs with 'type', 'data', 'direction', 'final_pos' + num_frames: Number of frames + stagger_delay: Frames between each object starting + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] for i in range(num_frames): @@ -250,4 +288,4 @@ builder.add_frames(frames) builder.save('slide_multi.gif', num_colors=128) - print("Created slide animations!")+ print("Created slide animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/slide.py
Improve documentation using docstrings
#!/usr/bin/env python3 import argparse import shutil import subprocess import sys import tempfile import defusedxml.minidom import zipfile from pathlib import Path def main(): parser = argparse.ArgumentParser(description="Pack a directory into an Office file") parser.add_argument("input_directory", help="Unpacked Office document directory") parser.add_argument("output_file", help="Output Office file (.docx/.pptx/.xlsx)") parser.add_argument("--force", action="store_true", help="Skip validation") args = parser.parse_args() try: success = pack_document( args.input_directory, args.output_file, validate=not args.force ) # Show warning if validation was skipped if args.force: print("Warning: Skipped validation, file may be corrupt", file=sys.stderr) # Exit with error if validation failed elif not success: print("Contents would produce a corrupt file.", file=sys.stderr) print("Please validate XML before repacking.", file=sys.stderr) print("Use --force to skip validation and pack anyway.", file=sys.stderr) sys.exit(1) except ValueError as e: sys.exit(f"Error: {e}") def pack_document(input_dir, output_file, validate=False): input_dir = Path(input_dir) output_file = Path(output_file) if not input_dir.is_dir(): raise ValueError(f"{input_dir} is not a directory") if output_file.suffix.lower() not in {".docx", ".pptx", ".xlsx"}: raise ValueError(f"{output_file} must be a .docx, .pptx, or .xlsx file") # Work in temporary directory to avoid modifying original with tempfile.TemporaryDirectory() as temp_dir: temp_content_dir = Path(temp_dir) / "content" shutil.copytree(input_dir, temp_content_dir) # Process XML files to remove pretty-printing whitespace for pattern in ["*.xml", "*.rels"]: for xml_file in temp_content_dir.rglob(pattern): condense_xml(xml_file) # Create final Office file as zip archive output_file.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED) as zf: for f in temp_content_dir.rglob("*"): if f.is_file(): zf.write(f, f.relative_to(temp_content_dir)) # Validate if requested if validate: if not validate_document(output_file): output_file.unlink() # Delete the corrupt file return False return True def validate_document(doc_path): # Determine the correct filter based on file extension match doc_path.suffix.lower(): case ".docx": filter_name = "html:HTML" case ".pptx": filter_name = "html:impress_html_Export" case ".xlsx": filter_name = "html:HTML (StarCalc)" with tempfile.TemporaryDirectory() as temp_dir: try: result = subprocess.run( [ "soffice", "--headless", "--convert-to", filter_name, "--outdir", temp_dir, str(doc_path), ], capture_output=True, timeout=10, text=True, ) if not (Path(temp_dir) / f"{doc_path.stem}.html").exists(): error_msg = result.stderr.strip() or "Document validation failed" print(f"Validation error: {error_msg}", file=sys.stderr) return False return True except FileNotFoundError: print("Warning: soffice not found. Skipping validation.", file=sys.stderr) return True except subprocess.TimeoutExpired: print("Validation error: Timeout during conversion", file=sys.stderr) return False except Exception as e: print(f"Validation error: {e}", file=sys.stderr) return False def condense_xml(xml_file): with open(xml_file, "r", encoding="utf-8") as f: dom = defusedxml.minidom.parse(f) # Process each element to remove whitespace and comments for element in dom.getElementsByTagName("*"): # Skip w:t elements and their processing if element.tagName.endswith(":t"): continue # Remove whitespace-only text nodes and comment nodes for child in list(element.childNodes): if ( child.nodeType == child.TEXT_NODE and child.nodeValue and child.nodeValue.strip() == "" ) or child.nodeType == child.COMMENT_NODE: element.removeChild(child) # Write back the condensed XML with open(xml_file, "wb") as f: f.write(dom.toxml(encoding="UTF-8")) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +Tool to pack a directory into a .docx, .pptx, or .xlsx file with XML formatting undone. + +Example usage: + python pack.py <input_directory> <office_file> [--force] +""" import argparse import shutil @@ -37,6 +43,16 @@ def pack_document(input_dir, output_file, validate=False): + """Pack a directory into an Office file (.docx/.pptx/.xlsx). + + Args: + input_dir: Path to unpacked Office document directory + output_file: Path to output Office file + validate: If True, validates with soffice (default: False) + + Returns: + bool: True if successful, False if validation failed + """ input_dir = Path(input_dir) output_file = Path(output_file) @@ -72,6 +88,7 @@ def validate_document(doc_path): + """Validate document by converting to HTML with soffice.""" # Determine the correct filter based on file extension match doc_path.suffix.lower(): case ".docx": @@ -114,6 +131,7 @@ def condense_xml(xml_file): + """Strip unnecessary whitespace and remove comments.""" with open(xml_file, "r", encoding="utf-8") as f: dom = defusedxml.minidom.parse(f) @@ -138,4 +156,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/ooxml/scripts/pack.py
Add minimal docstrings for each function
#!/usr/bin/env python3 import sys from pathlib import Path SKILL_TEMPLATE = """--- name: {skill_name} description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.] --- # {skill_title} ## Overview [TODO: 1-2 sentences explaining what this skill enables] ## Structuring This Skill [TODO: Choose the structure that best fits this skill's purpose. Common patterns: **1. Workflow-Based** (best for sequential processes) - Works well when there are clear step-by-step procedures - Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing" - Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2... **2. Task-Based** (best for tool collections) - Works well when the skill offers different operations/capabilities - Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text" - Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2... **3. Reference/Guidelines** (best for standards or specifications) - Works well for brand guidelines, coding standards, or requirements - Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features" - Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage... **4. Capabilities-Based** (best for integrated systems) - Works well when the skill provides multiple interrelated features - Example: Product Management with "Core Capabilities" → numbered capability list - Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature... Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations). Delete this entire "Structuring This Skill" section when done - it's just guidance.] ## [TODO: Replace with the first main section based on chosen structure] [TODO: Add content here. See examples in existing skills: - Code samples for technical skills - Decision trees for complex workflows - Concrete examples with realistic user requests - References to scripts/templates/references as needed] ## Resources This skill includes example resource directories that demonstrate how to organize different types of bundled resources: ### scripts/ Executable code (Python/Bash/etc.) that can be run directly to perform specific operations. **Examples from other skills:** - PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation - DOCX skill: `document.py`, `utilities.py` - Python modules for document processing **Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations. **Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments. ### references/ Documentation and reference material intended to be loaded into context to inform Claude's process and thinking. **Examples from other skills:** - Product management: `communication.md`, `context_building.md` - detailed workflow guides - BigQuery: API reference documentation and query examples - Finance: Schema documentation, company policies **Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working. ### assets/ Files not intended to be loaded into context, but rather used within the output Claude produces. **Examples from other skills:** - Brand styling: PowerPoint template files (.pptx), logo files - Frontend builder: HTML/React boilerplate project directories - Typography: Font files (.ttf, .woff2) **Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output. --- **Any unneeded directories can be deleted.** Not every skill requires all three types of resources. """ EXAMPLE_SCRIPT = '''#!/usr/bin/env python3 """ Example helper script for {skill_name} This is a placeholder script that can be executed directly. Replace with actual implementation or delete if not needed. Example real scripts from other skills: - pdf/scripts/fill_fillable_fields.py - Fills PDF form fields - pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images """ def main(): print("This is an example script for {skill_name}") # TODO: Add actual script logic here # This could be data processing, file conversion, API calls, etc. if __name__ == "__main__": main() ''' EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title} This is a placeholder for detailed reference documentation. Replace with actual reference content or delete if not needed. Example real reference docs from other skills: - product-management/references/communication.md - Comprehensive guide for status updates - product-management/references/context_building.md - Deep-dive on gathering context - bigquery/references/ - API references and query examples ## When Reference Docs Are Useful Reference docs are ideal for: - Comprehensive API documentation - Detailed workflow guides - Complex multi-step processes - Information too lengthy for main SKILL.md - Content that's only needed for specific use cases ## Structure Suggestions ### API Reference Example - Overview - Authentication - Endpoints with examples - Error codes - Rate limits ### Workflow Guide Example - Prerequisites - Step-by-step instructions - Common patterns - Troubleshooting - Best practices """ EXAMPLE_ASSET = """# Example Asset File This placeholder represents where asset files would be stored. Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed. Asset files are NOT intended to be loaded into context, but rather used within the output Claude produces. Example asset files from other skills: - Brand guidelines: logo.png, slides_template.pptx - Frontend builder: hello-world/ directory with HTML/React boilerplate - Typography: custom-font.ttf, font-family.woff2 - Data: sample_data.csv, test_dataset.json ## Common Asset Types - Templates: .pptx, .docx, boilerplate directories - Images: .png, .jpg, .svg, .gif - Fonts: .ttf, .otf, .woff, .woff2 - Boilerplate code: Project directories, starter files - Icons: .ico, .svg - Data files: .csv, .json, .xml, .yaml Note: This is a text placeholder. Actual assets can be any file type. """ def title_case_skill_name(skill_name): return ' '.join(word.capitalize() for word in skill_name.split('-')) def init_skill(skill_name, path): # Determine skill directory path skill_dir = Path(path).resolve() / skill_name # Check if directory already exists if skill_dir.exists(): print(f"❌ Error: Skill directory already exists: {skill_dir}") return None # Create skill directory try: skill_dir.mkdir(parents=True, exist_ok=False) print(f"✅ Created skill directory: {skill_dir}") except Exception as e: print(f"❌ Error creating directory: {e}") return None # Create SKILL.md from template skill_title = title_case_skill_name(skill_name) skill_content = SKILL_TEMPLATE.format( skill_name=skill_name, skill_title=skill_title ) skill_md_path = skill_dir / 'SKILL.md' try: skill_md_path.write_text(skill_content) print("✅ Created SKILL.md") except Exception as e: print(f"❌ Error creating SKILL.md: {e}") return None # Create resource directories with example files try: # Create scripts/ directory with example script scripts_dir = skill_dir / 'scripts' scripts_dir.mkdir(exist_ok=True) example_script = scripts_dir / 'example.py' example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name)) example_script.chmod(0o755) print("✅ Created scripts/example.py") # Create references/ directory with example reference doc references_dir = skill_dir / 'references' references_dir.mkdir(exist_ok=True) example_reference = references_dir / 'api_reference.md' example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title)) print("✅ Created references/api_reference.md") # Create assets/ directory with example asset placeholder assets_dir = skill_dir / 'assets' assets_dir.mkdir(exist_ok=True) example_asset = assets_dir / 'example_asset.txt' example_asset.write_text(EXAMPLE_ASSET) print("✅ Created assets/example_asset.txt") except Exception as e: print(f"❌ Error creating resource directories: {e}") return None # Print next steps print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}") print("\nNext steps:") print("1. Edit SKILL.md to complete the TODO items and update the description") print("2. Customize or delete the example files in scripts/, references/, and assets/") print("3. Run the validator when ready to check the skill structure") return skill_dir def main(): if len(sys.argv) < 4 or sys.argv[2] != '--path': print("Usage: init_skill.py <skill-name> --path <path>") print("\nSkill name requirements:") print(" - Hyphen-case identifier (e.g., 'data-analyzer')") print(" - Lowercase letters, digits, and hyphens only") print(" - Max 40 characters") print(" - Must match directory name exactly") print("\nExamples:") print(" init_skill.py my-new-skill --path skills/public") print(" init_skill.py my-api-helper --path skills/private") print(" init_skill.py custom-skill --path /custom/location") sys.exit(1) skill_name = sys.argv[1] path = sys.argv[3] print(f"🚀 Initializing skill: {skill_name}") print(f" Location: {path}") print() result = init_skill(skill_name, path) if result: sys.exit(0) else: sys.exit(1) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,15 @@ #!/usr/bin/env python3 +""" +Skill Initializer - Creates a new skill from template + +Usage: + init_skill.py <skill-name> --path <path> + +Examples: + init_skill.py my-new-skill --path skills/public + init_skill.py my-api-helper --path skills/private + init_skill.py custom-skill --path /custom/location +""" import sys from pathlib import Path @@ -176,10 +187,21 @@ def title_case_skill_name(skill_name): + """Convert hyphenated skill name to Title Case for display.""" return ' '.join(word.capitalize() for word in skill_name.split('-')) def init_skill(skill_name, path): + """ + Initialize a new skill directory with template SKILL.md. + + Args: + skill_name: Name of the skill + path: Path where the skill directory should be created + + Returns: + Path to created skill directory, or None if error + """ # Determine skill directory path skill_dir = Path(path).resolve() / skill_name @@ -278,4 +300,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/skill-creator/scripts/init_skill.py
Create structured documentation for my script
#!/usr/bin/env python3 import sys import zipfile from pathlib import Path from quick_validate import validate_skill def package_skill(skill_path, output_dir=None): skill_path = Path(skill_path).resolve() # Validate skill folder exists if not skill_path.exists(): print(f"❌ Error: Skill folder not found: {skill_path}") return None if not skill_path.is_dir(): print(f"❌ Error: Path is not a directory: {skill_path}") return None # Validate SKILL.md exists skill_md = skill_path / "SKILL.md" if not skill_md.exists(): print(f"❌ Error: SKILL.md not found in {skill_path}") return None # Run validation before packaging print("🔍 Validating skill...") valid, message = validate_skill(skill_path) if not valid: print(f"❌ Validation failed: {message}") print(" Please fix the validation errors before packaging.") return None print(f"✅ {message}\n") # Determine output location skill_name = skill_path.name if output_dir: output_path = Path(output_dir).resolve() output_path.mkdir(parents=True, exist_ok=True) else: output_path = Path.cwd() zip_filename = output_path / f"{skill_name}.zip" # Create the zip file try: with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf: # Walk through the skill directory for file_path in skill_path.rglob('*'): if file_path.is_file(): # Calculate the relative path within the zip arcname = file_path.relative_to(skill_path.parent) zipf.write(file_path, arcname) print(f" Added: {arcname}") print(f"\n✅ Successfully packaged skill to: {zip_filename}") return zip_filename except Exception as e: print(f"❌ Error creating zip file: {e}") return None def main(): if len(sys.argv) < 2: print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]") print("\nExample:") print(" python utils/package_skill.py skills/public/my-skill") print(" python utils/package_skill.py skills/public/my-skill ./dist") sys.exit(1) skill_path = sys.argv[1] output_dir = sys.argv[2] if len(sys.argv) > 2 else None print(f"📦 Packaging skill: {skill_path}") if output_dir: print(f" Output directory: {output_dir}") print() result = package_skill(skill_path, output_dir) if result: sys.exit(0) else: sys.exit(1) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3 +""" +Skill Packager - Creates a distributable zip file of a skill folder + +Usage: + python utils/package_skill.py <path/to/skill-folder> [output-directory] + +Example: + python utils/package_skill.py skills/public/my-skill + python utils/package_skill.py skills/public/my-skill ./dist +""" import sys import zipfile @@ -7,6 +17,16 @@ def package_skill(skill_path, output_dir=None): + """ + Package a skill folder into a zip file. + + Args: + skill_path: Path to the skill folder + output_dir: Optional output directory for the zip file (defaults to current directory) + + Returns: + Path to the created zip file, or None if error + """ skill_path = Path(skill_path).resolve() # Validate skill folder exists @@ -87,4 +107,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/skill-creator/scripts/package_skill.py
Generate docstrings for this script
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image, ImageOps, ImageDraw import numpy as np def apply_kaleidoscope(frame: Image.Image, segments: int = 8, center: tuple[int, int] | None = None) -> Image.Image: width, height = frame.size if center is None: center = (width // 2, height // 2) # Create output frame output = Image.new('RGB', (width, height)) # Calculate angle per segment angle_per_segment = 360 / segments # For simplicity, we'll create a radial mirror effect # A full implementation would rotate and mirror properly # This is a simplified version that creates interesting patterns # Convert to numpy for easier manipulation frame_array = np.array(frame) output_array = np.zeros_like(frame_array) center_x, center_y = center # Create wedge mask and mirror it for y in range(height): for x in range(width): # Calculate angle from center dx = x - center_x dy = y - center_y angle = (math.degrees(math.atan2(dy, dx)) + 180) % 360 distance = math.sqrt(dx * dx + dy * dy) # Which segment does this pixel belong to? segment = int(angle / angle_per_segment) # Mirror angle within segment segment_angle = angle % angle_per_segment if segment % 2 == 1: # Mirror every other segment segment_angle = angle_per_segment - segment_angle # Calculate source position source_angle = segment_angle + (segment // 2) * angle_per_segment * 2 source_angle_rad = math.radians(source_angle - 180) source_x = int(center_x + distance * math.cos(source_angle_rad)) source_y = int(center_y + distance * math.sin(source_angle_rad)) # Bounds check if 0 <= source_x < width and 0 <= source_y < height: output_array[y, x] = frame_array[source_y, source_x] else: output_array[y, x] = frame_array[y, x] return Image.fromarray(output_array) def apply_simple_mirror(frame: Image.Image, mode: str = 'quad') -> Image.Image: width, height = frame.size center_x, center_y = width // 2, height // 2 if mode == 'horizontal': # Mirror left half to right left_half = frame.crop((0, 0, center_x, height)) left_flipped = ImageOps.mirror(left_half) result = frame.copy() result.paste(left_flipped, (center_x, 0)) return result elif mode == 'vertical': # Mirror top half to bottom top_half = frame.crop((0, 0, width, center_y)) top_flipped = ImageOps.flip(top_half) result = frame.copy() result.paste(top_flipped, (0, center_y)) return result elif mode == 'quad': # 4-way mirror (top-left quadrant mirrored to all) quad = frame.crop((0, 0, center_x, center_y)) result = Image.new('RGB', (width, height)) # Top-left (original) result.paste(quad, (0, 0)) # Top-right (horizontal mirror) result.paste(ImageOps.mirror(quad), (center_x, 0)) # Bottom-left (vertical mirror) result.paste(ImageOps.flip(quad), (0, center_y)) # Bottom-right (both mirrors) result.paste(ImageOps.flip(ImageOps.mirror(quad)), (center_x, center_y)) return result else: return frame def create_kaleidoscope_animation( base_frame: Image.Image | None = None, num_frames: int = 30, segments: int = 8, rotation_speed: float = 1.0, width: int = 480, height: int = 480 ) -> list[Image.Image]: frames = [] # Create demo pattern if no base frame if base_frame is None: base_frame = Image.new('RGB', (width, height), (255, 255, 255)) draw = ImageDraw.Draw(base_frame) # Draw some colored shapes from core.color_palettes import get_palette palette = get_palette('vibrant') colors = [palette['primary'], palette['secondary'], palette['accent']] for i, color in enumerate(colors): x = width // 2 + int(100 * math.cos(i * 2 * math.pi / 3)) y = height // 2 + int(100 * math.sin(i * 2 * math.pi / 3)) draw.ellipse([x - 40, y - 40, x + 40, y + 40], fill=color) # Rotate base frame and apply kaleidoscope for i in range(num_frames): angle = (i / num_frames) * 360 * rotation_speed # Rotate base frame rotated = base_frame.rotate(angle, resample=Image.BICUBIC) # Apply kaleidoscope kaleido_frame = apply_kaleidoscope(rotated, segments=segments) frames.append(kaleido_frame) return frames # Example usage if __name__ == '__main__': from core.gif_builder import GIFBuilder print("Creating kaleidoscope GIF...") builder = GIFBuilder(width=480, height=480, fps=20) # Create kaleidoscope animation frames = create_kaleidoscope_animation( num_frames=40, segments=8, rotation_speed=0.5 ) builder.add_frames(frames) builder.save('kaleidoscope_test.gif', num_colors=128)
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Kaleidoscope Effect - Create mirror/rotation effects. + +Apply kaleidoscope effects to frames or objects for psychedelic visuals. +""" import sys from pathlib import Path @@ -12,6 +17,17 @@ def apply_kaleidoscope(frame: Image.Image, segments: int = 8, center: tuple[int, int] | None = None) -> Image.Image: + """ + Apply kaleidoscope effect by mirroring/rotating frame sections. + + Args: + frame: Input frame + segments: Number of mirror segments (4, 6, 8, 12 work well) + center: Center point for effect (None = frame center) + + Returns: + Frame with kaleidoscope effect + """ width, height = frame.size if center is None: @@ -68,6 +84,16 @@ def apply_simple_mirror(frame: Image.Image, mode: str = 'quad') -> Image.Image: + """ + Apply simple mirror effect (faster than full kaleidoscope). + + Args: + frame: Input frame + mode: 'horizontal', 'vertical', 'quad' (4-way), 'radial' + + Returns: + Mirrored frame + """ width, height = frame.size center_x, center_y = width // 2, height // 2 @@ -119,6 +145,20 @@ width: int = 480, height: int = 480 ) -> list[Image.Image]: + """ + Create animated kaleidoscope effect. + + Args: + base_frame: Frame to apply effect to (or None for demo pattern) + num_frames: Number of frames + segments: Kaleidoscope segments + rotation_speed: How fast pattern rotates (0.5-2.0) + width: Frame width if generating demo + height: Frame height if generating demo + + Returns: + List of frames with kaleidoscope effect + """ frames = [] # Create demo pattern if no base frame @@ -168,4 +208,4 @@ ) builder.add_frames(frames) - builder.save('kaleidoscope_test.gif', num_colors=128)+ builder.save('kaleidoscope_test.gif', num_colors=128)
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/kaleidoscope.py
Add docstrings for utility scripts
#!/usr/bin/env python3 from pathlib import Path def check_slack_size(gif_path: str | Path, is_emoji: bool = True) -> tuple[bool, dict]: gif_path = Path(gif_path) if not gif_path.exists(): return False, {'error': f'File not found: {gif_path}'} size_bytes = gif_path.stat().st_size size_kb = size_bytes / 1024 size_mb = size_kb / 1024 limit_kb = 64 if is_emoji else 2048 limit_mb = limit_kb / 1024 passes = size_kb <= limit_kb info = { 'size_bytes': size_bytes, 'size_kb': size_kb, 'size_mb': size_mb, 'limit_kb': limit_kb, 'limit_mb': limit_mb, 'passes': passes, 'type': 'emoji' if is_emoji else 'message' } # Print feedback if passes: print(f"✓ {size_kb:.1f} KB - within {limit_kb} KB limit") else: print(f"✗ {size_kb:.1f} KB - exceeds {limit_kb} KB limit") overage_kb = size_kb - limit_kb overage_percent = (overage_kb / limit_kb) * 100 print(f" Over by: {overage_kb:.1f} KB ({overage_percent:.1f}%)") print(f" Try: fewer frames, fewer colors, or simpler design") return passes, info def validate_dimensions(width: int, height: int, is_emoji: bool = True) -> tuple[bool, dict]: info = { 'width': width, 'height': height, 'is_square': width == height, 'type': 'emoji' if is_emoji else 'message' } if is_emoji: # Emoji GIFs should be 128x128 optimal = width == height == 128 acceptable = width == height and 64 <= width <= 128 info['optimal'] = optimal info['acceptable'] = acceptable if optimal: print(f"✓ {width}x{height} - optimal for emoji") passes = True elif acceptable: print(f"⚠ {width}x{height} - acceptable but 128x128 is optimal") passes = True else: print(f"✗ {width}x{height} - emoji should be square, 128x128 recommended") passes = False else: # Message GIFs should be square-ish and reasonable size aspect_ratio = max(width, height) / min(width, height) if min(width, height) > 0 else float('inf') reasonable_size = 320 <= min(width, height) <= 640 info['aspect_ratio'] = aspect_ratio info['reasonable_size'] = reasonable_size # Check if roughly square (within 2:1 ratio) is_square_ish = aspect_ratio <= 2.0 if is_square_ish and reasonable_size: print(f"✓ {width}x{height} - good for message GIF") passes = True elif is_square_ish: print(f"⚠ {width}x{height} - square-ish but unusual size") passes = True elif reasonable_size: print(f"⚠ {width}x{height} - good size but not square-ish") passes = True else: print(f"✗ {width}x{height} - unusual dimensions for Slack") passes = False return passes, info def validate_gif(gif_path: str | Path, is_emoji: bool = True) -> tuple[bool, dict]: from PIL import Image gif_path = Path(gif_path) if not gif_path.exists(): return False, {'error': f'File not found: {gif_path}'} print(f"\nValidating {gif_path.name} as {'emoji' if is_emoji else 'message'} GIF:") print("=" * 60) # Check file size size_pass, size_info = check_slack_size(gif_path, is_emoji) # Check dimensions try: with Image.open(gif_path) as img: width, height = img.size dim_pass, dim_info = validate_dimensions(width, height, is_emoji) # Count frames frame_count = 0 try: while True: img.seek(frame_count) frame_count += 1 except EOFError: pass # Get duration if available try: duration_ms = img.info.get('duration', 100) total_duration = (duration_ms * frame_count) / 1000 fps = frame_count / total_duration if total_duration > 0 else 0 except: duration_ms = None total_duration = None fps = None except Exception as e: return False, {'error': f'Failed to read GIF: {e}'} print(f"\nFrames: {frame_count}") if total_duration: print(f"Duration: {total_duration:.1f}s @ {fps:.1f} fps") all_pass = size_pass and dim_pass results = { 'file': str(gif_path), 'passes': all_pass, 'size': size_info, 'dimensions': dim_info, 'frame_count': frame_count, 'duration_seconds': total_duration, 'fps': fps } print("=" * 60) if all_pass: print("✓ All validations passed!") else: print("✗ Some validations failed") print() return all_pass, results def get_optimization_suggestions(results: dict) -> list[str]: suggestions = [] if not results.get('passes', False): size_info = results.get('size', {}) dim_info = results.get('dimensions', {}) # Size suggestions if not size_info.get('passes', True): overage = size_info['size_kb'] - size_info['limit_kb'] if size_info['type'] == 'emoji': suggestions.append(f"Reduce file size by {overage:.1f} KB:") suggestions.append(" - Limit to 10-12 frames") suggestions.append(" - Use 32-40 colors maximum") suggestions.append(" - Remove gradients (solid colors compress better)") suggestions.append(" - Simplify design") else: suggestions.append(f"Reduce file size by {overage:.1f} KB:") suggestions.append(" - Reduce frame count or FPS") suggestions.append(" - Use fewer colors (128 → 64)") suggestions.append(" - Reduce dimensions") # Dimension suggestions if not dim_info.get('optimal', True) and dim_info.get('type') == 'emoji': suggestions.append("For optimal emoji GIF:") suggestions.append(" - Use 128x128 dimensions") suggestions.append(" - Ensure square aspect ratio") return suggestions # Convenience function for quick checks def is_slack_ready(gif_path: str | Path, is_emoji: bool = True, verbose: bool = True) -> bool: if verbose: passes, results = validate_gif(gif_path, is_emoji) if not passes: suggestions = get_optimization_suggestions(results) if suggestions: print("\nSuggestions:") for suggestion in suggestions: print(suggestion) return passes else: size_pass, _ = check_slack_size(gif_path, is_emoji) return size_pass
--- +++ @@ -1,9 +1,24 @@ #!/usr/bin/env python3 +""" +Validators - Check if GIFs meet Slack's requirements. + +These validators help ensure your GIFs meet Slack's size and dimension constraints. +""" from pathlib import Path def check_slack_size(gif_path: str | Path, is_emoji: bool = True) -> tuple[bool, dict]: + """ + Check if GIF meets Slack size limits. + + Args: + gif_path: Path to GIF file + is_emoji: True for emoji GIF (64KB limit), False for message GIF (2MB limit) + + Returns: + Tuple of (passes: bool, info: dict with details) + """ gif_path = Path(gif_path) if not gif_path.exists(): @@ -42,6 +57,17 @@ def validate_dimensions(width: int, height: int, is_emoji: bool = True) -> tuple[bool, dict]: + """ + Check if dimensions are suitable for Slack. + + Args: + width: Frame width in pixels + height: Frame height in pixels + is_emoji: True for emoji GIF, False for message GIF + + Returns: + Tuple of (passes: bool, info: dict with details) + """ info = { 'width': width, 'height': height, @@ -94,6 +120,16 @@ def validate_gif(gif_path: str | Path, is_emoji: bool = True) -> tuple[bool, dict]: + """ + Run all validations on a GIF file. + + Args: + gif_path: Path to GIF file + is_emoji: True for emoji GIF, False for message GIF + + Returns: + Tuple of (all_pass: bool, results: dict) + """ from PIL import Image gif_path = Path(gif_path) @@ -162,6 +198,15 @@ def get_optimization_suggestions(results: dict) -> list[str]: + """ + Get suggestions for optimizing a GIF based on validation results. + + Args: + results: Results dict from validate_gif() + + Returns: + List of suggestion strings + """ suggestions = [] if not results.get('passes', False): @@ -194,6 +239,17 @@ # Convenience function for quick checks def is_slack_ready(gif_path: str | Path, is_emoji: bool = True, verbose: bool = True) -> bool: + """ + Quick check if GIF is ready for Slack. + + Args: + gif_path: Path to GIF file + is_emoji: True for emoji GIF, False for message GIF + verbose: Print detailed feedback + + Returns: + True if ready, False otherwise + """ if verbose: passes, results = validate_gif(gif_path, is_emoji) if not passes: @@ -205,4 +261,4 @@ return passes else: size_pass, _ = check_slack_size(gif_path, is_emoji) - return size_pass+ return size_pass
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/validators.py
Add docstrings to improve collaboration
#!/usr/bin/env python3 import json import sys import subprocess import os import platform from pathlib import Path from openpyxl import load_workbook def setup_libreoffice_macro(): if platform.system() == 'Darwin': macro_dir = os.path.expanduser('~/Library/Application Support/LibreOffice/4/user/basic/Standard') else: macro_dir = os.path.expanduser('~/.config/libreoffice/4/user/basic/Standard') macro_file = os.path.join(macro_dir, 'Module1.xba') if os.path.exists(macro_file): with open(macro_file, 'r') as f: if 'RecalculateAndSave' in f.read(): return True if not os.path.exists(macro_dir): subprocess.run(['soffice', '--headless', '--terminate_after_init'], capture_output=True, timeout=10) os.makedirs(macro_dir, exist_ok=True) macro_content = '''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"> <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic"> Sub RecalculateAndSave() ThisComponent.calculateAll() ThisComponent.store() ThisComponent.close(True) End Sub </script:module>''' try: with open(macro_file, 'w') as f: f.write(macro_content) return True except Exception: return False def recalc(filename, timeout=30): if not Path(filename).exists(): return {'error': f'File {filename} does not exist'} abs_path = str(Path(filename).absolute()) if not setup_libreoffice_macro(): return {'error': 'Failed to setup LibreOffice macro'} cmd = [ 'soffice', '--headless', '--norestore', 'vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application', abs_path ] # Handle timeout command differences between Linux and macOS if platform.system() != 'Windows': timeout_cmd = 'timeout' if platform.system() == 'Linux' else None if platform.system() == 'Darwin': # Check if gtimeout is available on macOS try: subprocess.run(['gtimeout', '--version'], capture_output=True, timeout=1, check=False) timeout_cmd = 'gtimeout' except (FileNotFoundError, subprocess.TimeoutExpired): pass if timeout_cmd: cmd = [timeout_cmd, str(timeout)] + cmd result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0 and result.returncode != 124: # 124 is timeout exit code error_msg = result.stderr or 'Unknown error during recalculation' if 'Module1' in error_msg or 'RecalculateAndSave' not in error_msg: return {'error': 'LibreOffice macro not configured properly'} else: return {'error': error_msg} # Check for Excel errors in the recalculated file - scan ALL cells try: wb = load_workbook(filename, data_only=True) excel_errors = ['#VALUE!', '#DIV/0!', '#REF!', '#NAME?', '#NULL!', '#NUM!', '#N/A'] error_details = {err: [] for err in excel_errors} total_errors = 0 for sheet_name in wb.sheetnames: ws = wb[sheet_name] # Check ALL rows and columns - no limits for row in ws.iter_rows(): for cell in row: if cell.value is not None and isinstance(cell.value, str): for err in excel_errors: if err in cell.value: location = f"{sheet_name}!{cell.coordinate}" error_details[err].append(location) total_errors += 1 break wb.close() # Build result summary result = { 'status': 'success' if total_errors == 0 else 'errors_found', 'total_errors': total_errors, 'error_summary': {} } # Add non-empty error categories for err_type, locations in error_details.items(): if locations: result['error_summary'][err_type] = { 'count': len(locations), 'locations': locations[:20] # Show up to 20 locations } # Add formula count for context - also check ALL cells wb_formulas = load_workbook(filename, data_only=False) formula_count = 0 for sheet_name in wb_formulas.sheetnames: ws = wb_formulas[sheet_name] for row in ws.iter_rows(): for cell in row: if cell.value and isinstance(cell.value, str) and cell.value.startswith('='): formula_count += 1 wb_formulas.close() result['total_formulas'] = formula_count return result except Exception as e: return {'error': str(e)} def main(): if len(sys.argv) < 2: print("Usage: python recalc.py <excel_file> [timeout_seconds]") print("\nRecalculates all formulas in an Excel file using LibreOffice") print("\nReturns JSON with error details:") print(" - status: 'success' or 'errors_found'") print(" - total_errors: Total number of Excel errors found") print(" - total_formulas: Number of formulas in the file") print(" - error_summary: Breakdown by error type with locations") print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A") sys.exit(1) filename = sys.argv[1] timeout = int(sys.argv[2]) if len(sys.argv) > 2 else 30 result = recalc(filename, timeout) print(json.dumps(result, indent=2)) if __name__ == '__main__': main()
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +""" +Excel Formula Recalculation Script +Recalculates all formulas in an Excel file using LibreOffice +""" import json import sys @@ -10,6 +14,7 @@ def setup_libreoffice_macro(): + """Setup LibreOffice macro for recalculation if not already configured""" if platform.system() == 'Darwin': macro_dir = os.path.expanduser('~/Library/Application Support/LibreOffice/4/user/basic/Standard') else: @@ -46,6 +51,16 @@ def recalc(filename, timeout=30): + """ + Recalculate formulas in Excel file and report any errors + + Args: + filename: Path to Excel file + timeout: Maximum time to wait for recalculation (seconds) + + Returns: + dict with error locations and counts + """ if not Path(filename).exists(): return {'error': f'File {filename} does not exist'}
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/xlsx/recalc.py
Add verbose docstrings with examples
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced from core.easing import interpolate def create_flip_animation( object1_data: dict, object2_data: dict | None = None, num_frames: int = 30, flip_axis: str = 'horizontal', # 'horizontal', 'vertical' easing: str = 'ease_in_out', object_type: str = 'emoji', center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] if object2_data is None: object2_data = object1_data for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 frame = create_blank_frame(frame_width, frame_height, bg_color) # Calculate rotation angle (0 to 180 degrees) angle = interpolate(0, 180, t, easing) # Determine which side is visible and calculate scale if angle < 90: # Front side visible current_object = object1_data scale_factor = math.cos(math.radians(angle)) else: # Back side visible current_object = object2_data scale_factor = abs(math.cos(math.radians(angle))) # Don't draw when edge-on (very thin) if scale_factor < 0.05: frames.append(frame) continue if object_type == 'emoji': size = current_object['size'] # Create emoji on canvas canvas_size = size * 2 emoji_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji=current_object['emoji'], position=(canvas_size // 2 - size // 2, canvas_size // 2 - size // 2), size=size, shadow=False ) # Apply flip scaling if flip_axis == 'horizontal': # Scale horizontally for horizontal flip new_width = max(1, int(canvas_size * scale_factor)) new_height = canvas_size else: # Scale vertically for vertical flip new_width = canvas_size new_height = max(1, int(canvas_size * scale_factor)) # Resize to simulate 3D rotation emoji_scaled = emoji_canvas.resize((new_width, new_height), Image.LANCZOS) # Position centered paste_x = center_pos[0] - new_width // 2 paste_y = center_pos[1] - new_height // 2 # Composite onto frame frame_rgba = frame.convert('RGBA') frame_rgba.paste(emoji_scaled, (paste_x, paste_y), emoji_scaled) frame = frame_rgba.convert('RGB') elif object_type == 'text': from core.typography import draw_text_with_outline # Create text on canvas text = current_object.get('text', 'FLIP') font_size = current_object.get('font_size', 50) canvas_size = max(frame_width, frame_height) text_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) # Draw on RGB for text rendering text_canvas_rgb = text_canvas.convert('RGB') text_canvas_rgb.paste(bg_color, (0, 0, canvas_size, canvas_size)) draw_text_with_outline( text_canvas_rgb, text=text, position=(canvas_size // 2, canvas_size // 2), font_size=font_size, text_color=current_object.get('text_color', (0, 0, 0)), outline_color=current_object.get('outline_color', (255, 255, 255)), outline_width=3, centered=True ) # Make background transparent text_canvas = text_canvas_rgb.convert('RGBA') data = text_canvas.getdata() new_data = [] for item in data: if item[:3] == bg_color: new_data.append((255, 255, 255, 0)) else: new_data.append(item) text_canvas.putdata(new_data) # Apply flip scaling if flip_axis == 'horizontal': new_width = max(1, int(canvas_size * scale_factor)) new_height = canvas_size else: new_width = canvas_size new_height = max(1, int(canvas_size * scale_factor)) text_scaled = text_canvas.resize((new_width, new_height), Image.LANCZOS) # Center and crop if flip_axis == 'horizontal': left = (new_width - frame_width) // 2 if new_width > frame_width else 0 top = (canvas_size - frame_height) // 2 paste_x = center_pos[0] - min(new_width, frame_width) // 2 paste_y = 0 text_cropped = text_scaled.crop(( left, top, left + min(new_width, frame_width), top + frame_height )) else: left = (canvas_size - frame_width) // 2 top = (new_height - frame_height) // 2 if new_height > frame_height else 0 paste_x = 0 paste_y = center_pos[1] - min(new_height, frame_height) // 2 text_cropped = text_scaled.crop(( left, top, left + frame_width, top + min(new_height, frame_height) )) frame_rgba = frame.convert('RGBA') frame_rgba.paste(text_cropped, (paste_x, paste_y), text_cropped) frame = frame_rgba.convert('RGB') frames.append(frame) return frames def create_quick_flip( emoji_front: str, emoji_back: str, num_frames: int = 20, frame_size: int = 128 ) -> list[Image.Image]: return create_flip_animation( object1_data={'emoji': emoji_front, 'size': 80}, object2_data={'emoji': emoji_back, 'size': 80}, num_frames=num_frames, flip_axis='horizontal', easing='ease_in_out', object_type='emoji', center_pos=(frame_size // 2, frame_size // 2), frame_width=frame_size, frame_height=frame_size, bg_color=(255, 255, 255) ) def create_nope_flip( num_frames: int = 25, frame_width: int = 480, frame_height: int = 480 ) -> list[Image.Image]: return create_flip_animation( object1_data={'text': 'NOPE', 'font_size': 80, 'text_color': (255, 50, 50)}, object2_data={'text': 'NOPE', 'font_size': 80, 'text_color': (255, 50, 50)}, num_frames=num_frames, flip_axis='horizontal', easing='ease_out', object_type='text', frame_width=frame_width, frame_height=frame_height, bg_color=(255, 255, 255) ) # Example usage if __name__ == '__main__': print("Creating flip animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Emoji flip frames = create_flip_animation( object1_data={'emoji': '😊', 'size': 120}, object2_data={'emoji': '😂', 'size': 120}, num_frames=30, flip_axis='horizontal', object_type='emoji' ) builder.add_frames(frames) builder.save('flip_emoji.gif', num_colors=128) # Example 2: Text flip builder.clear() frames = create_flip_animation( object1_data={'text': 'YES', 'font_size': 80, 'text_color': (100, 200, 100)}, object2_data={'text': 'NO', 'font_size': 80, 'text_color': (200, 100, 100)}, num_frames=30, flip_axis='vertical', object_type='text' ) builder.add_frames(frames) builder.save('flip_text.gif', num_colors=128) # Example 3: Quick flip (emoji size) builder = GIFBuilder(width=128, height=128, fps=15) frames = create_quick_flip('👍', '👎', num_frames=20) builder.add_frames(frames) builder.save('flip_quick.gif', num_colors=48, optimize_for_emoji=True) print("Created flip animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Flip Animation - 3D-style card flip and rotation effects. + +Creates horizontal and vertical flips with perspective. +""" import sys from pathlib import Path @@ -24,6 +29,24 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create 3D-style flip animation. + + Args: + object1_data: First object (front side) + object2_data: Second object (back side, None = same as front) + num_frames: Number of frames + flip_axis: Axis to flip around + easing: Easing function + object_type: Type of objects + center_pos: Center position + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] if object2_data is None: @@ -175,6 +198,18 @@ num_frames: int = 20, frame_size: int = 128 ) -> list[Image.Image]: + """ + Create quick flip for emoji GIFs. + + Args: + emoji_front: Front emoji + emoji_back: Back emoji + num_frames: Number of frames + frame_size: Frame size (square) + + Returns: + List of frames + """ return create_flip_animation( object1_data={'emoji': emoji_front, 'size': 80}, object2_data={'emoji': emoji_back, 'size': 80}, @@ -194,6 +229,17 @@ frame_width: int = 480, frame_height: int = 480 ) -> list[Image.Image]: + """ + Create "nope" reaction flip (like flipping table). + + Args: + num_frames: Number of frames + frame_width: Frame width + frame_height: Frame height + + Returns: + List of frames + """ return create_flip_animation( object1_data={'text': 'NOPE', 'font_size': 80, 'text_color': (255, 50, 50)}, object2_data={'text': 'NOPE', 'font_size': 80, 'text_color': (255, 50, 50)}, @@ -242,4 +288,4 @@ builder.add_frames(frames) builder.save('flip_quick.gif', num_colors=48, optimize_for_emoji=True) - print("Created flip animations!")+ print("Created flip animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/flip.py
Write docstrings for utility functions
import re from pathlib import Path import lxml.etree class BaseSchemaValidator: # Elements whose 'id' attributes must be unique within their file # Format: element_name -> (attribute_name, scope) # scope can be 'file' (unique within file) or 'global' (unique across all files) UNIQUE_ID_REQUIREMENTS = { # Word elements "comment": ("id", "file"), # Comment IDs in comments.xml "commentrangestart": ("id", "file"), # Must match comment IDs "commentrangeend": ("id", "file"), # Must match comment IDs "bookmarkstart": ("id", "file"), # Bookmark start IDs "bookmarkend": ("id", "file"), # Bookmark end IDs # Note: ins and del (track changes) can share IDs when part of same revision # PowerPoint elements "sldid": ("id", "file"), # Slide IDs in presentation.xml "sldmasterid": ("id", "global"), # Slide master IDs must be globally unique "sldlayoutid": ("id", "global"), # Slide layout IDs must be globally unique "cm": ("authorid", "file"), # Comment author IDs # Excel elements "sheet": ("sheetid", "file"), # Sheet IDs in workbook.xml "definedname": ("id", "file"), # Named range IDs # Drawing/Shape elements (all formats) "cxnsp": ("id", "file"), # Connection shape IDs "sp": ("id", "file"), # Shape IDs "pic": ("id", "file"), # Picture IDs "grpsp": ("id", "file"), # Group shape IDs } # Mapping of element names to expected relationship types # Subclasses should override this with format-specific mappings ELEMENT_RELATIONSHIP_TYPES = {} # Unified schema mappings for all Office document types SCHEMA_MAPPINGS = { # Document type specific schemas "word": "ISO-IEC29500-4_2016/wml.xsd", # Word documents "ppt": "ISO-IEC29500-4_2016/pml.xsd", # PowerPoint presentations "xl": "ISO-IEC29500-4_2016/sml.xsd", # Excel spreadsheets # Common file types "[Content_Types].xml": "ecma/fouth-edition/opc-contentTypes.xsd", "app.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd", "core.xml": "ecma/fouth-edition/opc-coreProperties.xsd", "custom.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd", ".rels": "ecma/fouth-edition/opc-relationships.xsd", # Word-specific files "people.xml": "microsoft/wml-2012.xsd", "commentsIds.xml": "microsoft/wml-cid-2016.xsd", "commentsExtensible.xml": "microsoft/wml-cex-2018.xsd", "commentsExtended.xml": "microsoft/wml-2012.xsd", # Chart files (common across document types) "chart": "ISO-IEC29500-4_2016/dml-chart.xsd", # Theme files (common across document types) "theme": "ISO-IEC29500-4_2016/dml-main.xsd", # Drawing and media files "drawing": "ISO-IEC29500-4_2016/dml-main.xsd", } # Unified namespace constants MC_NAMESPACE = "http://schemas.openxmlformats.org/markup-compatibility/2006" XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" # Common OOXML namespaces used across validators PACKAGE_RELATIONSHIPS_NAMESPACE = ( "http://schemas.openxmlformats.org/package/2006/relationships" ) OFFICE_RELATIONSHIPS_NAMESPACE = ( "http://schemas.openxmlformats.org/officeDocument/2006/relationships" ) CONTENT_TYPES_NAMESPACE = ( "http://schemas.openxmlformats.org/package/2006/content-types" ) # Folders where we should clean ignorable namespaces MAIN_CONTENT_FOLDERS = {"word", "ppt", "xl"} # All allowed OOXML namespaces (superset of all document types) OOXML_NAMESPACES = { "http://schemas.openxmlformats.org/officeDocument/2006/math", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "http://schemas.openxmlformats.org/schemaLibrary/2006/main", "http://schemas.openxmlformats.org/drawingml/2006/main", "http://schemas.openxmlformats.org/drawingml/2006/chart", "http://schemas.openxmlformats.org/drawingml/2006/chartDrawing", "http://schemas.openxmlformats.org/drawingml/2006/diagram", "http://schemas.openxmlformats.org/drawingml/2006/picture", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://schemas.openxmlformats.org/presentationml/2006/main", "http://schemas.openxmlformats.org/spreadsheetml/2006/main", "http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes", "http://www.w3.org/XML/1998/namespace", } def __init__(self, unpacked_dir, original_file, verbose=False): self.unpacked_dir = Path(unpacked_dir).resolve() self.original_file = Path(original_file) self.verbose = verbose # Set schemas directory self.schemas_dir = Path(__file__).parent.parent.parent / "schemas" # Get all XML and .rels files patterns = ["*.xml", "*.rels"] self.xml_files = [ f for pattern in patterns for f in self.unpacked_dir.rglob(pattern) ] if not self.xml_files: print(f"Warning: No XML files found in {self.unpacked_dir}") def validate(self): raise NotImplementedError("Subclasses must implement the validate method") def validate_xml(self): errors = [] for xml_file in self.xml_files: try: # Try to parse the XML file lxml.etree.parse(str(xml_file)) except lxml.etree.XMLSyntaxError as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {e.lineno}: {e.msg}" ) except Exception as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Unexpected error: {str(e)}" ) if errors: print(f"FAILED - Found {len(errors)} XML violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All XML files are well-formed") return True def validate_namespaces(self): errors = [] for xml_file in self.xml_files: try: root = lxml.etree.parse(str(xml_file)).getroot() declared = set(root.nsmap.keys()) - {None} # Exclude default namespace for attr_val in [ v for k, v in root.attrib.items() if k.endswith("Ignorable") ]: undeclared = set(attr_val.split()) - declared errors.extend( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Namespace '{ns}' in Ignorable but not declared" for ns in undeclared ) except lxml.etree.XMLSyntaxError: continue if errors: print(f"FAILED - {len(errors)} namespace issues:") for error in errors: print(error) return False if self.verbose: print("PASSED - All namespace prefixes properly declared") return True def validate_unique_ids(self): errors = [] global_ids = {} # Track globally unique IDs across all files for xml_file in self.xml_files: try: root = lxml.etree.parse(str(xml_file)).getroot() file_ids = {} # Track IDs that must be unique within this file # Remove all mc:AlternateContent elements from the tree mc_elements = root.xpath( ".//mc:AlternateContent", namespaces={"mc": self.MC_NAMESPACE} ) for elem in mc_elements: elem.getparent().remove(elem) # Now check IDs in the cleaned tree for elem in root.iter(): # Get the element name without namespace tag = ( elem.tag.split("}")[-1].lower() if "}" in elem.tag else elem.tag.lower() ) # Check if this element type has ID uniqueness requirements if tag in self.UNIQUE_ID_REQUIREMENTS: attr_name, scope = self.UNIQUE_ID_REQUIREMENTS[tag] # Look for the specified attribute id_value = None for attr, value in elem.attrib.items(): attr_local = ( attr.split("}")[-1].lower() if "}" in attr else attr.lower() ) if attr_local == attr_name: id_value = value break if id_value is not None: if scope == "global": # Check global uniqueness if id_value in global_ids: prev_file, prev_line, prev_tag = global_ids[ id_value ] errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: Global ID '{id_value}' in <{tag}> " f"already used in {prev_file} at line {prev_line} in <{prev_tag}>" ) else: global_ids[id_value] = ( xml_file.relative_to(self.unpacked_dir), elem.sourceline, tag, ) elif scope == "file": # Check file-level uniqueness key = (tag, attr_name) if key not in file_ids: file_ids[key] = {} if id_value in file_ids[key]: prev_line = file_ids[key][id_value] errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: Duplicate {attr_name}='{id_value}' in <{tag}> " f"(first occurrence at line {prev_line})" ) else: file_ids[key][id_value] = elem.sourceline except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} ID uniqueness violations:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All required IDs are unique") return True def validate_file_references(self): errors = [] # Find all .rels files rels_files = list(self.unpacked_dir.rglob("*.rels")) if not rels_files: if self.verbose: print("PASSED - No .rels files found") return True # Get all files in the unpacked directory (excluding reference files) all_files = [] for file_path in self.unpacked_dir.rglob("*"): if ( file_path.is_file() and file_path.name != "[Content_Types].xml" and not file_path.name.endswith(".rels") ): # This file is not referenced by .rels all_files.append(file_path.resolve()) # Track all files that are referenced by any .rels file all_referenced_files = set() if self.verbose: print( f"Found {len(rels_files)} .rels files and {len(all_files)} target files" ) # Check each .rels file for rels_file in rels_files: try: # Parse relationships file rels_root = lxml.etree.parse(str(rels_file)).getroot() # Get the directory where this .rels file is located rels_dir = rels_file.parent # Find all relationships and their targets referenced_files = set() broken_refs = [] for rel in rels_root.findall( ".//ns:Relationship", namespaces={"ns": self.PACKAGE_RELATIONSHIPS_NAMESPACE}, ): target = rel.get("Target") if target and not target.startswith( ("http", "mailto:") ): # Skip external URLs # Resolve the target path relative to the .rels file location if rels_file.name == ".rels": # Root .rels file - targets are relative to unpacked_dir target_path = self.unpacked_dir / target else: # Other .rels files - targets are relative to their parent's parent # e.g., word/_rels/document.xml.rels -> targets relative to word/ base_dir = rels_dir.parent target_path = base_dir / target # Normalize the path and check if it exists try: target_path = target_path.resolve() if target_path.exists() and target_path.is_file(): referenced_files.add(target_path) all_referenced_files.add(target_path) else: broken_refs.append((target, rel.sourceline)) except (OSError, ValueError): broken_refs.append((target, rel.sourceline)) # Report broken references if broken_refs: rel_path = rels_file.relative_to(self.unpacked_dir) for broken_ref, line_num in broken_refs: errors.append( f" {rel_path}: Line {line_num}: Broken reference to {broken_ref}" ) except Exception as e: rel_path = rels_file.relative_to(self.unpacked_dir) errors.append(f" Error parsing {rel_path}: {e}") # Check for unreferenced files (files that exist but are not referenced anywhere) unreferenced_files = set(all_files) - all_referenced_files if unreferenced_files: for unref_file in sorted(unreferenced_files): unref_rel_path = unref_file.relative_to(self.unpacked_dir) errors.append(f" Unreferenced file: {unref_rel_path}") if errors: print(f"FAILED - Found {len(errors)} relationship validation errors:") for error in errors: print(error) print( "CRITICAL: These errors will cause the document to appear corrupt. " + "Broken references MUST be fixed, " + "and unreferenced files MUST be referenced or removed." ) return False else: if self.verbose: print( "PASSED - All references are valid and all files are properly referenced" ) return True def validate_all_relationship_ids(self): import lxml.etree errors = [] # Process each XML file that might contain r:id references for xml_file in self.xml_files: # Skip .rels files themselves if xml_file.suffix == ".rels": continue # Determine the corresponding .rels file # For dir/file.xml, it's dir/_rels/file.xml.rels rels_dir = xml_file.parent / "_rels" rels_file = rels_dir / f"{xml_file.name}.rels" # Skip if there's no corresponding .rels file (that's okay) if not rels_file.exists(): continue try: # Parse the .rels file to get valid relationship IDs and their types rels_root = lxml.etree.parse(str(rels_file)).getroot() rid_to_type = {} for rel in rels_root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ): rid = rel.get("Id") rel_type = rel.get("Type", "") if rid: # Check for duplicate rIds if rid in rid_to_type: rels_rel_path = rels_file.relative_to(self.unpacked_dir) errors.append( f" {rels_rel_path}: Line {rel.sourceline}: " f"Duplicate relationship ID '{rid}' (IDs must be unique)" ) # Extract just the type name from the full URL type_name = ( rel_type.split("/")[-1] if "/" in rel_type else rel_type ) rid_to_type[rid] = type_name # Parse the XML file to find all r:id references xml_root = lxml.etree.parse(str(xml_file)).getroot() # Find all elements with r:id attributes for elem in xml_root.iter(): # Check for r:id attribute (relationship ID) rid_attr = elem.get(f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id") if rid_attr: xml_rel_path = xml_file.relative_to(self.unpacked_dir) elem_name = ( elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag ) # Check if the ID exists if rid_attr not in rid_to_type: errors.append( f" {xml_rel_path}: Line {elem.sourceline}: " f"<{elem_name}> references non-existent relationship '{rid_attr}' " f"(valid IDs: {', '.join(sorted(rid_to_type.keys())[:5])}{'...' if len(rid_to_type) > 5 else ''})" ) # Check if we have type expectations for this element elif self.ELEMENT_RELATIONSHIP_TYPES: expected_type = self._get_expected_relationship_type( elem_name ) if expected_type: actual_type = rid_to_type[rid_attr] # Check if the actual type matches or contains the expected type if expected_type not in actual_type.lower(): errors.append( f" {xml_rel_path}: Line {elem.sourceline}: " f"<{elem_name}> references '{rid_attr}' which points to '{actual_type}' " f"but should point to a '{expected_type}' relationship" ) except Exception as e: xml_rel_path = xml_file.relative_to(self.unpacked_dir) errors.append(f" Error processing {xml_rel_path}: {e}") if errors: print(f"FAILED - Found {len(errors)} relationship ID reference errors:") for error in errors: print(error) print("\nThese ID mismatches will cause the document to appear corrupt!") return False else: if self.verbose: print("PASSED - All relationship ID references are valid") return True def _get_expected_relationship_type(self, element_name): # Normalize element name to lowercase elem_lower = element_name.lower() # Check explicit mapping first if elem_lower in self.ELEMENT_RELATIONSHIP_TYPES: return self.ELEMENT_RELATIONSHIP_TYPES[elem_lower] # Try pattern detection for common patterns # Pattern 1: Elements ending in "Id" often expect a relationship of the prefix type if elem_lower.endswith("id") and len(elem_lower) > 2: # e.g., "sldId" -> "sld", "sldMasterId" -> "sldMaster" prefix = elem_lower[:-2] # Remove "id" # Check if this might be a compound like "sldMasterId" if prefix.endswith("master"): return prefix.lower() elif prefix.endswith("layout"): return prefix.lower() else: # Simple case like "sldId" -> "slide" # Common transformations if prefix == "sld": return "slide" return prefix.lower() # Pattern 2: Elements ending in "Reference" expect a relationship of the prefix type if elem_lower.endswith("reference") and len(elem_lower) > 9: prefix = elem_lower[:-9] # Remove "reference" return prefix.lower() return None def validate_content_types(self): errors = [] # Find [Content_Types].xml file content_types_file = self.unpacked_dir / "[Content_Types].xml" if not content_types_file.exists(): print("FAILED - [Content_Types].xml file not found") return False try: # Parse and get all declared parts and extensions root = lxml.etree.parse(str(content_types_file)).getroot() declared_parts = set() declared_extensions = set() # Get Override declarations (specific files) for override in root.findall( f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Override" ): part_name = override.get("PartName") if part_name is not None: declared_parts.add(part_name.lstrip("/")) # Get Default declarations (by extension) for default in root.findall( f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Default" ): extension = default.get("Extension") if extension is not None: declared_extensions.add(extension.lower()) # Root elements that require content type declaration declarable_roots = { "sld", "sldLayout", "sldMaster", "presentation", # PowerPoint "document", # Word "workbook", "worksheet", # Excel "theme", # Common } # Common media file extensions that should be declared media_extensions = { "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "bmp": "image/bmp", "tiff": "image/tiff", "wmf": "image/x-wmf", "emf": "image/x-emf", } # Get all files in the unpacked directory all_files = list(self.unpacked_dir.rglob("*")) all_files = [f for f in all_files if f.is_file()] # Check all XML files for Override declarations for xml_file in self.xml_files: path_str = str(xml_file.relative_to(self.unpacked_dir)).replace( "\\", "/" ) # Skip non-content files if any( skip in path_str for skip in [".rels", "[Content_Types]", "docProps/", "_rels/"] ): continue try: root_tag = lxml.etree.parse(str(xml_file)).getroot().tag root_name = root_tag.split("}")[-1] if "}" in root_tag else root_tag if root_name in declarable_roots and path_str not in declared_parts: errors.append( f" {path_str}: File with <{root_name}> root not declared in [Content_Types].xml" ) except Exception: continue # Skip unparseable files # Check all non-XML files for Default extension declarations for file_path in all_files: # Skip XML files and metadata files (already checked above) if file_path.suffix.lower() in {".xml", ".rels"}: continue if file_path.name == "[Content_Types].xml": continue if "_rels" in file_path.parts or "docProps" in file_path.parts: continue extension = file_path.suffix.lstrip(".").lower() if extension and extension not in declared_extensions: # Check if it's a known media extension that should be declared if extension in media_extensions: relative_path = file_path.relative_to(self.unpacked_dir) errors.append( f' {relative_path}: File with extension \'{extension}\' not declared in [Content_Types].xml - should add: <Default Extension="{extension}" ContentType="{media_extensions[extension]}"/>' ) except Exception as e: errors.append(f" Error parsing [Content_Types].xml: {e}") if errors: print(f"FAILED - Found {len(errors)} content type declaration errors:") for error in errors: print(error) return False else: if self.verbose: print( "PASSED - All content files are properly declared in [Content_Types].xml" ) return True def validate_file_against_xsd(self, xml_file, verbose=False): # Resolve both paths to handle symlinks xml_file = Path(xml_file).resolve() unpacked_dir = self.unpacked_dir.resolve() # Validate current file is_valid, current_errors = self._validate_single_file_xsd( xml_file, unpacked_dir ) if is_valid is None: return None, set() # Skipped elif is_valid: return True, set() # Valid, no errors # Get errors from original file for this specific file original_errors = self._get_original_file_errors(xml_file) # Compare with original (both are guaranteed to be sets here) assert current_errors is not None new_errors = current_errors - original_errors if new_errors: if verbose: relative_path = xml_file.relative_to(unpacked_dir) print(f"FAILED - {relative_path}: {len(new_errors)} new error(s)") for error in list(new_errors)[:3]: truncated = error[:250] + "..." if len(error) > 250 else error print(f" - {truncated}") return False, new_errors else: # All errors existed in original if verbose: print( f"PASSED - No new errors (original had {len(current_errors)} errors)" ) return True, set() def validate_against_xsd(self): new_errors = [] original_error_count = 0 valid_count = 0 skipped_count = 0 for xml_file in self.xml_files: relative_path = str(xml_file.relative_to(self.unpacked_dir)) is_valid, new_file_errors = self.validate_file_against_xsd( xml_file, verbose=False ) if is_valid is None: skipped_count += 1 continue elif is_valid and not new_file_errors: valid_count += 1 continue elif is_valid: # Had errors but all existed in original original_error_count += 1 valid_count += 1 continue # Has new errors new_errors.append(f" {relative_path}: {len(new_file_errors)} new error(s)") for error in list(new_file_errors)[:3]: # Show first 3 errors new_errors.append( f" - {error[:250]}..." if len(error) > 250 else f" - {error}" ) # Print summary if self.verbose: print(f"Validated {len(self.xml_files)} files:") print(f" - Valid: {valid_count}") print(f" - Skipped (no schema): {skipped_count}") if original_error_count: print(f" - With original errors (ignored): {original_error_count}") print( f" - With NEW errors: {len(new_errors) > 0 and len([e for e in new_errors if not e.startswith(' ')]) or 0}" ) if new_errors: print("\nFAILED - Found NEW validation errors:") for error in new_errors: print(error) return False else: if self.verbose: print("\nPASSED - No new XSD validation errors introduced") return True def _get_schema_path(self, xml_file): # Check exact filename match if xml_file.name in self.SCHEMA_MAPPINGS: return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.name] # Check .rels files if xml_file.suffix == ".rels": return self.schemas_dir / self.SCHEMA_MAPPINGS[".rels"] # Check chart files if "charts/" in str(xml_file) and xml_file.name.startswith("chart"): return self.schemas_dir / self.SCHEMA_MAPPINGS["chart"] # Check theme files if "theme/" in str(xml_file) and xml_file.name.startswith("theme"): return self.schemas_dir / self.SCHEMA_MAPPINGS["theme"] # Check if file is in a main content folder and use appropriate schema if xml_file.parent.name in self.MAIN_CONTENT_FOLDERS: return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.parent.name] return None def _clean_ignorable_namespaces(self, xml_doc): # Create a clean copy xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") xml_copy = lxml.etree.fromstring(xml_string) # Remove attributes not in allowed namespaces for elem in xml_copy.iter(): attrs_to_remove = [] for attr in elem.attrib: # Check if attribute is from a namespace other than allowed ones if "{" in attr: ns = attr.split("}")[0][1:] if ns not in self.OOXML_NAMESPACES: attrs_to_remove.append(attr) # Remove collected attributes for attr in attrs_to_remove: del elem.attrib[attr] # Remove elements not in allowed namespaces self._remove_ignorable_elements(xml_copy) return lxml.etree.ElementTree(xml_copy) def _remove_ignorable_elements(self, root): elements_to_remove = [] # Find elements to remove for elem in list(root): # Skip non-element nodes (comments, processing instructions, etc.) if not hasattr(elem, "tag") or callable(elem.tag): continue tag_str = str(elem.tag) if tag_str.startswith("{"): ns = tag_str.split("}")[0][1:] if ns not in self.OOXML_NAMESPACES: elements_to_remove.append(elem) continue # Recursively clean child elements self._remove_ignorable_elements(elem) # Remove collected elements for elem in elements_to_remove: root.remove(elem) def _preprocess_for_mc_ignorable(self, xml_doc): # Remove mc:Ignorable attributes before validation root = xml_doc.getroot() # Remove mc:Ignorable attribute from root if f"{{{self.MC_NAMESPACE}}}Ignorable" in root.attrib: del root.attrib[f"{{{self.MC_NAMESPACE}}}Ignorable"] return xml_doc def _validate_single_file_xsd(self, xml_file, base_path): schema_path = self._get_schema_path(xml_file) if not schema_path: return None, None # Skip file try: # Load schema with open(schema_path, "rb") as xsd_file: parser = lxml.etree.XMLParser() xsd_doc = lxml.etree.parse( xsd_file, parser=parser, base_url=str(schema_path) ) schema = lxml.etree.XMLSchema(xsd_doc) # Load and preprocess XML with open(xml_file, "r") as f: xml_doc = lxml.etree.parse(f) xml_doc, _ = self._remove_template_tags_from_text_nodes(xml_doc) xml_doc = self._preprocess_for_mc_ignorable(xml_doc) # Clean ignorable namespaces if needed relative_path = xml_file.relative_to(base_path) if ( relative_path.parts and relative_path.parts[0] in self.MAIN_CONTENT_FOLDERS ): xml_doc = self._clean_ignorable_namespaces(xml_doc) # Validate if schema.validate(xml_doc): return True, set() else: errors = set() for error in schema.error_log: # Store normalized error message (without line numbers for comparison) errors.add(error.message) return False, errors except Exception as e: return False, {str(e)} def _get_original_file_errors(self, xml_file): import tempfile import zipfile # Resolve both paths to handle symlinks (e.g., /var vs /private/var on macOS) xml_file = Path(xml_file).resolve() unpacked_dir = self.unpacked_dir.resolve() relative_path = xml_file.relative_to(unpacked_dir) with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Extract original file with zipfile.ZipFile(self.original_file, "r") as zip_ref: zip_ref.extractall(temp_path) # Find corresponding file in original original_xml_file = temp_path / relative_path if not original_xml_file.exists(): # File didn't exist in original, so no original errors return set() # Validate the specific file in original is_valid, errors = self._validate_single_file_xsd( original_xml_file, temp_path ) return errors if errors else set() def _remove_template_tags_from_text_nodes(self, xml_doc): warnings = [] template_pattern = re.compile(r"\{\{[^}]*\}\}") # Create a copy of the document to avoid modifying the original xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") xml_copy = lxml.etree.fromstring(xml_string) def process_text_content(text, content_type): if not text: return text matches = list(template_pattern.finditer(text)) if matches: for match in matches: warnings.append( f"Found template tag in {content_type}: {match.group()}" ) return template_pattern.sub("", text) return text # Process all text nodes in the document for elem in xml_copy.iter(): # Skip processing if this is a w:t element if not hasattr(elem, "tag") or callable(elem.tag): continue tag_str = str(elem.tag) if tag_str.endswith("}t") or tag_str == "t": continue elem.text = process_text_content(elem.text, "text content") elem.tail = process_text_content(elem.tail, "tail content") return lxml.etree.ElementTree(xml_copy), warnings if __name__ == "__main__": raise RuntimeError("This module should not be run directly.")
--- +++ @@ -1,3 +1,6 @@+""" +Base validator with common validation logic for document files. +""" import re from pathlib import Path @@ -6,6 +9,7 @@ class BaseSchemaValidator: + """Base validator with common validation logic for document files.""" # Elements whose 'id' attributes must be unique within their file # Format: element_name -> (attribute_name, scope) @@ -117,9 +121,11 @@ print(f"Warning: No XML files found in {self.unpacked_dir}") def validate(self): + """Run all validation checks and return True if all pass.""" raise NotImplementedError("Subclasses must implement the validate method") def validate_xml(self): + """Validate that all XML files are well-formed.""" errors = [] for xml_file in self.xml_files: @@ -148,6 +154,7 @@ return True def validate_namespaces(self): + """Validate that namespace prefixes in Ignorable attributes are declared.""" errors = [] for xml_file in self.xml_files: @@ -177,6 +184,7 @@ return True def validate_unique_ids(self): + """Validate that specific IDs are unique according to OOXML requirements.""" errors = [] global_ids = {} # Track globally unique IDs across all files @@ -267,6 +275,9 @@ return True def validate_file_references(self): + """ + Validate that all .rels files properly reference files and that all files are referenced. + """ errors = [] # Find all .rels files @@ -375,6 +386,10 @@ return True def validate_all_relationship_ids(self): + """ + Validate that all r:id attributes in XML files reference existing IDs + in their corresponding .rels files, and optionally validate relationship types. + """ import lxml.etree errors = [] @@ -469,6 +484,10 @@ return True def _get_expected_relationship_type(self, element_name): + """ + Get the expected relationship type for an element. + First checks the explicit mapping, then tries pattern detection. + """ # Normalize element name to lowercase elem_lower = element_name.lower() @@ -501,6 +520,7 @@ return None def validate_content_types(self): + """Validate that all content files are properly declared in [Content_Types].xml.""" errors = [] # Find [Content_Types].xml file @@ -619,6 +639,15 @@ return True def validate_file_against_xsd(self, xml_file, verbose=False): + """Validate a single XML file against XSD schema, comparing with original. + + Args: + xml_file: Path to XML file to validate + verbose: Enable verbose output + + Returns: + tuple: (is_valid, new_errors_set) where is_valid is True/False/None (skipped) + """ # Resolve both paths to handle symlinks xml_file = Path(xml_file).resolve() unpacked_dir = self.unpacked_dir.resolve() @@ -657,6 +686,7 @@ return True, set() def validate_against_xsd(self): + """Validate XML files against XSD schemas, showing only new errors compared to original.""" new_errors = [] original_error_count = 0 valid_count = 0 @@ -709,6 +739,7 @@ return True def _get_schema_path(self, xml_file): + """Determine the appropriate schema path for an XML file.""" # Check exact filename match if xml_file.name in self.SCHEMA_MAPPINGS: return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.name] @@ -732,6 +763,7 @@ return None def _clean_ignorable_namespaces(self, xml_doc): + """Remove attributes and elements not in allowed namespaces.""" # Create a clean copy xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") xml_copy = lxml.etree.fromstring(xml_string) @@ -757,6 +789,7 @@ return lxml.etree.ElementTree(xml_copy) def _remove_ignorable_elements(self, root): + """Recursively remove all elements not in allowed namespaces.""" elements_to_remove = [] # Find elements to remove @@ -780,6 +813,7 @@ root.remove(elem) def _preprocess_for_mc_ignorable(self, xml_doc): + """Preprocess XML to handle mc:Ignorable attribute properly.""" # Remove mc:Ignorable attributes before validation root = xml_doc.getroot() @@ -790,6 +824,7 @@ return xml_doc def _validate_single_file_xsd(self, xml_file, base_path): + """Validate a single XML file against XSD schema. Returns (is_valid, errors_set).""" schema_path = self._get_schema_path(xml_file) if not schema_path: return None, None # Skip file @@ -832,6 +867,14 @@ return False, {str(e)} def _get_original_file_errors(self, xml_file): + """Get XSD validation errors from a single file in the original document. + + Args: + xml_file: Path to the XML file in unpacked_dir to check + + Returns: + set: Set of error messages from the original file + """ import tempfile import zipfile @@ -861,6 +904,15 @@ return errors if errors else set() def _remove_template_tags_from_text_nodes(self, xml_doc): + """Remove template tags from XML text nodes and collect warnings. + + Template tags follow the pattern {{ ... }} and are used as placeholders + for content replacement. They should be removed from text content before + XSD validation while preserving XML structure. + + Returns: + tuple: (cleaned_xml_doc, warnings_list) + """ warnings = [] template_pattern = re.compile(r"\{\{[^}]*\}\}") @@ -896,4 +948,4 @@ if __name__ == "__main__": - raise RuntimeError("This module should not be run directly.")+ raise RuntimeError("This module should not be run directly.")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/docx/ooxml/scripts/validation/base.py
Include argument descriptions in docstrings
#!/usr/bin/env python3 import html from pathlib import Path from typing import Optional, Union import defusedxml.minidom import defusedxml.sax class XMLEditor: def __init__(self, xml_path): self.xml_path = Path(xml_path) if not self.xml_path.exists(): raise ValueError(f"XML file not found: {xml_path}") with open(self.xml_path, "rb") as f: header = f.read(200).decode("utf-8", errors="ignore") self.encoding = "ascii" if 'encoding="ascii"' in header else "utf-8" parser = _create_line_tracking_parser() self.dom = defusedxml.minidom.parse(str(self.xml_path), parser) def get_node( self, tag: str, attrs: Optional[dict[str, str]] = None, line_number: Optional[Union[int, range]] = None, contains: Optional[str] = None, ): matches = [] for elem in self.dom.getElementsByTagName(tag): # Check line_number filter if line_number is not None: parse_pos = getattr(elem, "parse_position", (None,)) elem_line = parse_pos[0] # Handle both single line number and range if isinstance(line_number, range): if elem_line not in line_number: continue else: if elem_line != line_number: continue # Check attrs filter if attrs is not None: if not all( elem.getAttribute(attr_name) == attr_value for attr_name, attr_value in attrs.items() ): continue # Check contains filter if contains is not None: elem_text = self._get_element_text(elem) # Normalize the search string: convert HTML entities to Unicode characters # This allows searching for both "&#8220;Rowan" and ""Rowan" normalized_contains = html.unescape(contains) if normalized_contains not in elem_text: continue # If all applicable filters passed, this is a match matches.append(elem) if not matches: # Build descriptive error message filters = [] if line_number is not None: line_str = ( f"lines {line_number.start}-{line_number.stop - 1}" if isinstance(line_number, range) else f"line {line_number}" ) filters.append(f"at {line_str}") if attrs is not None: filters.append(f"with attributes {attrs}") if contains is not None: filters.append(f"containing '{contains}'") filter_desc = " ".join(filters) if filters else "" base_msg = f"Node not found: <{tag}> {filter_desc}".strip() # Add helpful hint based on filters used if contains: hint = "Text may be split across elements or use different wording." elif line_number: hint = "Line numbers may have changed if document was modified." elif attrs: hint = "Verify attribute values are correct." else: hint = "Try adding filters (attrs, line_number, or contains)." raise ValueError(f"{base_msg}. {hint}") if len(matches) > 1: raise ValueError( f"Multiple nodes found: <{tag}>. " f"Add more filters (attrs, line_number, or contains) to narrow the search." ) return matches[0] def _get_element_text(self, elem): text_parts = [] for node in elem.childNodes: if node.nodeType == node.TEXT_NODE: # Skip whitespace-only text nodes (XML formatting) if node.data.strip(): text_parts.append(node.data) elif node.nodeType == node.ELEMENT_NODE: text_parts.append(self._get_element_text(node)) return "".join(text_parts) def replace_node(self, elem, new_content): parent = elem.parentNode nodes = self._parse_fragment(new_content) for node in nodes: parent.insertBefore(node, elem) parent.removeChild(elem) return nodes def insert_after(self, elem, xml_content): parent = elem.parentNode next_sibling = elem.nextSibling nodes = self._parse_fragment(xml_content) for node in nodes: if next_sibling: parent.insertBefore(node, next_sibling) else: parent.appendChild(node) return nodes def insert_before(self, elem, xml_content): parent = elem.parentNode nodes = self._parse_fragment(xml_content) for node in nodes: parent.insertBefore(node, elem) return nodes def append_to(self, elem, xml_content): nodes = self._parse_fragment(xml_content) for node in nodes: elem.appendChild(node) return nodes def get_next_rid(self): max_id = 0 for rel_elem in self.dom.getElementsByTagName("Relationship"): rel_id = rel_elem.getAttribute("Id") if rel_id.startswith("rId"): try: max_id = max(max_id, int(rel_id[3:])) except ValueError: pass return f"rId{max_id + 1}" def save(self): content = self.dom.toxml(encoding=self.encoding) self.xml_path.write_bytes(content) def _parse_fragment(self, xml_content): # Extract namespace declarations from the root document element root_elem = self.dom.documentElement namespaces = [] if root_elem and root_elem.attributes: for i in range(root_elem.attributes.length): attr = root_elem.attributes.item(i) if attr.name.startswith("xmlns"): # type: ignore namespaces.append(f'{attr.name}="{attr.value}"') # type: ignore ns_decl = " ".join(namespaces) wrapper = f"<root {ns_decl}>{xml_content}</root>" fragment_doc = defusedxml.minidom.parseString(wrapper) nodes = [ self.dom.importNode(child, deep=True) for child in fragment_doc.documentElement.childNodes # type: ignore ] elements = [n for n in nodes if n.nodeType == n.ELEMENT_NODE] assert elements, "Fragment must contain at least one element" return nodes def _create_line_tracking_parser(): def set_content_handler(dom_handler): def startElementNS(name, tagName, attrs): orig_start_cb(name, tagName, attrs) cur_elem = dom_handler.elementStack[-1] cur_elem.parse_position = ( parser._parser.CurrentLineNumber, # type: ignore parser._parser.CurrentColumnNumber, # type: ignore ) orig_start_cb = dom_handler.startElementNS dom_handler.startElementNS = startElementNS orig_set_content_handler(dom_handler) parser = defusedxml.sax.make_parser() orig_set_content_handler = parser.setContentHandler parser.setContentHandler = set_content_handler # type: ignore return parser
--- +++ @@ -1,4 +1,34 @@ #!/usr/bin/env python3 +""" +Utilities for editing OOXML documents. + +This module provides XMLEditor, a tool for manipulating XML files with support for +line-number-based node finding and DOM manipulation. Each element is automatically +annotated with its original line and column position during parsing. + +Example usage: + editor = XMLEditor("document.xml") + + # Find node by line number or range + elem = editor.get_node(tag="w:r", line_number=519) + elem = editor.get_node(tag="w:p", line_number=range(100, 200)) + + # Find node by text content + elem = editor.get_node(tag="w:p", contains="specific text") + + # Find node by attributes + elem = editor.get_node(tag="w:r", attrs={"w:id": "target"}) + + # Combine filters + elem = editor.get_node(tag="w:p", line_number=range(1, 50), contains="text") + + # Replace, insert, or manipulate + new_elem = editor.replace_node(elem, "<w:r><w:t>new text</w:t></w:r>") + editor.insert_after(new_elem, "<w:r><w:t>more</w:t></w:r>") + + # Save changes + editor.save() +""" import html from pathlib import Path @@ -9,8 +39,29 @@ class XMLEditor: + """ + Editor for manipulating OOXML XML files with line-number-based node finding. + + This class parses XML files and tracks the original line and column position + of each element. This enables finding nodes by their line number in the original + file, which is useful when working with Read tool output. + + Attributes: + xml_path: Path to the XML file being edited + encoding: Detected encoding of the XML file ('ascii' or 'utf-8') + dom: Parsed DOM tree with parse_position attributes on elements + """ def __init__(self, xml_path): + """ + Initialize with path to XML file and parse with line number tracking. + + Args: + xml_path: Path to XML file to edit (str or Path) + + Raises: + ValueError: If the XML file does not exist + """ self.xml_path = Path(xml_path) if not self.xml_path.exists(): raise ValueError(f"XML file not found: {xml_path}") @@ -29,6 +80,35 @@ line_number: Optional[Union[int, range]] = None, contains: Optional[str] = None, ): + """ + Get a DOM element by tag and identifier. + + Finds an element by either its line number in the original file or by + matching attribute values. Exactly one match must be found. + + Args: + tag: The XML tag name (e.g., "w:del", "w:ins", "w:r") + attrs: Dictionary of attribute name-value pairs to match (e.g., {"w:id": "1"}) + line_number: Line number (int) or line range (range) in original XML file (1-indexed) + contains: Text string that must appear in any text node within the element. + Supports both entity notation (&#8220;) and Unicode characters (\u201c). + + Returns: + defusedxml.minidom.Element: The matching DOM element + + Raises: + ValueError: If node not found or multiple matches found + + Example: + elem = editor.get_node(tag="w:r", line_number=519) + elem = editor.get_node(tag="w:r", line_number=range(100, 200)) + elem = editor.get_node(tag="w:del", attrs={"w:id": "1"}) + elem = editor.get_node(tag="w:p", attrs={"w14:paraId": "12345678"}) + elem = editor.get_node(tag="w:commentRangeStart", attrs={"w:id": "0"}) + elem = editor.get_node(tag="w:p", contains="specific text") + elem = editor.get_node(tag="w:t", contains="&#8220;Agreement") # Entity notation + elem = editor.get_node(tag="w:t", contains="\u201cAgreement") # Unicode character + """ matches = [] for elem in self.dom.getElementsByTagName(tag): # Check line_number filter @@ -101,6 +181,18 @@ return matches[0] def _get_element_text(self, elem): + """ + Recursively extract all text content from an element. + + Skips text nodes that contain only whitespace (spaces, tabs, newlines), + which typically represent XML formatting rather than document content. + + Args: + elem: defusedxml.minidom.Element to extract text from + + Returns: + str: Concatenated text from all non-whitespace text nodes within the element + """ text_parts = [] for node in elem.childNodes: if node.nodeType == node.TEXT_NODE: @@ -112,6 +204,19 @@ return "".join(text_parts) def replace_node(self, elem, new_content): + """ + Replace a DOM element with new XML content. + + Args: + elem: defusedxml.minidom.Element to replace + new_content: String containing XML to replace the node with + + Returns: + List[defusedxml.minidom.Node]: All inserted nodes + + Example: + new_nodes = editor.replace_node(old_elem, "<w:r><w:t>text</w:t></w:r>") + """ parent = elem.parentNode nodes = self._parse_fragment(new_content) for node in nodes: @@ -120,6 +225,19 @@ return nodes def insert_after(self, elem, xml_content): + """ + Insert XML content after a DOM element. + + Args: + elem: defusedxml.minidom.Element to insert after + xml_content: String containing XML to insert + + Returns: + List[defusedxml.minidom.Node]: All inserted nodes + + Example: + new_nodes = editor.insert_after(elem, "<w:r><w:t>text</w:t></w:r>") + """ parent = elem.parentNode next_sibling = elem.nextSibling nodes = self._parse_fragment(xml_content) @@ -131,6 +249,19 @@ return nodes def insert_before(self, elem, xml_content): + """ + Insert XML content before a DOM element. + + Args: + elem: defusedxml.minidom.Element to insert before + xml_content: String containing XML to insert + + Returns: + List[defusedxml.minidom.Node]: All inserted nodes + + Example: + new_nodes = editor.insert_before(elem, "<w:r><w:t>text</w:t></w:r>") + """ parent = elem.parentNode nodes = self._parse_fragment(xml_content) for node in nodes: @@ -138,12 +269,26 @@ return nodes def append_to(self, elem, xml_content): + """ + Append XML content as a child of a DOM element. + + Args: + elem: defusedxml.minidom.Element to append to + xml_content: String containing XML to append + + Returns: + List[defusedxml.minidom.Node]: All inserted nodes + + Example: + new_nodes = editor.append_to(elem, "<w:r><w:t>text</w:t></w:r>") + """ nodes = self._parse_fragment(xml_content) for node in nodes: elem.appendChild(node) return nodes def get_next_rid(self): + """Get the next available rId for relationships files.""" max_id = 0 for rel_elem in self.dom.getElementsByTagName("Relationship"): rel_id = rel_elem.getAttribute("Id") @@ -155,10 +300,28 @@ return f"rId{max_id + 1}" def save(self): + """ + Save the edited XML back to the file. + + Serializes the DOM tree and writes it back to the original file path, + preserving the original encoding (ascii or utf-8). + """ content = self.dom.toxml(encoding=self.encoding) self.xml_path.write_bytes(content) def _parse_fragment(self, xml_content): + """ + Parse XML fragment and return list of imported nodes. + + Args: + xml_content: String containing XML fragment + + Returns: + List of defusedxml.minidom.Node objects imported into this document + + Raises: + AssertionError: If fragment contains no element nodes + """ # Extract namespace declarations from the root document element root_elem = self.dom.documentElement namespaces = [] @@ -181,6 +344,16 @@ def _create_line_tracking_parser(): + """ + Create a SAX parser that tracks line and column numbers for each element. + + Monkey patches the SAX content handler to store the current line and column + position from the underlying expat parser onto each element as a parse_position + attribute (line, column) tuple. + + Returns: + defusedxml.sax.xmlreader.XMLReader: Configured SAX parser + """ def set_content_handler(dom_handler): def startElementNS(name, tagName, attrs): @@ -198,4 +371,4 @@ parser = defusedxml.sax.make_parser() orig_set_content_handler = parser.setContentHandler parser.setContentHandler = set_content_handler # type: ignore - return parser+ return parser
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/docx/scripts/utilities.py
Please document this code using docstrings
#!/usr/bin/env python3 import sys from pathlib import Path import math import random sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image, ImageDraw import numpy as np from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced from core.visual_effects import ParticleSystem from core.easing import interpolate def create_explode_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 30, explode_type: str = 'burst', # 'burst', 'shatter', 'dissolve', 'implode' num_pieces: int = 20, explosion_speed: float = 5.0, center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] # Default object data if object_data is None: if object_type == 'emoji': object_data = {'emoji': '💣', 'size': 100} # Generate pieces/particles pieces = [] for _ in range(num_pieces): angle = random.uniform(0, 2 * math.pi) speed = random.uniform(explosion_speed * 0.5, explosion_speed * 1.5) vx = math.cos(angle) * speed vy = math.sin(angle) * speed size = random.randint(3, 12) color = ( random.randint(100, 255), random.randint(100, 255), random.randint(100, 255) ) rotation_speed = random.uniform(-20, 20) pieces.append({ 'vx': vx, 'vy': vy, 'size': size, 'color': color, 'rotation': 0, 'rotation_speed': rotation_speed }) for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 frame = create_blank_frame(frame_width, frame_height, bg_color) draw = ImageDraw.Draw(frame) if explode_type == 'burst': # Show object at start, then explode if t < 0.2: # Object still intact scale = interpolate(1.0, 1.2, t / 0.2, 'ease_out') if object_type == 'emoji': size = int(object_data['size'] * scale) draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(center_pos[0] - size // 2, center_pos[1] - size // 2), size=size, shadow=False ) else: # Exploded - draw pieces explosion_t = (t - 0.2) / 0.8 for piece in pieces: # Update position x = center_pos[0] + piece['vx'] * explosion_t * 50 y = center_pos[1] + piece['vy'] * explosion_t * 50 + 0.5 * 300 * explosion_t ** 2 # Gravity # Fade out alpha = 1.0 - explosion_t if alpha > 0: color = tuple(int(c * alpha) for c in piece['color']) size = int(piece['size'] * (1 - explosion_t * 0.5)) draw.ellipse( [x - size, y - size, x + size, y + size], fill=color ) elif explode_type == 'shatter': # Break into geometric pieces if t < 0.15: # Object intact if object_type == 'emoji': draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(center_pos[0] - object_data['size'] // 2, center_pos[1] - object_data['size'] // 2), size=object_data['size'], shadow=False ) else: # Shattered shatter_t = (t - 0.15) / 0.85 # Draw triangular shards for piece in pieces[:min(10, len(pieces))]: x = center_pos[0] + piece['vx'] * shatter_t * 30 y = center_pos[1] + piece['vy'] * shatter_t * 30 + 0.5 * 200 * shatter_t ** 2 # Update rotation rotation = piece['rotation_speed'] * shatter_t * 100 # Draw triangle shard shard_size = piece['size'] * 2 points = [] for j in range(3): angle = (rotation + j * 120) * math.pi / 180 px = x + shard_size * math.cos(angle) py = y + shard_size * math.sin(angle) points.append((px, py)) alpha = 1.0 - shatter_t if alpha > 0: color = tuple(int(c * alpha) for c in piece['color']) draw.polygon(points, fill=color) elif explode_type == 'dissolve': # Dissolve into particles dissolve_scale = interpolate(1.0, 0.0, t, 'ease_in') if dissolve_scale > 0.1: # Draw fading object if object_type == 'emoji': size = int(object_data['size'] * dissolve_scale) size = max(12, size) emoji_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji=object_data['emoji'], position=(center_pos[0] - size // 2, center_pos[1] - size // 2), size=size, shadow=False ) # Apply opacity from templates.fade import apply_opacity emoji_canvas = apply_opacity(emoji_canvas, dissolve_scale) frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, emoji_canvas) frame = frame.convert('RGB') draw = ImageDraw.Draw(frame) # Draw outward-moving particles for piece in pieces: x = center_pos[0] + piece['vx'] * t * 40 y = center_pos[1] + piece['vy'] * t * 40 alpha = 1.0 - t if alpha > 0: color = tuple(int(c * alpha) for c in piece['color']) size = int(piece['size'] * (1 - t * 0.5)) draw.ellipse( [x - size, y - size, x + size, y + size], fill=color ) elif explode_type == 'implode': # Reverse explosion - pieces fly inward if t < 0.7: # Pieces converging implode_t = 1.0 - (t / 0.7) for piece in pieces: x = center_pos[0] + piece['vx'] * implode_t * 50 y = center_pos[1] + piece['vy'] * implode_t * 50 alpha = 1.0 - (1.0 - implode_t) * 0.5 color = tuple(int(c * alpha) for c in piece['color']) size = int(piece['size'] * alpha) draw.ellipse( [x - size, y - size, x + size, y + size], fill=color ) else: # Object reforms reform_t = (t - 0.7) / 0.3 scale = interpolate(0.5, 1.0, reform_t, 'elastic_out') if object_type == 'emoji': size = int(object_data['size'] * scale) draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(center_pos[0] - size // 2, center_pos[1] - size // 2), size=size, shadow=False ) frames.append(frame) return frames def create_particle_burst( num_frames: int = 25, particle_count: int = 30, center_pos: tuple[int, int] = (240, 240), colors: list[tuple[int, int, int]] | None = None, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: particles = ParticleSystem() # Emit particles if colors is None: from core.color_palettes import get_palette palette = get_palette('vibrant') colors = [palette['primary'], palette['secondary'], palette['accent']] for _ in range(particle_count): color = random.choice(colors) particles.emit( center_pos[0], center_pos[1], count=1, speed=random.uniform(3, 8), color=color, lifetime=random.uniform(20, 30), size=random.randint(3, 8), shape='star' ) frames = [] for _ in range(num_frames): frame = create_blank_frame(frame_width, frame_height, bg_color) particles.update() particles.render(frame) frames.append(frame) return frames # Example usage if __name__ == '__main__': print("Creating explode animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Burst frames = create_explode_animation( object_type='emoji', object_data={'emoji': '💣', 'size': 100}, num_frames=30, explode_type='burst', num_pieces=25 ) builder.add_frames(frames) builder.save('explode_burst.gif', num_colors=128) # Example 2: Shatter builder.clear() frames = create_explode_animation( object_type='emoji', object_data={'emoji': '🪟', 'size': 100}, num_frames=30, explode_type='shatter', num_pieces=12 ) builder.add_frames(frames) builder.save('explode_shatter.gif', num_colors=128) # Example 3: Particle burst builder.clear() frames = create_particle_burst(num_frames=25, particle_count=40) builder.add_frames(frames) builder.save('explode_particles.gif', num_colors=128) print("Created explode animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Explode Animation - Break objects into pieces that fly outward. + +Creates explosion, shatter, and particle burst effects. +""" import sys from pathlib import Path @@ -27,6 +32,24 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create explosion animation. + + Args: + object_type: 'emoji', 'circle', 'text' + object_data: Object configuration + num_frames: Number of frames + explode_type: Type of explosion + num_pieces: Number of pieces/particles + explosion_speed: Speed of explosion + center_pos: Center position + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -223,6 +246,21 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create simple particle burst effect. + + Args: + num_frames: Number of frames + particle_count: Number of particles + center_pos: Burst center + colors: Particle colors (None for random) + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ particles = ParticleSystem() # Emit particles @@ -290,4 +328,4 @@ builder.add_frames(frames) builder.save('explode_particles.gif', num_colors=128) - print("Created explode animations!")+ print("Created explode animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/explode.py
Generate missing documentation strings
#!/usr/bin/env python3 import math def linear(t: float) -> float: return t def ease_in_quad(t: float) -> float: return t * t def ease_out_quad(t: float) -> float: return t * (2 - t) def ease_in_out_quad(t: float) -> float: if t < 0.5: return 2 * t * t return -1 + (4 - 2 * t) * t def ease_in_cubic(t: float) -> float: return t * t * t def ease_out_cubic(t: float) -> float: return (t - 1) * (t - 1) * (t - 1) + 1 def ease_in_out_cubic(t: float) -> float: if t < 0.5: return 4 * t * t * t return (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 def ease_in_bounce(t: float) -> float: return 1 - ease_out_bounce(1 - t) def ease_out_bounce(t: float) -> float: if t < 1 / 2.75: return 7.5625 * t * t elif t < 2 / 2.75: t -= 1.5 / 2.75 return 7.5625 * t * t + 0.75 elif t < 2.5 / 2.75: t -= 2.25 / 2.75 return 7.5625 * t * t + 0.9375 else: t -= 2.625 / 2.75 return 7.5625 * t * t + 0.984375 def ease_in_out_bounce(t: float) -> float: if t < 0.5: return ease_in_bounce(t * 2) * 0.5 return ease_out_bounce(t * 2 - 1) * 0.5 + 0.5 def ease_in_elastic(t: float) -> float: if t == 0 or t == 1: return t return -math.pow(2, 10 * (t - 1)) * math.sin((t - 1.1) * 5 * math.pi) def ease_out_elastic(t: float) -> float: if t == 0 or t == 1: return t return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) + 1 def ease_in_out_elastic(t: float) -> float: if t == 0 or t == 1: return t t = t * 2 - 1 if t < 0: return -0.5 * math.pow(2, 10 * t) * math.sin((t - 0.1) * 5 * math.pi) return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) * 0.5 + 1 # Convenience mapping EASING_FUNCTIONS = { 'linear': linear, 'ease_in': ease_in_quad, 'ease_out': ease_out_quad, 'ease_in_out': ease_in_out_quad, 'bounce_in': ease_in_bounce, 'bounce_out': ease_out_bounce, 'bounce': ease_in_out_bounce, 'elastic_in': ease_in_elastic, 'elastic_out': ease_out_elastic, 'elastic': ease_in_out_elastic, } def get_easing(name: str = 'linear'): return EASING_FUNCTIONS.get(name, linear) def interpolate(start: float, end: float, t: float, easing: str = 'linear') -> float: ease_func = get_easing(easing) eased_t = ease_func(t) return start + (end - start) * eased_t def ease_back_in(t: float) -> float: c1 = 1.70158 c3 = c1 + 1 return c3 * t * t * t - c1 * t * t def ease_back_out(t: float) -> float: c1 = 1.70158 c3 = c1 + 1 return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2) def ease_back_in_out(t: float) -> float: c1 = 1.70158 c2 = c1 * 1.525 if t < 0.5: return (pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2 return (pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2 def apply_squash_stretch(base_scale: tuple[float, float], intensity: float, direction: str = 'vertical') -> tuple[float, float]: width_scale, height_scale = base_scale if direction == 'vertical': # Compress vertically, expand horizontally (preserve volume) height_scale *= (1 - intensity * 0.5) width_scale *= (1 + intensity * 0.5) elif direction == 'horizontal': # Compress horizontally, expand vertically width_scale *= (1 - intensity * 0.5) height_scale *= (1 + intensity * 0.5) elif direction == 'both': # General squash (both dimensions) width_scale *= (1 - intensity * 0.3) height_scale *= (1 - intensity * 0.3) return (width_scale, height_scale) def calculate_arc_motion(start: tuple[float, float], end: tuple[float, float], height: float, t: float) -> tuple[float, float]: x1, y1 = start x2, y2 = end # Linear interpolation for x x = x1 + (x2 - x1) * t # Parabolic interpolation for y # y = start + progress * (end - start) + arc_offset # Arc offset peaks at t=0.5 arc_offset = 4 * height * t * (1 - t) y = y1 + (y2 - y1) * t - arc_offset return (x, y) # Add new easing functions to the convenience mapping EASING_FUNCTIONS.update({ 'back_in': ease_back_in, 'back_out': ease_back_out, 'back_in_out': ease_back_in_out, 'anticipate': ease_back_in, # Alias 'overshoot': ease_back_out, # Alias })
--- +++ @@ -1,45 +1,60 @@ #!/usr/bin/env python3 +""" +Easing Functions - Timing functions for smooth animations. + +Provides various easing functions for natural motion and timing. +All functions take a value t (0.0 to 1.0) and return eased value (0.0 to 1.0). +""" import math def linear(t: float) -> float: + """Linear interpolation (no easing).""" return t def ease_in_quad(t: float) -> float: + """Quadratic ease-in (slow start, accelerating).""" return t * t def ease_out_quad(t: float) -> float: + """Quadratic ease-out (fast start, decelerating).""" return t * (2 - t) def ease_in_out_quad(t: float) -> float: + """Quadratic ease-in-out (slow start and end).""" if t < 0.5: return 2 * t * t return -1 + (4 - 2 * t) * t def ease_in_cubic(t: float) -> float: + """Cubic ease-in (slow start).""" return t * t * t def ease_out_cubic(t: float) -> float: + """Cubic ease-out (fast start).""" return (t - 1) * (t - 1) * (t - 1) + 1 def ease_in_out_cubic(t: float) -> float: + """Cubic ease-in-out.""" if t < 0.5: return 4 * t * t * t return (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 def ease_in_bounce(t: float) -> float: + """Bounce ease-in (bouncy start).""" return 1 - ease_out_bounce(1 - t) def ease_out_bounce(t: float) -> float: + """Bounce ease-out (bouncy end).""" if t < 1 / 2.75: return 7.5625 * t * t elif t < 2 / 2.75: @@ -54,24 +69,28 @@ def ease_in_out_bounce(t: float) -> float: + """Bounce ease-in-out.""" if t < 0.5: return ease_in_bounce(t * 2) * 0.5 return ease_out_bounce(t * 2 - 1) * 0.5 + 0.5 def ease_in_elastic(t: float) -> float: + """Elastic ease-in (spring effect).""" if t == 0 or t == 1: return t return -math.pow(2, 10 * (t - 1)) * math.sin((t - 1.1) * 5 * math.pi) def ease_out_elastic(t: float) -> float: + """Elastic ease-out (spring effect).""" if t == 0 or t == 1: return t return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) + 1 def ease_in_out_elastic(t: float) -> float: + """Elastic ease-in-out.""" if t == 0 or t == 1: return t t = t * 2 - 1 @@ -96,28 +115,44 @@ def get_easing(name: str = 'linear'): + """Get easing function by name.""" return EASING_FUNCTIONS.get(name, linear) def interpolate(start: float, end: float, t: float, easing: str = 'linear') -> float: + """ + Interpolate between two values with easing. + + Args: + start: Start value + end: End value + t: Progress from 0.0 to 1.0 + easing: Name of easing function + + Returns: + Interpolated value + """ ease_func = get_easing(easing) eased_t = ease_func(t) return start + (end - start) * eased_t def ease_back_in(t: float) -> float: + """Back ease-in (slight overshoot backward before forward motion).""" c1 = 1.70158 c3 = c1 + 1 return c3 * t * t * t - c1 * t * t def ease_back_out(t: float) -> float: + """Back ease-out (overshoot forward then settle back).""" c1 = 1.70158 c3 = c1 + 1 return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2) def ease_back_in_out(t: float) -> float: + """Back ease-in-out (overshoot at both ends).""" c1 = 1.70158 c2 = c1 * 1.525 if t < 0.5: @@ -127,6 +162,17 @@ def apply_squash_stretch(base_scale: tuple[float, float], intensity: float, direction: str = 'vertical') -> tuple[float, float]: + """ + Calculate squash and stretch scales for more dynamic animation. + + Args: + base_scale: (width_scale, height_scale) base scales + intensity: Squash/stretch intensity (0.0-1.0) + direction: 'vertical', 'horizontal', or 'both' + + Returns: + (width_scale, height_scale) with squash/stretch applied + """ width_scale, height_scale = base_scale if direction == 'vertical': @@ -147,6 +193,18 @@ def calculate_arc_motion(start: tuple[float, float], end: tuple[float, float], height: float, t: float) -> tuple[float, float]: + """ + Calculate position along a parabolic arc (natural motion path). + + Args: + start: (x, y) starting position + end: (x, y) ending position + height: Arc height at midpoint (positive = upward) + t: Progress (0.0-1.0) + + Returns: + (x, y) position along arc + """ x1, y1 = start x2, y2 = end
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/easing.py
Add inline docstrings for readability
import re from .base import BaseSchemaValidator class PPTXSchemaValidator(BaseSchemaValidator): # PowerPoint presentation namespace PRESENTATIONML_NAMESPACE = ( "http://schemas.openxmlformats.org/presentationml/2006/main" ) # PowerPoint-specific element to relationship type mappings ELEMENT_RELATIONSHIP_TYPES = { "sldid": "slide", "sldmasterid": "slidemaster", "notesmasterid": "notesmaster", "sldlayoutid": "slidelayout", "themeid": "theme", "tablestyleid": "tablestyles", } def validate(self): # Test 0: XML well-formedness if not self.validate_xml(): return False # Test 1: Namespace declarations all_valid = True if not self.validate_namespaces(): all_valid = False # Test 2: Unique IDs if not self.validate_unique_ids(): all_valid = False # Test 3: UUID ID validation if not self.validate_uuid_ids(): all_valid = False # Test 4: Relationship and file reference validation if not self.validate_file_references(): all_valid = False # Test 5: Slide layout ID validation if not self.validate_slide_layout_ids(): all_valid = False # Test 6: Content type declarations if not self.validate_content_types(): all_valid = False # Test 7: XSD schema validation if not self.validate_against_xsd(): all_valid = False # Test 8: Notes slide reference validation if not self.validate_notes_slide_references(): all_valid = False # Test 9: Relationship ID reference validation if not self.validate_all_relationship_ids(): all_valid = False # Test 10: Duplicate slide layout references validation if not self.validate_no_duplicate_slide_layouts(): all_valid = False return all_valid def validate_uuid_ids(self): import lxml.etree errors = [] # UUID pattern: 8-4-4-4-12 hex digits with optional braces/hyphens uuid_pattern = re.compile( r"^[\{\(]?[0-9A-Fa-f]{8}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{12}[\}\)]?$" ) for xml_file in self.xml_files: try: root = lxml.etree.parse(str(xml_file)).getroot() # Check all elements for ID attributes for elem in root.iter(): for attr, value in elem.attrib.items(): # Check if this is an ID attribute attr_name = attr.split("}")[-1].lower() if attr_name == "id" or attr_name.endswith("id"): # Check if value looks like a UUID (has the right length and pattern structure) if self._looks_like_uuid(value): # Validate that it contains only hex characters in the right positions if not uuid_pattern.match(value): errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: " f"Line {elem.sourceline}: ID '{value}' appears to be a UUID but contains invalid hex characters" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} UUID ID validation errors:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All UUID-like IDs contain valid hex values") return True def _looks_like_uuid(self, value): # Remove common UUID delimiters clean_value = value.strip("{}()").replace("-", "") # Check if it's 32 hex-like characters (could include invalid hex chars) return len(clean_value) == 32 and all(c.isalnum() for c in clean_value) def validate_slide_layout_ids(self): import lxml.etree errors = [] # Find all slide master files slide_masters = list(self.unpacked_dir.glob("ppt/slideMasters/*.xml")) if not slide_masters: if self.verbose: print("PASSED - No slide masters found") return True for slide_master in slide_masters: try: # Parse the slide master file root = lxml.etree.parse(str(slide_master)).getroot() # Find the corresponding _rels file for this slide master rels_file = slide_master.parent / "_rels" / f"{slide_master.name}.rels" if not rels_file.exists(): errors.append( f" {slide_master.relative_to(self.unpacked_dir)}: " f"Missing relationships file: {rels_file.relative_to(self.unpacked_dir)}" ) continue # Parse the relationships file rels_root = lxml.etree.parse(str(rels_file)).getroot() # Build a set of valid relationship IDs that point to slide layouts valid_layout_rids = set() for rel in rels_root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ): rel_type = rel.get("Type", "") if "slideLayout" in rel_type: valid_layout_rids.add(rel.get("Id")) # Find all sldLayoutId elements in the slide master for sld_layout_id in root.findall( f".//{{{self.PRESENTATIONML_NAMESPACE}}}sldLayoutId" ): r_id = sld_layout_id.get( f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id" ) layout_id = sld_layout_id.get("id") if r_id and r_id not in valid_layout_rids: errors.append( f" {slide_master.relative_to(self.unpacked_dir)}: " f"Line {sld_layout_id.sourceline}: sldLayoutId with id='{layout_id}' " f"references r:id='{r_id}' which is not found in slide layout relationships" ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {slide_master.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print(f"FAILED - Found {len(errors)} slide layout ID validation errors:") for error in errors: print(error) print( "Remove invalid references or add missing slide layouts to the relationships file." ) return False else: if self.verbose: print("PASSED - All slide layout IDs reference valid slide layouts") return True def validate_no_duplicate_slide_layouts(self): import lxml.etree errors = [] slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels")) for rels_file in slide_rels_files: try: root = lxml.etree.parse(str(rels_file)).getroot() # Find all slideLayout relationships layout_rels = [ rel for rel in root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ) if "slideLayout" in rel.get("Type", "") ] if len(layout_rels) > 1: errors.append( f" {rels_file.relative_to(self.unpacked_dir)}: has {len(layout_rels)} slideLayout references" ) except Exception as e: errors.append( f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}" ) if errors: print("FAILED - Found slides with duplicate slideLayout references:") for error in errors: print(error) return False else: if self.verbose: print("PASSED - All slides have exactly one slideLayout reference") return True def validate_notes_slide_references(self): import lxml.etree errors = [] notes_slide_references = {} # Track which slides reference each notesSlide # Find all slide relationship files slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels")) if not slide_rels_files: if self.verbose: print("PASSED - No slide relationship files found") return True for rels_file in slide_rels_files: try: # Parse the relationships file root = lxml.etree.parse(str(rels_file)).getroot() # Find all notesSlide relationships for rel in root.findall( f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" ): rel_type = rel.get("Type", "") if "notesSlide" in rel_type: target = rel.get("Target", "") if target: # Normalize the target path to handle relative paths normalized_target = target.replace("../", "") # Track which slide references this notesSlide slide_name = rels_file.stem.replace( ".xml", "" ) # e.g., "slide1" if normalized_target not in notes_slide_references: notes_slide_references[normalized_target] = [] notes_slide_references[normalized_target].append( (slide_name, rels_file) ) except (lxml.etree.XMLSyntaxError, Exception) as e: errors.append( f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}" ) # Check for duplicate references for target, references in notes_slide_references.items(): if len(references) > 1: slide_names = [ref[0] for ref in references] errors.append( f" Notes slide '{target}' is referenced by multiple slides: {', '.join(slide_names)}" ) for slide_name, rels_file in references: errors.append(f" - {rels_file.relative_to(self.unpacked_dir)}") if errors: print( f"FAILED - Found {len([e for e in errors if not e.startswith(' ')])} notes slide reference validation errors:" ) for error in errors: print(error) print("Each slide may optionally have its own slide file.") return False else: if self.verbose: print("PASSED - All notes slide references are unique") return True if __name__ == "__main__": raise RuntimeError("This module should not be run directly.")
--- +++ @@ -1,3 +1,6 @@+""" +Validator for PowerPoint presentation XML files against XSD schemas. +""" import re @@ -5,6 +8,7 @@ class PPTXSchemaValidator(BaseSchemaValidator): + """Validator for PowerPoint presentation XML files against XSD schemas.""" # PowerPoint presentation namespace PRESENTATIONML_NAMESPACE = ( @@ -22,6 +26,7 @@ } def validate(self): + """Run all validation checks and return True if all pass.""" # Test 0: XML well-formedness if not self.validate_xml(): return False @@ -70,6 +75,7 @@ return all_valid def validate_uuid_ids(self): + """Validate that ID attributes that look like UUIDs contain only hex values.""" import lxml.etree errors = [] @@ -113,12 +119,14 @@ return True def _looks_like_uuid(self, value): + """Check if a value has the general structure of a UUID.""" # Remove common UUID delimiters clean_value = value.strip("{}()").replace("-", "") # Check if it's 32 hex-like characters (could include invalid hex chars) return len(clean_value) == 32 and all(c.isalnum() for c in clean_value) def validate_slide_layout_ids(self): + """Validate that sldLayoutId elements in slide masters reference valid slide layouts.""" import lxml.etree errors = [] @@ -193,6 +201,7 @@ return True def validate_no_duplicate_slide_layouts(self): + """Validate that each slide has exactly one slideLayout reference.""" import lxml.etree errors = [] @@ -232,6 +241,7 @@ return True def validate_notes_slide_references(self): + """Validate that each notesSlide file is referenced by only one slide.""" import lxml.etree errors = [] @@ -302,4 +312,4 @@ if __name__ == "__main__": - raise RuntimeError("This module should not be run directly.")+ raise RuntimeError("This module should not be run directly.")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/ooxml/scripts/validation/pptx.py
Write docstrings describing each step
import json import sys from pypdf import PdfReader, PdfWriter from pypdf.annotations import FreeText # Fills a PDF by adding text annotations defined in `fields.json`. See forms.md. def transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height): # Image coordinates: origin at top-left, y increases downward # PDF coordinates: origin at bottom-left, y increases upward x_scale = pdf_width / image_width y_scale = pdf_height / image_height left = bbox[0] * x_scale right = bbox[2] * x_scale # Flip Y coordinates for PDF top = pdf_height - (bbox[1] * y_scale) bottom = pdf_height - (bbox[3] * y_scale) return left, bottom, right, top def fill_pdf_form(input_pdf_path, fields_json_path, output_pdf_path): # `fields.json` format described in forms.md. with open(fields_json_path, "r") as f: fields_data = json.load(f) # Open the PDF reader = PdfReader(input_pdf_path) writer = PdfWriter() # Copy all pages to writer writer.append(reader) # Get PDF dimensions for each page pdf_dimensions = {} for i, page in enumerate(reader.pages): mediabox = page.mediabox pdf_dimensions[i + 1] = [mediabox.width, mediabox.height] # Process each form field annotations = [] for field in fields_data["form_fields"]: page_num = field["page_number"] # Get page dimensions and transform coordinates. page_info = next(p for p in fields_data["pages"] if p["page_number"] == page_num) image_width = page_info["image_width"] image_height = page_info["image_height"] pdf_width, pdf_height = pdf_dimensions[page_num] transformed_entry_box = transform_coordinates( field["entry_bounding_box"], image_width, image_height, pdf_width, pdf_height ) # Skip empty fields if "entry_text" not in field or "text" not in field["entry_text"]: continue entry_text = field["entry_text"] text = entry_text["text"] if not text: continue font_name = entry_text.get("font", "Arial") font_size = str(entry_text.get("font_size", 14)) + "pt" font_color = entry_text.get("font_color", "000000") # Font size/color seems to not work reliably across viewers: # https://github.com/py-pdf/pypdf/issues/2084 annotation = FreeText( text=text, rect=transformed_entry_box, font=font_name, font_size=font_size, font_color=font_color, border_color=None, background_color=None, ) annotations.append(annotation) # page_number is 0-based for pypdf writer.add_annotation(page_number=page_num - 1, annotation=annotation) # Save the filled PDF with open(output_pdf_path, "wb") as output: writer.write(output) print(f"Successfully filled PDF form and saved to {output_pdf_path}") print(f"Added {len(annotations)} text annotations") if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: fill_pdf_form_with_annotations.py [input pdf] [fields.json] [output pdf]") sys.exit(1) input_pdf = sys.argv[1] fields_json = sys.argv[2] output_pdf = sys.argv[3] fill_pdf_form(input_pdf, fields_json, output_pdf)
--- +++ @@ -9,6 +9,7 @@ def transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height): + """Transform bounding box from image coordinates to PDF coordinates""" # Image coordinates: origin at top-left, y increases downward # PDF coordinates: origin at bottom-left, y increases upward x_scale = pdf_width / image_width @@ -25,6 +26,7 @@ def fill_pdf_form(input_pdf_path, fields_json_path, output_pdf_path): + """Fill the PDF form with data from fields.json""" # `fields.json` format described in forms.md. with open(fields_json_path, "r") as f:
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pdf/scripts/fill_pdf_form_with_annotations.py
Add clean documentation to messy code
#!/usr/bin/env python3 from PIL import Image, ImageDraw, ImageFilter import numpy as np import math import random from typing import Optional class Particle: def __init__(self, x: float, y: float, vx: float, vy: float, lifetime: float, color: tuple[int, int, int], size: int = 3, shape: str = 'circle'): self.x = x self.y = y self.vx = vx self.vy = vy self.lifetime = lifetime self.max_lifetime = lifetime self.color = color self.size = size self.shape = shape self.gravity = 0.5 # Pixels per frame squared self.drag = 0.98 # Velocity multiplier per frame def update(self): # Apply physics self.vy += self.gravity self.vx *= self.drag self.vy *= self.drag # Update position self.x += self.vx self.y += self.vy # Decrease lifetime self.lifetime -= 1 def is_alive(self) -> bool: return self.lifetime > 0 def get_alpha(self) -> float: return max(0, min(1, self.lifetime / self.max_lifetime)) def render(self, frame: Image.Image): if not self.is_alive(): return draw = ImageDraw.Draw(frame) alpha = self.get_alpha() # Calculate faded color color = tuple(int(c * alpha) for c in self.color) # Draw based on shape x, y = int(self.x), int(self.y) size = max(1, int(self.size * alpha)) if self.shape == 'circle': bbox = [x - size, y - size, x + size, y + size] draw.ellipse(bbox, fill=color) elif self.shape == 'square': bbox = [x - size, y - size, x + size, y + size] draw.rectangle(bbox, fill=color) elif self.shape == 'star': # Simple 4-point star points = [ (x, y - size), (x - size // 2, y), (x, y), (x, y + size), (x, y), (x + size // 2, y), ] draw.line(points, fill=color, width=2) class ParticleSystem: def __init__(self): self.particles: list[Particle] = [] def emit(self, x: int, y: int, count: int = 10, spread: float = 2.0, speed: float = 5.0, color: tuple[int, int, int] = (255, 200, 0), lifetime: float = 20.0, size: int = 3, shape: str = 'circle'): for _ in range(count): # Random angle and speed angle = random.uniform(0, 2 * math.pi) vel_mag = random.uniform(speed * 0.5, speed * 1.5) vx = math.cos(angle) * vel_mag vy = math.sin(angle) * vel_mag # Random lifetime variation life = random.uniform(lifetime * 0.7, lifetime * 1.3) particle = Particle(x, y, vx, vy, life, color, size, shape) self.particles.append(particle) def emit_confetti(self, x: int, y: int, count: int = 20, colors: Optional[list[tuple[int, int, int]]] = None): if colors is None: colors = [ (255, 107, 107), (255, 159, 64), (255, 218, 121), (107, 185, 240), (162, 155, 254), (255, 182, 193) ] for _ in range(count): color = random.choice(colors) vx = random.uniform(-3, 3) vy = random.uniform(-8, -2) shape = random.choice(['square', 'circle']) size = random.randint(2, 4) lifetime = random.uniform(40, 60) particle = Particle(x, y, vx, vy, lifetime, color, size, shape) particle.gravity = 0.3 # Lighter gravity for confetti self.particles.append(particle) def emit_sparkles(self, x: int, y: int, count: int = 15): colors = [(255, 255, 200), (255, 255, 255), (255, 255, 150)] for _ in range(count): color = random.choice(colors) angle = random.uniform(0, 2 * math.pi) speed = random.uniform(1, 3) vx = math.cos(angle) * speed vy = math.sin(angle) * speed lifetime = random.uniform(15, 30) particle = Particle(x, y, vx, vy, lifetime, color, 2, 'star') particle.gravity = 0 particle.drag = 0.95 self.particles.append(particle) def update(self): # Update alive particles for particle in self.particles: particle.update() # Remove dead particles self.particles = [p for p in self.particles if p.is_alive()] def render(self, frame: Image.Image): for particle in self.particles: particle.render(frame) def get_particle_count(self) -> int: return len(self.particles) def add_motion_blur(frame: Image.Image, prev_frame: Optional[Image.Image], blur_amount: float = 0.5) -> Image.Image: if prev_frame is None: return frame # Blend current frame with previous frame frame_array = np.array(frame, dtype=np.float32) prev_array = np.array(prev_frame, dtype=np.float32) blended = frame_array * (1 - blur_amount) + prev_array * blur_amount blended = np.clip(blended, 0, 255).astype(np.uint8) return Image.fromarray(blended) def create_impact_flash(frame: Image.Image, position: tuple[int, int], radius: int = 100, intensity: float = 0.7) -> Image.Image: # Create overlay overlay = Image.new('RGBA', frame.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay) x, y = position # Draw concentric circles with decreasing opacity num_circles = 5 for i in range(num_circles): alpha = int(255 * intensity * (1 - i / num_circles)) r = radius * (1 - i / num_circles) color = (255, 255, 240, alpha) # Warm white bbox = [x - r, y - r, x + r, y + r] draw.ellipse(bbox, fill=color) # Composite onto frame frame_rgba = frame.convert('RGBA') frame_rgba = Image.alpha_composite(frame_rgba, overlay) return frame_rgba.convert('RGB') def create_shockwave_rings(frame: Image.Image, position: tuple[int, int], radii: list[int], color: tuple[int, int, int] = (255, 200, 0), width: int = 3) -> Image.Image: draw = ImageDraw.Draw(frame) x, y = position for radius in radii: bbox = [x - radius, y - radius, x + radius, y + radius] draw.ellipse(bbox, outline=color, width=width) return frame def create_explosion_effect(frame: Image.Image, position: tuple[int, int], radius: int, progress: float, color: tuple[int, int, int] = (255, 150, 0)) -> Image.Image: current_radius = int(radius * progress) fade = 1 - progress # Create overlay overlay = Image.new('RGBA', frame.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay) x, y = position # Draw expanding circle with fade alpha = int(255 * fade) r, g, b = color circle_color = (r, g, b, alpha) bbox = [x - current_radius, y - current_radius, x + current_radius, y + current_radius] draw.ellipse(bbox, fill=circle_color) # Composite frame_rgba = frame.convert('RGBA') frame_rgba = Image.alpha_composite(frame_rgba, overlay) return frame_rgba.convert('RGB') def add_glow_effect(frame: Image.Image, mask_color: tuple[int, int, int], glow_color: tuple[int, int, int], blur_radius: int = 10) -> Image.Image: # Create mask of target color frame_array = np.array(frame) mask = np.all(frame_array == mask_color, axis=-1) # Create glow layer glow = Image.new('RGB', frame.size, (0, 0, 0)) glow_array = np.array(glow) glow_array[mask] = glow_color glow = Image.fromarray(glow_array) # Blur the glow glow = glow.filter(ImageFilter.GaussianBlur(blur_radius)) # Blend with original blended = Image.blend(frame, glow, 0.5) return blended def add_drop_shadow(frame: Image.Image, object_bounds: tuple[int, int, int, int], shadow_offset: tuple[int, int] = (5, 5), shadow_color: tuple[int, int, int] = (0, 0, 0), blur: int = 5) -> Image.Image: # Extract object x1, y1, x2, y2 = object_bounds obj = frame.crop((x1, y1, x2, y2)) # Create shadow shadow = Image.new('RGBA', obj.size, (*shadow_color, 180)) # Create frame with alpha frame_rgba = frame.convert('RGBA') # Paste shadow shadow_pos = (x1 + shadow_offset[0], y1 + shadow_offset[1]) frame_rgba.paste(shadow, shadow_pos, shadow) # Paste object on top frame_rgba.paste(obj, (x1, y1)) return frame_rgba.convert('RGB') def create_speed_lines(frame: Image.Image, position: tuple[int, int], direction: float, length: int = 50, count: int = 5, color: tuple[int, int, int] = (200, 200, 200)) -> Image.Image: draw = ImageDraw.Draw(frame) x, y = position # Opposite direction (lines trail behind) trail_angle = direction + math.pi for i in range(count): # Offset from center offset_angle = trail_angle + random.uniform(-0.3, 0.3) offset_dist = random.uniform(10, 30) start_x = x + math.cos(offset_angle) * offset_dist start_y = y + math.sin(offset_angle) * offset_dist # End point line_length = random.uniform(length * 0.7, length * 1.3) end_x = start_x + math.cos(trail_angle) * line_length end_y = start_y + math.sin(trail_angle) * line_length # Draw line with varying opacity alpha = random.randint(100, 200) width = random.randint(1, 3) # Simple line (full opacity simulation) draw.line([(start_x, start_y), (end_x, end_y)], fill=color, width=width) return frame def create_screen_shake_offset(intensity: int, frame_index: int) -> tuple[int, int]: # Use frame index for deterministic but random-looking shake random.seed(frame_index) offset_x = random.randint(-intensity, intensity) offset_y = random.randint(-intensity, intensity) random.seed() # Reset seed return (offset_x, offset_y) def apply_screen_shake(frame: Image.Image, intensity: int, frame_index: int) -> Image.Image: offset_x, offset_y = create_screen_shake_offset(intensity, frame_index) # Create new frame with background shaken = Image.new('RGB', frame.size, (0, 0, 0)) # Paste original frame with offset shaken.paste(frame, (offset_x, offset_y)) return shaken
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +Visual Effects - Particles, motion blur, impacts, and other effects for GIFs. + +This module provides high-impact visual effects that make animations feel +professional and dynamic while keeping file sizes reasonable. +""" from PIL import Image, ImageDraw, ImageFilter import numpy as np @@ -8,10 +14,22 @@ class Particle: + """A single particle in a particle system.""" def __init__(self, x: float, y: float, vx: float, vy: float, lifetime: float, color: tuple[int, int, int], size: int = 3, shape: str = 'circle'): + """ + Initialize a particle. + + Args: + x, y: Starting position + vx, vy: Velocity + lifetime: How long particle lives (in frames) + color: RGB color + size: Particle size in pixels + shape: 'circle', 'square', or 'star' + """ self.x = x self.y = y self.vx = vx @@ -25,6 +43,7 @@ self.drag = 0.98 # Velocity multiplier per frame def update(self): + """Update particle position and lifetime.""" # Apply physics self.vy += self.gravity self.vx *= self.drag @@ -38,12 +57,20 @@ self.lifetime -= 1 def is_alive(self) -> bool: + """Check if particle is still alive.""" return self.lifetime > 0 def get_alpha(self) -> float: + """Get particle opacity based on lifetime.""" return max(0, min(1, self.lifetime / self.max_lifetime)) def render(self, frame: Image.Image): + """ + Render particle to frame. + + Args: + frame: PIL Image to draw on + """ if not self.is_alive(): return @@ -77,14 +104,29 @@ class ParticleSystem: + """Manages a collection of particles.""" def __init__(self): + """Initialize particle system.""" self.particles: list[Particle] = [] def emit(self, x: int, y: int, count: int = 10, spread: float = 2.0, speed: float = 5.0, color: tuple[int, int, int] = (255, 200, 0), lifetime: float = 20.0, size: int = 3, shape: str = 'circle'): + """ + Emit a burst of particles. + + Args: + x, y: Emission position + count: Number of particles to emit + spread: Angle spread (radians) + speed: Initial speed + color: Particle color + lifetime: Particle lifetime in frames + size: Particle size + shape: Particle shape + """ for _ in range(count): # Random angle and speed angle = random.uniform(0, 2 * math.pi) @@ -100,6 +142,14 @@ def emit_confetti(self, x: int, y: int, count: int = 20, colors: Optional[list[tuple[int, int, int]]] = None): + """ + Emit confetti particles (colorful, falling). + + Args: + x, y: Emission position + count: Number of confetti pieces + colors: List of colors (random if None) + """ if colors is None: colors = [ (255, 107, 107), (255, 159, 64), (255, 218, 121), @@ -119,6 +169,13 @@ self.particles.append(particle) def emit_sparkles(self, x: int, y: int, count: int = 15): + """ + Emit sparkle particles (twinkling stars). + + Args: + x, y: Emission position + count: Number of sparkles + """ colors = [(255, 255, 200), (255, 255, 255), (255, 255, 150)] for _ in range(count): @@ -135,6 +192,7 @@ self.particles.append(particle) def update(self): + """Update all particles.""" # Update alive particles for particle in self.particles: particle.update() @@ -143,15 +201,28 @@ self.particles = [p for p in self.particles if p.is_alive()] def render(self, frame: Image.Image): + """Render all particles to frame.""" for particle in self.particles: particle.render(frame) def get_particle_count(self) -> int: + """Get number of active particles.""" return len(self.particles) def add_motion_blur(frame: Image.Image, prev_frame: Optional[Image.Image], blur_amount: float = 0.5) -> Image.Image: + """ + Add motion blur by blending with previous frame. + + Args: + frame: Current frame + prev_frame: Previous frame (None for first frame) + blur_amount: Amount of blur (0.0-1.0) + + Returns: + Frame with motion blur applied + """ if prev_frame is None: return frame @@ -167,6 +238,18 @@ def create_impact_flash(frame: Image.Image, position: tuple[int, int], radius: int = 100, intensity: float = 0.7) -> Image.Image: + """ + Create a bright flash effect at impact point. + + Args: + frame: PIL Image to draw on + position: Center of flash + radius: Flash radius + intensity: Flash intensity (0.0-1.0) + + Returns: + Modified frame + """ # Create overlay overlay = Image.new('RGBA', frame.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay) @@ -192,6 +275,19 @@ def create_shockwave_rings(frame: Image.Image, position: tuple[int, int], radii: list[int], color: tuple[int, int, int] = (255, 200, 0), width: int = 3) -> Image.Image: + """ + Create expanding ring effects. + + Args: + frame: PIL Image to draw on + position: Center of rings + radii: List of ring radii + color: Ring color + width: Ring width + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) x, y = position @@ -205,6 +301,19 @@ def create_explosion_effect(frame: Image.Image, position: tuple[int, int], radius: int, progress: float, color: tuple[int, int, int] = (255, 150, 0)) -> Image.Image: + """ + Create an explosion effect that expands and fades. + + Args: + frame: PIL Image to draw on + position: Explosion center + radius: Maximum radius + progress: Animation progress (0.0-1.0) + color: Explosion color + + Returns: + Modified frame + """ current_radius = int(radius * progress) fade = 1 - progress @@ -231,6 +340,18 @@ def add_glow_effect(frame: Image.Image, mask_color: tuple[int, int, int], glow_color: tuple[int, int, int], blur_radius: int = 10) -> Image.Image: + """ + Add a glow effect to areas of a specific color. + + Args: + frame: PIL Image + mask_color: Color to create glow around + glow_color: Color of glow + blur_radius: Blur amount + + Returns: + Frame with glow + """ # Create mask of target color frame_array = np.array(frame) mask = np.all(frame_array == mask_color, axis=-1) @@ -253,6 +374,19 @@ shadow_offset: tuple[int, int] = (5, 5), shadow_color: tuple[int, int, int] = (0, 0, 0), blur: int = 5) -> Image.Image: + """ + Add drop shadow to an object. + + Args: + frame: PIL Image + object_bounds: (x1, y1, x2, y2) bounds of object + shadow_offset: (x, y) offset of shadow + shadow_color: Shadow color + blur: Shadow blur amount + + Returns: + Frame with shadow + """ # Extract object x1, y1, x2, y2 = object_bounds obj = frame.crop((x1, y1, x2, y2)) @@ -276,6 +410,20 @@ def create_speed_lines(frame: Image.Image, position: tuple[int, int], direction: float, length: int = 50, count: int = 5, color: tuple[int, int, int] = (200, 200, 200)) -> Image.Image: + """ + Create speed lines for motion effect. + + Args: + frame: PIL Image to draw on + position: Center position + direction: Angle in radians (0 = right, pi/2 = down) + length: Line length + count: Number of lines + color: Line color + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) x, y = position @@ -305,6 +453,16 @@ def create_screen_shake_offset(intensity: int, frame_index: int) -> tuple[int, int]: + """ + Calculate screen shake offset for a frame. + + Args: + intensity: Shake intensity in pixels + frame_index: Current frame number + + Returns: + (x, y) offset tuple + """ # Use frame index for deterministic but random-looking shake random.seed(frame_index) offset_x = random.randint(-intensity, intensity) @@ -314,6 +472,17 @@ def apply_screen_shake(frame: Image.Image, intensity: int, frame_index: int) -> Image.Image: + """ + Apply screen shake effect to entire frame. + + Args: + frame: PIL Image + intensity: Shake intensity + frame_index: Current frame number + + Returns: + Shaken frame + """ offset_x, offset_y = create_screen_shake_offset(intensity, frame_index) # Create new frame with background
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/visual_effects.py
Generate documentation strings for clarity
#!/usr/bin/env python3 from typing import Optional import colorsys # Professional color palettes - hand-picked for GIF compression and visual appeal VIBRANT = { 'primary': (255, 68, 68), # Bright red 'secondary': (255, 168, 0), # Bright orange 'accent': (0, 168, 255), # Bright blue 'success': (68, 255, 68), # Bright green 'background': (240, 248, 255), # Alice blue 'text': (30, 30, 30), # Almost black 'text_light': (255, 255, 255), # White } PASTEL = { 'primary': (255, 179, 186), # Pastel pink 'secondary': (255, 223, 186), # Pastel peach 'accent': (186, 225, 255), # Pastel blue 'success': (186, 255, 201), # Pastel green 'background': (255, 250, 240), # Floral white 'text': (80, 80, 80), # Dark gray 'text_light': (255, 255, 255), # White } DARK = { 'primary': (255, 100, 100), # Muted red 'secondary': (100, 200, 255), # Muted blue 'accent': (255, 200, 100), # Muted gold 'success': (100, 255, 150), # Muted green 'background': (30, 30, 35), # Almost black 'text': (220, 220, 220), # Light gray 'text_light': (255, 255, 255), # White } NEON = { 'primary': (255, 16, 240), # Neon pink 'secondary': (0, 255, 255), # Cyan 'accent': (255, 255, 0), # Yellow 'success': (57, 255, 20), # Neon green 'background': (20, 20, 30), # Dark blue-black 'text': (255, 255, 255), # White 'text_light': (255, 255, 255), # White } PROFESSIONAL = { 'primary': (0, 122, 255), # System blue 'secondary': (88, 86, 214), # System purple 'accent': (255, 149, 0), # System orange 'success': (52, 199, 89), # System green 'background': (255, 255, 255), # White 'text': (0, 0, 0), # Black 'text_light': (255, 255, 255), # White } WARM = { 'primary': (255, 107, 107), # Coral red 'secondary': (255, 159, 64), # Orange 'accent': (255, 218, 121), # Yellow 'success': (106, 176, 76), # Olive green 'background': (255, 246, 229), # Warm white 'text': (51, 51, 51), # Charcoal 'text_light': (255, 255, 255), # White } COOL = { 'primary': (107, 185, 240), # Sky blue 'secondary': (130, 202, 157), # Mint 'accent': (162, 155, 254), # Lavender 'success': (86, 217, 150), # Aqua green 'background': (240, 248, 255), # Alice blue 'text': (45, 55, 72), # Dark slate 'text_light': (255, 255, 255), # White } MONOCHROME = { 'primary': (80, 80, 80), # Dark gray 'secondary': (130, 130, 130), # Medium gray 'accent': (180, 180, 180), # Light gray 'success': (100, 100, 100), # Gray 'background': (245, 245, 245), # Off-white 'text': (30, 30, 30), # Almost black 'text_light': (255, 255, 255), # White } # Map of palette names PALETTES = { 'vibrant': VIBRANT, 'pastel': PASTEL, 'dark': DARK, 'neon': NEON, 'professional': PROFESSIONAL, 'warm': WARM, 'cool': COOL, 'monochrome': MONOCHROME, } def get_palette(name: str = 'vibrant') -> dict: return PALETTES.get(name.lower(), VIBRANT) def get_text_color_for_background(bg_color: tuple[int, int, int]) -> tuple[int, int, int]: # Calculate relative luminance r, g, b = bg_color luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255 # Return black for light backgrounds, white for dark return (0, 0, 0) if luminance > 0.5 else (255, 255, 255) def get_complementary_color(color: tuple[int, int, int]) -> tuple[int, int, int]: # Convert to HSV r, g, b = [x / 255.0 for x in color] h, s, v = colorsys.rgb_to_hsv(r, g, b) # Rotate hue by 180 degrees (0.5 in 0-1 scale) h_comp = (h + 0.5) % 1.0 # Convert back to RGB r_comp, g_comp, b_comp = colorsys.hsv_to_rgb(h_comp, s, v) return (int(r_comp * 255), int(g_comp * 255), int(b_comp * 255)) def lighten_color(color: tuple[int, int, int], amount: float = 0.3) -> tuple[int, int, int]: r, g, b = color r = min(255, int(r + (255 - r) * amount)) g = min(255, int(g + (255 - g) * amount)) b = min(255, int(b + (255 - b) * amount)) return (r, g, b) def darken_color(color: tuple[int, int, int], amount: float = 0.3) -> tuple[int, int, int]: r, g, b = color r = max(0, int(r * (1 - amount))) g = max(0, int(g * (1 - amount))) b = max(0, int(b * (1 - amount))) return (r, g, b) def blend_colors(color1: tuple[int, int, int], color2: tuple[int, int, int], ratio: float = 0.5) -> tuple[int, int, int]: r1, g1, b1 = color1 r2, g2, b2 = color2 r = int(r1 * (1 - ratio) + r2 * ratio) g = int(g1 * (1 - ratio) + g2 * ratio) b = int(b1 * (1 - ratio) + b2 * ratio) return (r, g, b) def create_gradient_colors(start_color: tuple[int, int, int], end_color: tuple[int, int, int], steps: int) -> list[tuple[int, int, int]]: colors = [] for i in range(steps): ratio = i / (steps - 1) if steps > 1 else 0 colors.append(blend_colors(start_color, end_color, ratio)) return colors # Impact/emphasis colors that work well across palettes IMPACT_COLORS = { 'flash': (255, 255, 240), # Bright flash (cream) 'explosion': (255, 150, 0), # Orange explosion 'electricity': (100, 200, 255), # Electric blue 'fire': (255, 100, 0), # Fire orange-red 'success': (50, 255, 100), # Success green 'error': (255, 50, 50), # Error red 'warning': (255, 200, 0), # Warning yellow 'magic': (200, 100, 255), # Magic purple } def get_impact_color(effect_type: str = 'flash') -> tuple[int, int, int]: return IMPACT_COLORS.get(effect_type, IMPACT_COLORS['flash']) # Emoji-safe palettes (work well at 128x128 with 32-64 colors) EMOJI_PALETTES = { 'simple': [ (255, 255, 255), # White (0, 0, 0), # Black (255, 100, 100), # Red (100, 255, 100), # Green (100, 100, 255), # Blue (255, 255, 100), # Yellow ], 'vibrant_emoji': [ (255, 255, 255), # White (30, 30, 30), # Black (255, 68, 68), # Red (68, 255, 68), # Green (68, 68, 255), # Blue (255, 200, 68), # Gold (255, 68, 200), # Pink (68, 255, 200), # Cyan ] } def get_emoji_palette(name: str = 'simple') -> list[tuple[int, int, int]]: return EMOJI_PALETTES.get(name, EMOJI_PALETTES['simple'])
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +Color Palettes - Professional, harmonious color schemes for GIFs. + +Using consistent, well-designed color palettes makes GIFs look professional +and polished instead of random and amateurish. +""" from typing import Optional import colorsys @@ -100,10 +106,30 @@ def get_palette(name: str = 'vibrant') -> dict: + """ + Get a color palette by name. + + Args: + name: Palette name (vibrant, pastel, dark, neon, professional, warm, cool, monochrome) + + Returns: + Dictionary of color roles to RGB tuples + """ return PALETTES.get(name.lower(), VIBRANT) def get_text_color_for_background(bg_color: tuple[int, int, int]) -> tuple[int, int, int]: + """ + Get the best text color (black or white) for a given background. + + Uses luminance calculation to ensure readability. + + Args: + bg_color: Background RGB color + + Returns: + Text color (black or white) that contrasts well + """ # Calculate relative luminance r, g, b = bg_color luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255 @@ -113,6 +139,15 @@ def get_complementary_color(color: tuple[int, int, int]) -> tuple[int, int, int]: + """ + Get the complementary (opposite) color on the color wheel. + + Args: + color: RGB color tuple + + Returns: + Complementary RGB color + """ # Convert to HSV r, g, b = [x / 255.0 for x in color] h, s, v = colorsys.rgb_to_hsv(r, g, b) @@ -126,6 +161,16 @@ def lighten_color(color: tuple[int, int, int], amount: float = 0.3) -> tuple[int, int, int]: + """ + Lighten a color by a given amount. + + Args: + color: RGB color tuple + amount: Amount to lighten (0.0-1.0) + + Returns: + Lightened RGB color + """ r, g, b = color r = min(255, int(r + (255 - r) * amount)) g = min(255, int(g + (255 - g) * amount)) @@ -134,6 +179,16 @@ def darken_color(color: tuple[int, int, int], amount: float = 0.3) -> tuple[int, int, int]: + """ + Darken a color by a given amount. + + Args: + color: RGB color tuple + amount: Amount to darken (0.0-1.0) + + Returns: + Darkened RGB color + """ r, g, b = color r = max(0, int(r * (1 - amount))) g = max(0, int(g * (1 - amount))) @@ -143,6 +198,17 @@ def blend_colors(color1: tuple[int, int, int], color2: tuple[int, int, int], ratio: float = 0.5) -> tuple[int, int, int]: + """ + Blend two colors together. + + Args: + color1: First RGB color + color2: Second RGB color + ratio: Blend ratio (0.0 = all color1, 1.0 = all color2) + + Returns: + Blended RGB color + """ r1, g1, b1 = color1 r2, g2, b2 = color2 @@ -156,6 +222,17 @@ def create_gradient_colors(start_color: tuple[int, int, int], end_color: tuple[int, int, int], steps: int) -> list[tuple[int, int, int]]: + """ + Create a gradient of colors between two colors. + + Args: + start_color: Starting RGB color + end_color: Ending RGB color + steps: Number of gradient steps + + Returns: + List of RGB colors forming gradient + """ colors = [] for i in range(steps): ratio = i / (steps - 1) if steps > 1 else 0 @@ -177,6 +254,15 @@ def get_impact_color(effect_type: str = 'flash') -> tuple[int, int, int]: + """ + Get a color for impact/emphasis effects. + + Args: + effect_type: Type of effect (flash, explosion, electricity, etc.) + + Returns: + RGB color for effect + """ return IMPACT_COLORS.get(effect_type, IMPACT_COLORS['flash']) @@ -204,4 +290,13 @@ def get_emoji_palette(name: str = 'simple') -> list[tuple[int, int, int]]: + """ + Get a limited color palette optimized for emoji GIFs (<64KB). + + Args: + name: Palette name (simple, vibrant_emoji) + + Returns: + List of RGB colors (6-8 colors) + """ return EMOJI_PALETTES.get(name, EMOJI_PALETTES['simple'])
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/color_palettes.py
Please document this code using docstrings
#!/usr/bin/env python3 import argparse import shutil import sys from copy import deepcopy from pathlib import Path import six from pptx import Presentation def main(): parser = argparse.ArgumentParser( description="Rearrange PowerPoint slides based on a sequence of indices.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python rearrange.py template.pptx output.pptx 0,34,34,50,52 Creates output.pptx using slides 0, 34 (twice), 50, and 52 from template.pptx python rearrange.py template.pptx output.pptx 5,3,1,2,4 Creates output.pptx with slides reordered as specified Note: Slide indices are 0-based (first slide is 0, second is 1, etc.) """, ) parser.add_argument("template", help="Path to template PPTX file") parser.add_argument("output", help="Path for output PPTX file") parser.add_argument( "sequence", help="Comma-separated sequence of slide indices (0-based)" ) args = parser.parse_args() # Parse the slide sequence try: slide_sequence = [int(x.strip()) for x in args.sequence.split(",")] except ValueError: print( "Error: Invalid sequence format. Use comma-separated integers (e.g., 0,34,34,50,52)" ) sys.exit(1) # Check template exists template_path = Path(args.template) if not template_path.exists(): print(f"Error: Template file not found: {args.template}") sys.exit(1) # Create output directory if needed output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) try: rearrange_presentation(template_path, output_path, slide_sequence) except ValueError as e: print(f"Error: {e}") sys.exit(1) except Exception as e: print(f"Error processing presentation: {e}") sys.exit(1) def duplicate_slide(pres, index): source = pres.slides[index] # Use source's layout to preserve formatting new_slide = pres.slides.add_slide(source.slide_layout) # Collect all image and media relationships from the source slide image_rels = {} for rel_id, rel in six.iteritems(source.part.rels): if "image" in rel.reltype or "media" in rel.reltype: image_rels[rel_id] = rel # CRITICAL: Clear placeholder shapes to avoid duplicates for shape in new_slide.shapes: sp = shape.element sp.getparent().remove(sp) # Copy all shapes from source for shape in source.shapes: el = shape.element new_el = deepcopy(el) new_slide.shapes._spTree.insert_element_before(new_el, "p:extLst") # Handle picture shapes - need to update the blip reference # Look for all blip elements (they can be in pic or other contexts) # Using the element's own xpath method without namespaces argument blips = new_el.xpath(".//a:blip[@r:embed]") for blip in blips: old_rId = blip.get( "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed" ) if old_rId in image_rels: # Create a new relationship in the destination slide for this image old_rel = image_rels[old_rId] # get_or_add returns the rId directly, or adds and returns new rId new_rId = new_slide.part.rels.get_or_add( old_rel.reltype, old_rel._target ) # Update the blip's embed reference to use the new relationship ID blip.set( "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed", new_rId, ) # Copy any additional image/media relationships that might be referenced elsewhere for rel_id, rel in image_rels.items(): try: new_slide.part.rels.get_or_add(rel.reltype, rel._target) except Exception: pass # Relationship might already exist return new_slide def delete_slide(pres, index): rId = pres.slides._sldIdLst[index].rId pres.part.drop_rel(rId) del pres.slides._sldIdLst[index] def reorder_slides(pres, slide_index, target_index): slides = pres.slides._sldIdLst # Remove slide element from current position slide_element = slides[slide_index] slides.remove(slide_element) # Insert at target position slides.insert(target_index, slide_element) def rearrange_presentation(template_path, output_path, slide_sequence): # Copy template to preserve dimensions and theme if template_path != output_path: shutil.copy2(template_path, output_path) prs = Presentation(output_path) else: prs = Presentation(template_path) total_slides = len(prs.slides) # Validate indices for idx in slide_sequence: if idx < 0 or idx >= total_slides: raise ValueError(f"Slide index {idx} out of range (0-{total_slides - 1})") # Track original slides and their duplicates slide_map = [] # List of actual slide indices for final presentation duplicated = {} # Track duplicates: original_idx -> [duplicate_indices] # Step 1: DUPLICATE repeated slides print(f"Processing {len(slide_sequence)} slides from template...") for i, template_idx in enumerate(slide_sequence): if template_idx in duplicated and duplicated[template_idx]: # Already duplicated this slide, use the duplicate slide_map.append(duplicated[template_idx].pop(0)) print(f" [{i}] Using duplicate of slide {template_idx}") elif slide_sequence.count(template_idx) > 1 and template_idx not in duplicated: # First occurrence of a repeated slide - create duplicates slide_map.append(template_idx) duplicates = [] count = slide_sequence.count(template_idx) - 1 print( f" [{i}] Using original slide {template_idx}, creating {count} duplicate(s)" ) for _ in range(count): duplicate_slide(prs, template_idx) duplicates.append(len(prs.slides) - 1) duplicated[template_idx] = duplicates else: # Unique slide or first occurrence already handled, use original slide_map.append(template_idx) print(f" [{i}] Using original slide {template_idx}") # Step 2: DELETE unwanted slides (work backwards) slides_to_keep = set(slide_map) print(f"\nDeleting {len(prs.slides) - len(slides_to_keep)} unused slides...") for i in range(len(prs.slides) - 1, -1, -1): if i not in slides_to_keep: delete_slide(prs, i) # Update slide_map indices after deletion slide_map = [idx - 1 if idx > i else idx for idx in slide_map] # Step 3: REORDER to final sequence print(f"Reordering {len(slide_map)} slides to final sequence...") for target_pos in range(len(slide_map)): # Find which slide should be at target_pos current_pos = slide_map[target_pos] if current_pos != target_pos: reorder_slides(prs, current_pos, target_pos) # Update slide_map: the move shifts other slides for i in range(len(slide_map)): if slide_map[i] > current_pos and slide_map[i] <= target_pos: slide_map[i] -= 1 elif slide_map[i] < current_pos and slide_map[i] >= target_pos: slide_map[i] += 1 slide_map[target_pos] = target_pos # Save the presentation prs.save(output_path) print(f"\nSaved rearranged presentation to: {output_path}") print(f"Final presentation has {len(prs.slides)} slides") if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3 +""" +Rearrange PowerPoint slides based on a sequence of indices. + +Usage: + python rearrange.py template.pptx output.pptx 0,34,34,50,52 + +This will create output.pptx using slides from template.pptx in the specified order. +Slides can be repeated (e.g., 34 appears twice). +""" import argparse import shutil @@ -64,6 +73,7 @@ def duplicate_slide(pres, index): + """Duplicate a slide in the presentation.""" source = pres.slides[index] # Use source's layout to preserve formatting @@ -118,12 +128,14 @@ def delete_slide(pres, index): + """Delete a slide from the presentation.""" rId = pres.slides._sldIdLst[index].rId pres.part.drop_rel(rId) del pres.slides._sldIdLst[index] def reorder_slides(pres, slide_index, target_index): + """Move a slide from one position to another.""" slides = pres.slides._sldIdLst # Remove slide element from current position @@ -135,6 +147,14 @@ def rearrange_presentation(template_path, output_path, slide_sequence): + """ + Create a new presentation with slides from template in specified order. + + Args: + template_path: Path to template PPTX file + output_path: Path for output PPTX file + slide_sequence: List of slide indices (0-based) to include + """ # Copy template to preserve dimensions and theme if template_path != output_path: shutil.copy2(template_path, output_path) @@ -208,4 +228,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/rearrange.py
Create documentation for each function signature
#!/usr/bin/env python3 import argparse import json import platform import sys from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union from PIL import Image, ImageDraw, ImageFont from pptx import Presentation from pptx.enum.text import PP_ALIGN from pptx.shapes.base import BaseShape # Type aliases for cleaner signatures JsonValue = Union[str, int, float, bool, None] ParagraphDict = Dict[str, JsonValue] ShapeDict = Dict[ str, Union[str, float, bool, List[ParagraphDict], List[str], Dict[str, Any], None] ] InventoryData = Dict[ str, Dict[str, "ShapeData"] ] # Dict of slide_id -> {shape_id -> ShapeData} InventoryDict = Dict[str, Dict[str, ShapeDict]] # JSON-serializable inventory def main(): parser = argparse.ArgumentParser( description="Extract text inventory from PowerPoint with proper GroupShape support.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python inventory.py presentation.pptx inventory.json Extracts text inventory with correct absolute positions for grouped shapes python inventory.py presentation.pptx inventory.json --issues-only Extracts only text shapes that have overflow or overlap issues The output JSON includes: - All text content organized by slide and shape - Correct absolute positions for shapes in groups - Visual position and size in inches - Paragraph properties and formatting - Issue detection: text overflow and shape overlaps """, ) parser.add_argument("input", help="Input PowerPoint file (.pptx)") parser.add_argument("output", help="Output JSON file for inventory") parser.add_argument( "--issues-only", action="store_true", help="Include only text shapes that have overflow or overlap issues", ) args = parser.parse_args() input_path = Path(args.input) if not input_path.exists(): print(f"Error: Input file not found: {args.input}") sys.exit(1) if not input_path.suffix.lower() == ".pptx": print("Error: Input must be a PowerPoint file (.pptx)") sys.exit(1) try: print(f"Extracting text inventory from: {args.input}") if args.issues_only: print( "Filtering to include only text shapes with issues (overflow/overlap)" ) inventory = extract_text_inventory(input_path, issues_only=args.issues_only) output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) save_inventory(inventory, output_path) print(f"Output saved to: {args.output}") # Report statistics total_slides = len(inventory) total_shapes = sum(len(shapes) for shapes in inventory.values()) if args.issues_only: if total_shapes > 0: print( f"Found {total_shapes} text elements with issues in {total_slides} slides" ) else: print("No issues discovered") else: print( f"Found text in {total_slides} slides with {total_shapes} text elements" ) except Exception as e: print(f"Error processing presentation: {e}") import traceback traceback.print_exc() sys.exit(1) @dataclass class ShapeWithPosition: shape: BaseShape absolute_left: int # in EMUs absolute_top: int # in EMUs class ParagraphData: def __init__(self, paragraph: Any): self.text: str = paragraph.text.strip() self.bullet: bool = False self.level: Optional[int] = None self.alignment: Optional[str] = None self.space_before: Optional[float] = None self.space_after: Optional[float] = None self.font_name: Optional[str] = None self.font_size: Optional[float] = None self.bold: Optional[bool] = None self.italic: Optional[bool] = None self.underline: Optional[bool] = None self.color: Optional[str] = None self.theme_color: Optional[str] = None self.line_spacing: Optional[float] = None # Check for bullet formatting if ( hasattr(paragraph, "_p") and paragraph._p is not None and paragraph._p.pPr is not None ): pPr = paragraph._p.pPr ns = "{http://schemas.openxmlformats.org/drawingml/2006/main}" if ( pPr.find(f"{ns}buChar") is not None or pPr.find(f"{ns}buAutoNum") is not None ): self.bullet = True if hasattr(paragraph, "level"): self.level = paragraph.level # Add alignment if not LEFT (default) if hasattr(paragraph, "alignment") and paragraph.alignment is not None: alignment_map = { PP_ALIGN.CENTER: "CENTER", PP_ALIGN.RIGHT: "RIGHT", PP_ALIGN.JUSTIFY: "JUSTIFY", } if paragraph.alignment in alignment_map: self.alignment = alignment_map[paragraph.alignment] # Add spacing properties if set if hasattr(paragraph, "space_before") and paragraph.space_before: self.space_before = paragraph.space_before.pt if hasattr(paragraph, "space_after") and paragraph.space_after: self.space_after = paragraph.space_after.pt # Extract font properties from first run if paragraph.runs: first_run = paragraph.runs[0] if hasattr(first_run, "font"): font = first_run.font if font.name: self.font_name = font.name if font.size: self.font_size = font.size.pt if font.bold is not None: self.bold = font.bold if font.italic is not None: self.italic = font.italic if font.underline is not None: self.underline = font.underline # Handle color - both RGB and theme colors try: # Try RGB color first if font.color.rgb: self.color = str(font.color.rgb) except (AttributeError, TypeError): # Fall back to theme color try: if font.color.theme_color: self.theme_color = font.color.theme_color.name except (AttributeError, TypeError): pass # Add line spacing if set if hasattr(paragraph, "line_spacing") and paragraph.line_spacing is not None: if hasattr(paragraph.line_spacing, "pt"): self.line_spacing = round(paragraph.line_spacing.pt, 2) else: # Multiplier - convert to points font_size = self.font_size if self.font_size else 12.0 self.line_spacing = round(paragraph.line_spacing * font_size, 2) def to_dict(self) -> ParagraphDict: result: ParagraphDict = {"text": self.text} # Add optional fields only if they have values if self.bullet: result["bullet"] = self.bullet if self.level is not None: result["level"] = self.level if self.alignment: result["alignment"] = self.alignment if self.space_before is not None: result["space_before"] = self.space_before if self.space_after is not None: result["space_after"] = self.space_after if self.font_name: result["font_name"] = self.font_name if self.font_size is not None: result["font_size"] = self.font_size if self.bold is not None: result["bold"] = self.bold if self.italic is not None: result["italic"] = self.italic if self.underline is not None: result["underline"] = self.underline if self.color: result["color"] = self.color if self.theme_color: result["theme_color"] = self.theme_color if self.line_spacing is not None: result["line_spacing"] = self.line_spacing return result class ShapeData: @staticmethod def emu_to_inches(emu: int) -> float: return emu / 914400.0 @staticmethod def inches_to_pixels(inches: float, dpi: int = 96) -> int: return int(inches * dpi) @staticmethod def get_font_path(font_name: str) -> Optional[str]: system = platform.system() # Common font file variations to try font_variations = [ font_name, font_name.lower(), font_name.replace(" ", ""), font_name.replace(" ", "-"), ] # Define font directories and extensions by platform if system == "Darwin": # macOS font_dirs = [ "/System/Library/Fonts/", "/Library/Fonts/", "~/Library/Fonts/", ] extensions = [".ttf", ".otf", ".ttc", ".dfont"] else: # Linux font_dirs = [ "/usr/share/fonts/truetype/", "/usr/local/share/fonts/", "~/.fonts/", ] extensions = [".ttf", ".otf"] # Try to find the font file from pathlib import Path for font_dir in font_dirs: font_dir_path = Path(font_dir).expanduser() if not font_dir_path.exists(): continue # First try exact matches for variant in font_variations: for ext in extensions: font_path = font_dir_path / f"{variant}{ext}" if font_path.exists(): return str(font_path) # Then try fuzzy matching - find files containing the font name try: for file_path in font_dir_path.iterdir(): if file_path.is_file(): file_name_lower = file_path.name.lower() font_name_lower = font_name.lower().replace(" ", "") if font_name_lower in file_name_lower and any( file_name_lower.endswith(ext) for ext in extensions ): return str(file_path) except (OSError, PermissionError): continue return None @staticmethod def get_slide_dimensions(slide: Any) -> tuple[Optional[int], Optional[int]]: try: prs = slide.part.package.presentation_part.presentation return prs.slide_width, prs.slide_height except (AttributeError, TypeError): return None, None @staticmethod def get_default_font_size(shape: BaseShape, slide_layout: Any) -> Optional[float]: try: if not hasattr(shape, "placeholder_format"): return None shape_type = shape.placeholder_format.type # type: ignore for layout_placeholder in slide_layout.placeholders: if layout_placeholder.placeholder_format.type == shape_type: # Find first defRPr element with sz (size) attribute for elem in layout_placeholder.element.iter(): if "defRPr" in elem.tag and (sz := elem.get("sz")): return float(sz) / 100.0 # Convert EMUs to points break except Exception: pass return None def __init__( self, shape: BaseShape, absolute_left: Optional[int] = None, absolute_top: Optional[int] = None, slide: Optional[Any] = None, ): self.shape = shape # Store reference to original shape self.shape_id: str = "" # Will be set after sorting # Get slide dimensions from slide object self.slide_width_emu, self.slide_height_emu = ( self.get_slide_dimensions(slide) if slide else (None, None) ) # Get placeholder type if applicable self.placeholder_type: Optional[str] = None self.default_font_size: Optional[float] = None if hasattr(shape, "is_placeholder") and shape.is_placeholder: # type: ignore if shape.placeholder_format and shape.placeholder_format.type: # type: ignore self.placeholder_type = ( str(shape.placeholder_format.type).split(".")[-1].split(" ")[0] # type: ignore ) # Get default font size from layout if slide and hasattr(slide, "slide_layout"): self.default_font_size = self.get_default_font_size( shape, slide.slide_layout ) # Get position information # Use absolute positions if provided (for shapes in groups), otherwise use shape's position left_emu = ( absolute_left if absolute_left is not None else (shape.left if hasattr(shape, "left") else 0) ) top_emu = ( absolute_top if absolute_top is not None else (shape.top if hasattr(shape, "top") else 0) ) self.left: float = round(self.emu_to_inches(left_emu), 2) # type: ignore self.top: float = round(self.emu_to_inches(top_emu), 2) # type: ignore self.width: float = round( self.emu_to_inches(shape.width if hasattr(shape, "width") else 0), 2, # type: ignore ) self.height: float = round( self.emu_to_inches(shape.height if hasattr(shape, "height") else 0), 2, # type: ignore ) # Store EMU positions for overflow calculations self.left_emu = left_emu self.top_emu = top_emu self.width_emu = shape.width if hasattr(shape, "width") else 0 self.height_emu = shape.height if hasattr(shape, "height") else 0 # Calculate overflow status self.frame_overflow_bottom: Optional[float] = None self.slide_overflow_right: Optional[float] = None self.slide_overflow_bottom: Optional[float] = None self.overlapping_shapes: Dict[ str, float ] = {} # Dict of shape_id -> overlap area in sq inches self.warnings: List[str] = [] self._estimate_frame_overflow() self._calculate_slide_overflow() self._detect_bullet_issues() @property def paragraphs(self) -> List[ParagraphData]: if not self.shape or not hasattr(self.shape, "text_frame"): return [] paragraphs = [] for paragraph in self.shape.text_frame.paragraphs: # type: ignore if paragraph.text.strip(): paragraphs.append(ParagraphData(paragraph)) return paragraphs def _get_default_font_size(self) -> int: try: if not ( hasattr(self.shape, "part") and hasattr(self.shape.part, "slide_layout") ): return 14 slide_master = self.shape.part.slide_layout.slide_master # type: ignore if not hasattr(slide_master, "element"): return 14 # Determine theme style based on placeholder type style_name = "bodyStyle" # Default if self.placeholder_type and "TITLE" in self.placeholder_type: style_name = "titleStyle" # Find font size in theme styles for child in slide_master.element.iter(): tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag if tag == style_name: for elem in child.iter(): if "sz" in elem.attrib: return int(elem.attrib["sz"]) // 100 except Exception: pass return 14 # Conservative default for body text def _get_usable_dimensions(self, text_frame) -> Tuple[int, int]: # Default PowerPoint margins in inches margins = {"top": 0.05, "bottom": 0.05, "left": 0.1, "right": 0.1} # Override with actual margins if set if hasattr(text_frame, "margin_top") and text_frame.margin_top: margins["top"] = self.emu_to_inches(text_frame.margin_top) if hasattr(text_frame, "margin_bottom") and text_frame.margin_bottom: margins["bottom"] = self.emu_to_inches(text_frame.margin_bottom) if hasattr(text_frame, "margin_left") and text_frame.margin_left: margins["left"] = self.emu_to_inches(text_frame.margin_left) if hasattr(text_frame, "margin_right") and text_frame.margin_right: margins["right"] = self.emu_to_inches(text_frame.margin_right) # Calculate usable area usable_width = self.width - margins["left"] - margins["right"] usable_height = self.height - margins["top"] - margins["bottom"] # Convert to pixels return ( self.inches_to_pixels(usable_width), self.inches_to_pixels(usable_height), ) def _wrap_text_line(self, line: str, max_width_px: int, draw, font) -> List[str]: if not line: return [""] # Use textlength for efficient width calculation if draw.textlength(line, font=font) <= max_width_px: return [line] # Need to wrap - split into words wrapped = [] words = line.split(" ") current_line = "" for word in words: test_line = current_line + (" " if current_line else "") + word if draw.textlength(test_line, font=font) <= max_width_px: current_line = test_line else: if current_line: wrapped.append(current_line) current_line = word if current_line: wrapped.append(current_line) return wrapped def _estimate_frame_overflow(self) -> None: if not self.shape or not hasattr(self.shape, "text_frame"): return text_frame = self.shape.text_frame # type: ignore if not text_frame or not text_frame.paragraphs: return # Get usable dimensions after accounting for margins usable_width_px, usable_height_px = self._get_usable_dimensions(text_frame) if usable_width_px <= 0 or usable_height_px <= 0: return # Set up PIL for text measurement dummy_img = Image.new("RGB", (1, 1)) draw = ImageDraw.Draw(dummy_img) # Get default font size from placeholder or use conservative estimate default_font_size = self._get_default_font_size() # Calculate total height of all paragraphs total_height_px = 0 for para_idx, paragraph in enumerate(text_frame.paragraphs): if not paragraph.text.strip(): continue para_data = ParagraphData(paragraph) # Load font for this paragraph font_name = para_data.font_name or "Arial" font_size = int(para_data.font_size or default_font_size) font = None font_path = self.get_font_path(font_name) if font_path: try: font = ImageFont.truetype(font_path, size=font_size) except Exception: font = ImageFont.load_default() else: font = ImageFont.load_default() # Wrap all lines in this paragraph all_wrapped_lines = [] for line in paragraph.text.split("\n"): wrapped = self._wrap_text_line(line, usable_width_px, draw, font) all_wrapped_lines.extend(wrapped) if all_wrapped_lines: # Calculate line height if para_data.line_spacing: # Custom line spacing explicitly set line_height_px = para_data.line_spacing * 96 / 72 else: # PowerPoint default single spacing (1.0x font size) line_height_px = font_size * 96 / 72 # Add space_before (except first paragraph) if para_idx > 0 and para_data.space_before: total_height_px += para_data.space_before * 96 / 72 # Add paragraph text height total_height_px += len(all_wrapped_lines) * line_height_px # Add space_after if para_data.space_after: total_height_px += para_data.space_after * 96 / 72 # Check for overflow (ignore negligible overflows <= 0.05") if total_height_px > usable_height_px: overflow_px = total_height_px - usable_height_px overflow_inches = round(overflow_px / 96.0, 2) if overflow_inches > 0.05: # Only report significant overflows self.frame_overflow_bottom = overflow_inches def _calculate_slide_overflow(self) -> None: if self.slide_width_emu is None or self.slide_height_emu is None: return # Check right overflow (ignore negligible overflows <= 0.01") right_edge_emu = self.left_emu + self.width_emu if right_edge_emu > self.slide_width_emu: overflow_emu = right_edge_emu - self.slide_width_emu overflow_inches = round(self.emu_to_inches(overflow_emu), 2) if overflow_inches > 0.01: # Only report significant overflows self.slide_overflow_right = overflow_inches # Check bottom overflow (ignore negligible overflows <= 0.01") bottom_edge_emu = self.top_emu + self.height_emu if bottom_edge_emu > self.slide_height_emu: overflow_emu = bottom_edge_emu - self.slide_height_emu overflow_inches = round(self.emu_to_inches(overflow_emu), 2) if overflow_inches > 0.01: # Only report significant overflows self.slide_overflow_bottom = overflow_inches def _detect_bullet_issues(self) -> None: if not self.shape or not hasattr(self.shape, "text_frame"): return text_frame = self.shape.text_frame # type: ignore if not text_frame or not text_frame.paragraphs: return # Common bullet symbols that indicate manual bullets bullet_symbols = ["•", "●", "○"] for paragraph in text_frame.paragraphs: text = paragraph.text.strip() # Check for manual bullet symbols if text and any(text.startswith(symbol + " ") for symbol in bullet_symbols): self.warnings.append( "manual_bullet_symbol: use proper bullet formatting" ) break @property def has_any_issues(self) -> bool: return ( self.frame_overflow_bottom is not None or self.slide_overflow_right is not None or self.slide_overflow_bottom is not None or len(self.overlapping_shapes) > 0 or len(self.warnings) > 0 ) def to_dict(self) -> ShapeDict: result: ShapeDict = { "left": self.left, "top": self.top, "width": self.width, "height": self.height, } # Add optional fields if present if self.placeholder_type: result["placeholder_type"] = self.placeholder_type if self.default_font_size: result["default_font_size"] = self.default_font_size # Add overflow information only if there is overflow overflow_data = {} # Add frame overflow if present if self.frame_overflow_bottom is not None: overflow_data["frame"] = {"overflow_bottom": self.frame_overflow_bottom} # Add slide overflow if present slide_overflow = {} if self.slide_overflow_right is not None: slide_overflow["overflow_right"] = self.slide_overflow_right if self.slide_overflow_bottom is not None: slide_overflow["overflow_bottom"] = self.slide_overflow_bottom if slide_overflow: overflow_data["slide"] = slide_overflow # Only add overflow field if there is overflow if overflow_data: result["overflow"] = overflow_data # Add overlap field if there are overlapping shapes if self.overlapping_shapes: result["overlap"] = {"overlapping_shapes": self.overlapping_shapes} # Add warnings field if there are warnings if self.warnings: result["warnings"] = self.warnings # Add paragraphs after placeholder_type result["paragraphs"] = [para.to_dict() for para in self.paragraphs] return result def is_valid_shape(shape: BaseShape) -> bool: # Must have a text frame with content if not hasattr(shape, "text_frame") or not shape.text_frame: # type: ignore return False text = shape.text_frame.text.strip() # type: ignore if not text: return False # Skip slide numbers and numeric footers if hasattr(shape, "is_placeholder") and shape.is_placeholder: # type: ignore if shape.placeholder_format and shape.placeholder_format.type: # type: ignore placeholder_type = ( str(shape.placeholder_format.type).split(".")[-1].split(" ")[0] # type: ignore ) if placeholder_type == "SLIDE_NUMBER": return False if placeholder_type == "FOOTER" and text.isdigit(): return False return True def collect_shapes_with_absolute_positions( shape: BaseShape, parent_left: int = 0, parent_top: int = 0 ) -> List[ShapeWithPosition]: if hasattr(shape, "shapes"): # GroupShape result = [] # Get this group's position group_left = shape.left if hasattr(shape, "left") else 0 group_top = shape.top if hasattr(shape, "top") else 0 # Calculate absolute position for this group abs_group_left = parent_left + group_left abs_group_top = parent_top + group_top # Process children with accumulated offsets for child in shape.shapes: # type: ignore result.extend( collect_shapes_with_absolute_positions( child, abs_group_left, abs_group_top ) ) return result # Regular shape - check if it has valid text if is_valid_shape(shape): # Calculate absolute position shape_left = shape.left if hasattr(shape, "left") else 0 shape_top = shape.top if hasattr(shape, "top") else 0 return [ ShapeWithPosition( shape=shape, absolute_left=parent_left + shape_left, absolute_top=parent_top + shape_top, ) ] return [] def sort_shapes_by_position(shapes: List[ShapeData]) -> List[ShapeData]: if not shapes: return shapes # Sort by top position first shapes = sorted(shapes, key=lambda s: (s.top, s.left)) # Group shapes by row (within 0.5 inches vertically) result = [] row = [shapes[0]] row_top = shapes[0].top for shape in shapes[1:]: if abs(shape.top - row_top) <= 0.5: row.append(shape) else: # Sort current row by left position and add to result result.extend(sorted(row, key=lambda s: s.left)) row = [shape] row_top = shape.top # Don't forget the last row result.extend(sorted(row, key=lambda s: s.left)) return result def calculate_overlap( rect1: Tuple[float, float, float, float], rect2: Tuple[float, float, float, float], tolerance: float = 0.05, ) -> Tuple[bool, float]: left1, top1, w1, h1 = rect1 left2, top2, w2, h2 = rect2 # Calculate overlap dimensions overlap_width = min(left1 + w1, left2 + w2) - max(left1, left2) overlap_height = min(top1 + h1, top2 + h2) - max(top1, top2) # Check if there's meaningful overlap (more than tolerance) if overlap_width > tolerance and overlap_height > tolerance: # Calculate overlap area in square inches overlap_area = overlap_width * overlap_height return True, round(overlap_area, 2) return False, 0 def detect_overlaps(shapes: List[ShapeData]) -> None: n = len(shapes) # Compare each pair of shapes for i in range(n): for j in range(i + 1, n): shape1 = shapes[i] shape2 = shapes[j] # Ensure shape IDs are set assert shape1.shape_id, f"Shape at index {i} has no shape_id" assert shape2.shape_id, f"Shape at index {j} has no shape_id" rect1 = (shape1.left, shape1.top, shape1.width, shape1.height) rect2 = (shape2.left, shape2.top, shape2.width, shape2.height) overlaps, overlap_area = calculate_overlap(rect1, rect2) if overlaps: # Add shape IDs with overlap area in square inches shape1.overlapping_shapes[shape2.shape_id] = overlap_area shape2.overlapping_shapes[shape1.shape_id] = overlap_area def extract_text_inventory( pptx_path: Path, prs: Optional[Any] = None, issues_only: bool = False ) -> InventoryData: if prs is None: prs = Presentation(str(pptx_path)) inventory: InventoryData = {} for slide_idx, slide in enumerate(prs.slides): # Collect all valid shapes from this slide with absolute positions shapes_with_positions = [] for shape in slide.shapes: # type: ignore shapes_with_positions.extend(collect_shapes_with_absolute_positions(shape)) if not shapes_with_positions: continue # Convert to ShapeData with absolute positions and slide reference shape_data_list = [ ShapeData( swp.shape, swp.absolute_left, swp.absolute_top, slide, ) for swp in shapes_with_positions ] # Sort by visual position and assign stable IDs in one step sorted_shapes = sort_shapes_by_position(shape_data_list) for idx, shape_data in enumerate(sorted_shapes): shape_data.shape_id = f"shape-{idx}" # Detect overlaps using the stable shape IDs if len(sorted_shapes) > 1: detect_overlaps(sorted_shapes) # Filter for issues only if requested (after overlap detection) if issues_only: sorted_shapes = [sd for sd in sorted_shapes if sd.has_any_issues] if not sorted_shapes: continue # Create slide inventory using the stable shape IDs inventory[f"slide-{slide_idx}"] = { shape_data.shape_id: shape_data for shape_data in sorted_shapes } return inventory def get_inventory_as_dict(pptx_path: Path, issues_only: bool = False) -> InventoryDict: inventory = extract_text_inventory(pptx_path, issues_only=issues_only) # Convert ShapeData objects to dictionaries dict_inventory: InventoryDict = {} for slide_key, shapes in inventory.items(): dict_inventory[slide_key] = { shape_key: shape_data.to_dict() for shape_key, shape_data in shapes.items() } return dict_inventory def save_inventory(inventory: InventoryData, output_path: Path) -> None: # Convert ShapeData objects to dictionaries json_inventory: InventoryDict = {} for slide_key, shapes in inventory.items(): json_inventory[slide_key] = { shape_key: shape_data.to_dict() for shape_key, shape_data in shapes.items() } with open(output_path, "w", encoding="utf-8") as f: json.dump(json_inventory, f, indent=2, ensure_ascii=False) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,26 @@ #!/usr/bin/env python3 +""" +Extract structured text content from PowerPoint presentations. + +This module provides functionality to: +- Extract all text content from PowerPoint shapes +- Preserve paragraph formatting (alignment, bullets, fonts, spacing) +- Handle nested GroupShapes recursively with correct absolute positions +- Sort shapes by visual position on slides +- Filter out slide numbers and non-content placeholders +- Export to JSON with clean, structured data + +Classes: + ParagraphData: Represents a text paragraph with formatting + ShapeData: Represents a shape with position and text content + +Main Functions: + extract_text_inventory: Extract all text from a presentation + save_inventory: Save extracted data to JSON + +Usage: + python inventory.py input.pptx output.json +""" import argparse import json @@ -26,6 +48,7 @@ def main(): + """Main entry point for command-line usage.""" parser = argparse.ArgumentParser( description="Extract text inventory from PowerPoint with proper GroupShape support.", formatter_class=argparse.RawDescriptionHelpFormatter, @@ -104,6 +127,7 @@ @dataclass class ShapeWithPosition: + """A shape with its absolute position on the slide.""" shape: BaseShape absolute_left: int # in EMUs @@ -111,8 +135,14 @@ class ParagraphData: + """Data structure for paragraph properties extracted from a PowerPoint paragraph.""" def __init__(self, paragraph: Any): + """Initialize from a PowerPoint paragraph object. + + Args: + paragraph: The PowerPoint paragraph object + """ self.text: str = paragraph.text.strip() self.bullet: bool = False self.level: Optional[int] = None @@ -199,6 +229,7 @@ self.line_spacing = round(paragraph.line_spacing * font_size, 2) def to_dict(self) -> ParagraphDict: + """Convert to dictionary for JSON serialization, excluding None values.""" result: ParagraphDict = {"text": self.text} # Add optional fields only if they have values @@ -233,17 +264,28 @@ class ShapeData: + """Data structure for shape properties extracted from a PowerPoint shape.""" @staticmethod def emu_to_inches(emu: int) -> float: + """Convert EMUs (English Metric Units) to inches.""" return emu / 914400.0 @staticmethod def inches_to_pixels(inches: float, dpi: int = 96) -> int: + """Convert inches to pixels at given DPI.""" return int(inches * dpi) @staticmethod def get_font_path(font_name: str) -> Optional[str]: + """Get the font file path for a given font name. + + Args: + font_name: Name of the font (e.g., 'Arial', 'Calibri') + + Returns: + Path to the font file, or None if not found + """ system = platform.system() # Common font file variations to try @@ -302,6 +344,14 @@ @staticmethod def get_slide_dimensions(slide: Any) -> tuple[Optional[int], Optional[int]]: + """Get slide dimensions from slide object. + + Args: + slide: Slide object + + Returns: + Tuple of (width_emu, height_emu) or (None, None) if not found + """ try: prs = slide.part.package.presentation_part.presentation return prs.slide_width, prs.slide_height @@ -310,6 +360,15 @@ @staticmethod def get_default_font_size(shape: BaseShape, slide_layout: Any) -> Optional[float]: + """Extract default font size from slide layout for a placeholder shape. + + Args: + shape: Placeholder shape + slide_layout: Slide layout containing the placeholder definition + + Returns: + Default font size in points, or None if not found + """ try: if not hasattr(shape, "placeholder_format"): return None @@ -333,6 +392,14 @@ absolute_top: Optional[int] = None, slide: Optional[Any] = None, ): + """Initialize from a PowerPoint shape object. + + Args: + shape: The PowerPoint shape object (should be pre-validated) + absolute_left: Absolute left position in EMUs (for shapes in groups) + absolute_top: Absolute top position in EMUs (for shapes in groups) + slide: Optional slide object to get dimensions and layout information + """ self.shape = shape # Store reference to original shape self.shape_id: str = "" # Will be set after sorting @@ -400,6 +467,7 @@ @property def paragraphs(self) -> List[ParagraphData]: + """Calculate paragraphs from the shape's text frame.""" if not self.shape or not hasattr(self.shape, "text_frame"): return [] @@ -410,6 +478,7 @@ return paragraphs def _get_default_font_size(self) -> int: + """Get default font size from theme text styles or use conservative default.""" try: if not ( hasattr(self.shape, "part") and hasattr(self.shape.part, "slide_layout") @@ -438,6 +507,7 @@ return 14 # Conservative default for body text def _get_usable_dimensions(self, text_frame) -> Tuple[int, int]: + """Get usable width and height in pixels after accounting for margins.""" # Default PowerPoint margins in inches margins = {"top": 0.05, "bottom": 0.05, "left": 0.1, "right": 0.1} @@ -462,6 +532,7 @@ ) def _wrap_text_line(self, line: str, max_width_px: int, draw, font) -> List[str]: + """Wrap a single line of text to fit within max_width_px.""" if not line: return [""] @@ -489,6 +560,7 @@ return wrapped def _estimate_frame_overflow(self) -> None: + """Estimate if text overflows the shape bounds using PIL text measurement.""" if not self.shape or not hasattr(self.shape, "text_frame"): return @@ -565,6 +637,7 @@ self.frame_overflow_bottom = overflow_inches def _calculate_slide_overflow(self) -> None: + """Calculate if shape overflows the slide boundaries.""" if self.slide_width_emu is None or self.slide_height_emu is None: return @@ -585,6 +658,7 @@ self.slide_overflow_bottom = overflow_inches def _detect_bullet_issues(self) -> None: + """Detect bullet point formatting issues in paragraphs.""" if not self.shape or not hasattr(self.shape, "text_frame"): return @@ -606,6 +680,7 @@ @property def has_any_issues(self) -> bool: + """Check if shape has any issues (overflow, overlap, or warnings).""" return ( self.frame_overflow_bottom is not None or self.slide_overflow_right is not None @@ -615,6 +690,7 @@ ) def to_dict(self) -> ShapeDict: + """Convert to dictionary for JSON serialization.""" result: ShapeDict = { "left": self.left, "top": self.top, @@ -664,6 +740,7 @@ def is_valid_shape(shape: BaseShape) -> bool: + """Check if a shape contains meaningful text content.""" # Must have a text frame with content if not hasattr(shape, "text_frame") or not shape.text_frame: # type: ignore return False @@ -689,6 +766,20 @@ def collect_shapes_with_absolute_positions( shape: BaseShape, parent_left: int = 0, parent_top: int = 0 ) -> List[ShapeWithPosition]: + """Recursively collect all shapes with valid text, calculating absolute positions. + + For shapes within groups, their positions are relative to the group. + This function calculates the absolute position on the slide by accumulating + parent group offsets. + + Args: + shape: The shape to process + parent_left: Accumulated left offset from parent groups (in EMUs) + parent_top: Accumulated top offset from parent groups (in EMUs) + + Returns: + List of ShapeWithPosition objects with absolute positions + """ if hasattr(shape, "shapes"): # GroupShape result = [] # Get this group's position @@ -726,6 +817,10 @@ def sort_shapes_by_position(shapes: List[ShapeData]) -> List[ShapeData]: + """Sort shapes by visual position (top-to-bottom, left-to-right). + + Shapes within 0.5 inches vertically are considered on the same row. + """ if not shapes: return shapes @@ -756,6 +851,18 @@ rect2: Tuple[float, float, float, float], tolerance: float = 0.05, ) -> Tuple[bool, float]: + """Calculate if and how much two rectangles overlap. + + Args: + rect1: (left, top, width, height) of first rectangle in inches + rect2: (left, top, width, height) of second rectangle in inches + tolerance: Minimum overlap in inches to consider as overlapping (default: 0.05") + + Returns: + Tuple of (overlaps, overlap_area) where: + - overlaps: True if rectangles overlap by more than tolerance + - overlap_area: Area of overlap in square inches + """ left1, top1, w1, h1 = rect1 left2, top2, w2, h2 = rect2 @@ -773,6 +880,14 @@ def detect_overlaps(shapes: List[ShapeData]) -> None: + """Detect overlapping shapes and update their overlapping_shapes dictionaries. + + This function requires each ShapeData to have its shape_id already set. + It modifies the shapes in-place, adding shape IDs with overlap areas in square inches. + + Args: + shapes: List of ShapeData objects with shape_id attributes set + """ n = len(shapes) # Compare each pair of shapes @@ -799,6 +914,18 @@ def extract_text_inventory( pptx_path: Path, prs: Optional[Any] = None, issues_only: bool = False ) -> InventoryData: + """Extract text content from all slides in a PowerPoint presentation. + + Args: + pptx_path: Path to the PowerPoint file + prs: Optional Presentation object to use. If not provided, will load from pptx_path. + issues_only: If True, only include shapes that have overflow or overlap issues + + Returns a nested dictionary: {slide-N: {shape-N: ShapeData}} + Shapes are sorted by visual position (top-to-bottom, left-to-right). + The ShapeData objects contain the full shape information and can be + converted to dictionaries for JSON serialization using to_dict(). + """ if prs is None: prs = Presentation(str(pptx_path)) inventory: InventoryData = {} @@ -848,6 +975,19 @@ def get_inventory_as_dict(pptx_path: Path, issues_only: bool = False) -> InventoryDict: + """Extract text inventory and return as JSON-serializable dictionaries. + + This is a convenience wrapper around extract_text_inventory that returns + dictionaries instead of ShapeData objects, useful for testing and direct + JSON serialization. + + Args: + pptx_path: Path to the PowerPoint file + issues_only: If True, only include shapes that have overflow or overlap issues + + Returns: + Nested dictionary with all data serialized for JSON + """ inventory = extract_text_inventory(pptx_path, issues_only=issues_only) # Convert ShapeData objects to dictionaries @@ -861,6 +1001,10 @@ def save_inventory(inventory: InventoryData, output_path: Path) -> None: + """Save inventory to JSON file with proper formatting. + + Converts ShapeData objects to dictionaries for JSON serialization. + """ # Convert ShapeData objects to dictionaries json_inventory: InventoryDict = {} for slide_key, shapes in inventory.items(): @@ -873,4 +1017,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/inventory.py
Write reusable docstrings
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced from core.easing import interpolate def create_wiggle_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 30, wiggle_type: str = 'jello', # 'jello', 'wave', 'bounce', 'sway' intensity: float = 1.0, cycles: float = 2.0, center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] # Default object data if object_data is None: if object_type == 'emoji': object_data = {'emoji': '🎈', 'size': 100} for i in range(num_frames): t = i / (num_frames - 1) if num_frames > 1 else 0 frame = create_blank_frame(frame_width, frame_height, bg_color) # Calculate wiggle transformations offset_x = 0 offset_y = 0 rotation = 0 scale_x = 1.0 scale_y = 1.0 if wiggle_type == 'jello': # Jello wobble - multiple frequencies freq1 = cycles * 2 * math.pi freq2 = cycles * 3 * math.pi freq3 = cycles * 5 * math.pi decay = 1.0 - t if cycles < 1.5 else 1.0 # Decay for single wiggles offset_x = ( math.sin(freq1 * t) * 15 + math.sin(freq2 * t) * 8 + math.sin(freq3 * t) * 3 ) * intensity * decay rotation = ( math.sin(freq1 * t) * 10 + math.cos(freq2 * t) * 5 ) * intensity * decay # Squash and stretch scale_y = 1.0 + math.sin(freq1 * t) * 0.1 * intensity * decay scale_x = 1.0 / scale_y # Preserve volume elif wiggle_type == 'wave': # Wave motion freq = cycles * 2 * math.pi offset_y = math.sin(freq * t) * 20 * intensity rotation = math.sin(freq * t + math.pi / 4) * 8 * intensity elif wiggle_type == 'bounce': # Bouncy wiggle freq = cycles * 2 * math.pi bounce = abs(math.sin(freq * t)) scale_y = 1.0 + bounce * 0.2 * intensity scale_x = 1.0 - bounce * 0.1 * intensity offset_y = -bounce * 10 * intensity elif wiggle_type == 'sway': # Gentle sway back and forth freq = cycles * 2 * math.pi offset_x = math.sin(freq * t) * 25 * intensity rotation = math.sin(freq * t) * 12 * intensity # Subtle scale change scale = 1.0 + math.sin(freq * t) * 0.05 * intensity scale_x = scale scale_y = scale elif wiggle_type == 'tail_wag': # Like a wagging tail - base stays, tip moves freq = cycles * 2 * math.pi wag = math.sin(freq * t) * intensity # Rotation focused at one end rotation = wag * 20 offset_x = wag * 15 # Apply transformations if object_type == 'emoji': size = object_data['size'] size_x = int(size * scale_x) size_y = int(size * scale_y) # For non-uniform scaling or rotation, we need to use PIL transforms if abs(scale_x - scale_y) > 0.01 or abs(rotation) > 0.1: # Create emoji on transparent canvas canvas_size = int(size * 2) emoji_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) # Draw emoji draw_emoji_enhanced( emoji_canvas, emoji=object_data['emoji'], position=(canvas_size // 2 - size // 2, canvas_size // 2 - size // 2), size=size, shadow=False ) # Scale if abs(scale_x - scale_y) > 0.01: new_size = (int(canvas_size * scale_x), int(canvas_size * scale_y)) emoji_canvas = emoji_canvas.resize(new_size, Image.LANCZOS) canvas_size_x, canvas_size_y = new_size else: canvas_size_x = canvas_size_y = canvas_size # Rotate if abs(rotation) > 0.1: emoji_canvas = emoji_canvas.rotate( rotation, resample=Image.BICUBIC, expand=False ) # Position with offset paste_x = int(center_pos[0] - canvas_size_x // 2 + offset_x) paste_y = int(center_pos[1] - canvas_size_y // 2 + offset_y) frame_rgba = frame.convert('RGBA') frame_rgba.paste(emoji_canvas, (paste_x, paste_y), emoji_canvas) frame = frame_rgba.convert('RGB') else: # Simple case - just offset pos_x = int(center_pos[0] - size // 2 + offset_x) pos_y = int(center_pos[1] - size // 2 + offset_y) draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(pos_x, pos_y), size=size, shadow=object_data.get('shadow', True) ) elif object_type == 'text': from core.typography import draw_text_with_outline # Create text on canvas for transformation canvas_size = max(frame_width, frame_height) text_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) # Convert to RGB for drawing text_canvas_rgb = text_canvas.convert('RGB') text_canvas_rgb.paste(bg_color, (0, 0, canvas_size, canvas_size)) draw_text_with_outline( text_canvas_rgb, text=object_data.get('text', 'WIGGLE'), position=(canvas_size // 2, canvas_size // 2), font_size=object_data.get('font_size', 50), text_color=object_data.get('text_color', (0, 0, 0)), outline_color=object_data.get('outline_color', (255, 255, 255)), outline_width=3, centered=True ) # Make transparent text_canvas = text_canvas_rgb.convert('RGBA') data = text_canvas.getdata() new_data = [] for item in data: if item[:3] == bg_color: new_data.append((255, 255, 255, 0)) else: new_data.append(item) text_canvas.putdata(new_data) # Apply rotation if abs(rotation) > 0.1: text_canvas = text_canvas.rotate(rotation, center=(canvas_size // 2, canvas_size // 2), resample=Image.BICUBIC) # Crop to frame with offset left = (canvas_size - frame_width) // 2 - int(offset_x) top = (canvas_size - frame_height) // 2 - int(offset_y) text_cropped = text_canvas.crop((left, top, left + frame_width, top + frame_height)) frame_rgba = frame.convert('RGBA') frame = Image.alpha_composite(frame_rgba, text_cropped) frame = frame.convert('RGB') frames.append(frame) return frames def create_excited_wiggle( emoji: str = '🎉', num_frames: int = 20, frame_size: int = 128 ) -> list[Image.Image]: return create_wiggle_animation( object_type='emoji', object_data={'emoji': emoji, 'size': 80, 'shadow': False}, num_frames=num_frames, wiggle_type='jello', intensity=0.8, cycles=2, center_pos=(frame_size // 2, frame_size // 2), frame_width=frame_size, frame_height=frame_size, bg_color=(255, 255, 255) ) # Example usage if __name__ == '__main__': print("Creating wiggle animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Jello wiggle frames = create_wiggle_animation( object_type='emoji', object_data={'emoji': '🎈', 'size': 100}, num_frames=40, wiggle_type='jello', intensity=1.0, cycles=2 ) builder.add_frames(frames) builder.save('wiggle_jello.gif', num_colors=128) # Example 2: Wave builder.clear() frames = create_wiggle_animation( object_type='emoji', object_data={'emoji': '🌊', 'size': 100}, num_frames=30, wiggle_type='wave', intensity=1.2, cycles=3 ) builder.add_frames(frames) builder.save('wiggle_wave.gif', num_colors=128) # Example 3: Excited wiggle (emoji size) builder = GIFBuilder(width=128, height=128, fps=15) frames = create_excited_wiggle(emoji='🎉', num_frames=20) builder.add_frames(frames) builder.save('wiggle_excited.gif', num_colors=48, optimize_for_emoji=True) print("Created wiggle animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Wiggle Animation - Smooth, organic wobbling and jiggling motions. + +Creates playful, elastic movements that are smoother than shake. +""" import sys from pathlib import Path @@ -24,6 +29,24 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create wiggle/wobble animation. + + Args: + object_type: 'emoji', 'text' + object_data: Object configuration + num_frames: Number of frames + wiggle_type: Type of wiggle motion + intensity: Wiggle intensity multiplier + cycles: Number of wiggle cycles + center_pos: Center position + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -212,6 +235,17 @@ num_frames: int = 20, frame_size: int = 128 ) -> list[Image.Image]: + """ + Create excited wiggle for emoji GIFs. + + Args: + emoji: Emoji to wiggle + num_frames: Number of frames + frame_size: Frame size (square) + + Returns: + List of frames + """ return create_wiggle_animation( object_type='emoji', object_data={'emoji': emoji, 'size': 80, 'shadow': False}, @@ -263,4 +297,4 @@ builder.add_frames(frames) builder.save('wiggle_excited.gif', num_colors=48, optimize_for_emoji=True) - print("Created wiggle animations!")+ print("Created wiggle animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/wiggle.py
Generate docstrings for each module
#!/usr/bin/env python3 import sys from pathlib import Path # Add parent directory to path sys.path.append(str(Path(__file__).parent.parent)) from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_circle, draw_emoji from core.easing import ease_out_bounce, interpolate def create_bounce_animation( object_type: str = 'circle', object_data: dict = None, num_frames: int = 30, bounce_height: int = 150, ground_y: int = 350, start_x: int = 240, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list: frames = [] # Default object data if object_data is None: if object_type == 'circle': object_data = {'radius': 30, 'color': (255, 100, 100)} elif object_type == 'emoji': object_data = {'emoji': '⚽', 'size': 60} for i in range(num_frames): # Create blank frame frame = create_blank_frame(frame_width, frame_height, bg_color) # Calculate progress (0.0 to 1.0) t = i / (num_frames - 1) if num_frames > 1 else 0 # Calculate Y position using bounce easing y = ground_y - int(ease_out_bounce(t) * bounce_height) # Draw object if object_type == 'circle': draw_circle( frame, center=(start_x, y), radius=object_data['radius'], fill_color=object_data['color'] ) elif object_type == 'emoji': draw_emoji( frame, emoji=object_data['emoji'], position=(start_x - object_data['size'] // 2, y - object_data['size'] // 2), size=object_data['size'] ) frames.append(frame) return frames # Example usage if __name__ == '__main__': print("Creating bouncing ball GIF...") # Create GIF builder builder = GIFBuilder(width=480, height=480, fps=20) # Generate bounce animation frames = create_bounce_animation( object_type='circle', object_data={'radius': 40, 'color': (255, 100, 100)}, num_frames=40, bounce_height=200 ) # Add frames to builder builder.add_frames(frames) # Save GIF builder.save('bounce_test.gif', num_colors=64)
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Bounce Animation Template - Creates bouncing motion for objects. + +Use this to make objects bounce up and down or horizontally with realistic physics. +""" import sys from pathlib import Path @@ -22,6 +27,23 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list: + """ + Create frames for a bouncing animation. + + Args: + object_type: 'circle', 'emoji', or 'custom' + object_data: Data for the object (e.g., {'radius': 30, 'color': (255, 0, 0)}) + num_frames: Number of frames in the animation + bounce_height: Maximum height of bounce + ground_y: Y position of ground + start_x: X position (or starting X if moving horizontally) + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/bounce.py
Add docstrings to incomplete code
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_circle, draw_emoji_enhanced from core.easing import interpolate, calculate_arc_motion def create_move_animation( object_type: str = 'emoji', object_data: dict | None = None, start_pos: tuple[int, int] = (50, 240), end_pos: tuple[int, int] = (430, 240), num_frames: int = 30, motion_type: str = 'linear', # 'linear', 'arc', 'bezier', 'circle', 'wave' easing: str = 'ease_out', motion_params: dict | None = None, frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list: frames = [] # Default object data if object_data is None: if object_type == 'circle': object_data = {'radius': 30, 'color': (100, 150, 255)} elif object_type == 'emoji': object_data = {'emoji': '🚀', 'size': 60} # Default motion params if motion_params is None: motion_params = {} for i in range(num_frames): frame = create_blank_frame(frame_width, frame_height, bg_color) t = i / (num_frames - 1) if num_frames > 1 else 0 # Calculate position based on motion type if motion_type == 'linear': # Straight line with easing x = interpolate(start_pos[0], end_pos[0], t, easing) y = interpolate(start_pos[1], end_pos[1], t, easing) elif motion_type == 'arc': # Parabolic arc arc_height = motion_params.get('arc_height', 100) x, y = calculate_arc_motion(start_pos, end_pos, arc_height, t) elif motion_type == 'circle': # Circular motion around a center center = motion_params.get('center', (frame_width // 2, frame_height // 2)) radius = motion_params.get('radius', 150) start_angle = motion_params.get('start_angle', 0) angle_range = motion_params.get('angle_range', 360) # Full circle angle = start_angle + (angle_range * t) angle_rad = math.radians(angle) x = center[0] + radius * math.cos(angle_rad) y = center[1] + radius * math.sin(angle_rad) elif motion_type == 'wave': # Move in straight line but add wave motion wave_amplitude = motion_params.get('wave_amplitude', 50) wave_frequency = motion_params.get('wave_frequency', 2) # Base linear motion base_x = interpolate(start_pos[0], end_pos[0], t, easing) base_y = interpolate(start_pos[1], end_pos[1], t, easing) # Add wave offset perpendicular to motion direction dx = end_pos[0] - start_pos[0] dy = end_pos[1] - start_pos[1] length = math.sqrt(dx * dx + dy * dy) if length > 0: # Perpendicular direction perp_x = -dy / length perp_y = dx / length # Wave offset wave_offset = math.sin(t * wave_frequency * 2 * math.pi) * wave_amplitude x = base_x + perp_x * wave_offset y = base_y + perp_y * wave_offset else: x, y = base_x, base_y elif motion_type == 'bezier': # Quadratic bezier curve control_point = motion_params.get('control_point', ( (start_pos[0] + end_pos[0]) // 2, (start_pos[1] + end_pos[1]) // 2 - 100 )) # Quadratic Bezier formula: B(t) = (1-t)²P0 + 2(1-t)tP1 + t²P2 x = (1 - t) ** 2 * start_pos[0] + 2 * (1 - t) * t * control_point[0] + t ** 2 * end_pos[0] y = (1 - t) ** 2 * start_pos[1] + 2 * (1 - t) * t * control_point[1] + t ** 2 * end_pos[1] else: # Default to linear x = interpolate(start_pos[0], end_pos[0], t, easing) y = interpolate(start_pos[1], end_pos[1], t, easing) # Draw object at calculated position x, y = int(x), int(y) if object_type == 'circle': draw_circle( frame, center=(x, y), radius=object_data['radius'], fill_color=object_data['color'] ) elif object_type == 'emoji': draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(x - object_data['size'] // 2, y - object_data['size'] // 2), size=object_data['size'], shadow=object_data.get('shadow', True) ) frames.append(frame) return frames def create_path_from_points(points: list[tuple[int, int]], num_frames: int = 60, easing: str = 'ease_in_out') -> list[tuple[int, int]]: if len(points) < 2: return points * num_frames path = [] frames_per_segment = num_frames // (len(points) - 1) for i in range(len(points) - 1): start = points[i] end = points[i + 1] # Last segment gets remaining frames if i == len(points) - 2: segment_frames = num_frames - len(path) else: segment_frames = frames_per_segment for j in range(segment_frames): t = j / segment_frames if segment_frames > 0 else 0 x = interpolate(start[0], end[0], t, easing) y = interpolate(start[1], end[1], t, easing) path.append((int(x), int(y))) return path def apply_trail_effect(frames: list, trail_length: int = 5, fade_alpha: float = 0.3) -> list: from PIL import Image, ImageChops import numpy as np trailed_frames = [] for i, frame in enumerate(frames): # Start with current frame result = frame.copy() # Blend previous frames for j in range(1, min(trail_length + 1, i + 1)): prev_frame = frames[i - j] # Calculate fade alpha = fade_alpha ** j # Blend result_array = np.array(result, dtype=np.float32) prev_array = np.array(prev_frame, dtype=np.float32) blended = result_array * (1 - alpha) + prev_array * alpha result = Image.fromarray(blended.astype(np.uint8)) trailed_frames.append(result) return trailed_frames # Example usage if __name__ == '__main__': print("Creating movement examples...") # Example 1: Linear movement builder = GIFBuilder(width=480, height=480, fps=20) frames = create_move_animation( object_type='emoji', object_data={'emoji': '🚀', 'size': 60}, start_pos=(50, 240), end_pos=(430, 240), num_frames=30, motion_type='linear', easing='ease_out' ) builder.add_frames(frames) builder.save('move_linear.gif', num_colors=128) # Example 2: Arc movement builder.clear() frames = create_move_animation( object_type='emoji', object_data={'emoji': '⚽', 'size': 60}, start_pos=(50, 350), end_pos=(430, 350), num_frames=30, motion_type='arc', motion_params={'arc_height': 150}, easing='linear' ) builder.add_frames(frames) builder.save('move_arc.gif', num_colors=128) # Example 3: Circular movement builder.clear() frames = create_move_animation( object_type='emoji', object_data={'emoji': '🌍', 'size': 50}, start_pos=(0, 0), # Ignored for circle end_pos=(0, 0), # Ignored for circle num_frames=40, motion_type='circle', motion_params={ 'center': (240, 240), 'radius': 120, 'start_angle': 0, 'angle_range': 360 }, easing='linear' ) builder.add_frames(frames) builder.save('move_circle.gif', num_colors=128) print("Created movement examples!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Move Animation - Move objects along paths with various motion types. + +Provides flexible movement primitives for objects along linear, arc, or custom paths. +""" import sys from pathlib import Path @@ -24,6 +29,25 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list: + """ + Create frames showing object moving along a path. + + Args: + object_type: 'circle', 'emoji', or 'custom' + object_data: Data for the object + start_pos: Starting (x, y) position + end_pos: Ending (x, y) position + num_frames: Number of frames + motion_type: Type of motion path + easing: Easing function name + motion_params: Additional parameters for motion (e.g., {'arc_height': 100}) + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -136,6 +160,17 @@ def create_path_from_points(points: list[tuple[int, int]], num_frames: int = 60, easing: str = 'ease_in_out') -> list[tuple[int, int]]: + """ + Create a smooth path through multiple points. + + Args: + points: List of (x, y) waypoints + num_frames: Total number of frames + easing: Easing between points + + Returns: + List of (x, y) positions for each frame + """ if len(points) < 2: return points * num_frames @@ -163,6 +198,17 @@ def apply_trail_effect(frames: list, trail_length: int = 5, fade_alpha: float = 0.3) -> list: + """ + Add motion trail effect to moving object. + + Args: + frames: List of frames with moving object + trail_length: Number of previous frames to blend + fade_alpha: Opacity of trail frames + + Returns: + List of frames with trail effect + """ from PIL import Image, ImageChops import numpy as np @@ -244,4 +290,4 @@ builder.add_frames(frames) builder.save('move_circle.gif', num_colors=128) - print("Created movement examples!")+ print("Created movement examples!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/move.py
Write docstrings describing each step
#!/usr/bin/env python3 import argparse import subprocess import sys import tempfile from pathlib import Path from inventory import extract_text_inventory from PIL import Image, ImageDraw, ImageFont from pptx import Presentation # Constants THUMBNAIL_WIDTH = 300 # Fixed thumbnail width in pixels CONVERSION_DPI = 100 # DPI for PDF to image conversion MAX_COLS = 6 # Maximum number of columns DEFAULT_COLS = 5 # Default number of columns JPEG_QUALITY = 95 # JPEG compression quality # Grid layout constants GRID_PADDING = 20 # Padding between thumbnails BORDER_WIDTH = 2 # Border width around thumbnails FONT_SIZE_RATIO = 0.12 # Font size as fraction of thumbnail width LABEL_PADDING_RATIO = 0.4 # Label padding as fraction of font size def main(): parser = argparse.ArgumentParser( description="Create thumbnail grids from PowerPoint slides." ) parser.add_argument("input", help="Input PowerPoint file (.pptx)") parser.add_argument( "output_prefix", nargs="?", default="thumbnails", help="Output prefix for image files (default: thumbnails, will create prefix.jpg or prefix-N.jpg)", ) parser.add_argument( "--cols", type=int, default=DEFAULT_COLS, help=f"Number of columns (default: {DEFAULT_COLS}, max: {MAX_COLS})", ) parser.add_argument( "--outline-placeholders", action="store_true", help="Outline text placeholders with a colored border", ) args = parser.parse_args() # Validate columns cols = min(args.cols, MAX_COLS) if args.cols > MAX_COLS: print(f"Warning: Columns limited to {MAX_COLS} (requested {args.cols})") # Validate input input_path = Path(args.input) if not input_path.exists() or input_path.suffix.lower() != ".pptx": print(f"Error: Invalid PowerPoint file: {args.input}") sys.exit(1) # Construct output path (always JPG) output_path = Path(f"{args.output_prefix}.jpg") print(f"Processing: {args.input}") try: with tempfile.TemporaryDirectory() as temp_dir: # Get placeholder regions if outlining is enabled placeholder_regions = None slide_dimensions = None if args.outline_placeholders: print("Extracting placeholder regions...") placeholder_regions, slide_dimensions = get_placeholder_regions( input_path ) if placeholder_regions: print(f"Found placeholders on {len(placeholder_regions)} slides") # Convert slides to images slide_images = convert_to_images(input_path, Path(temp_dir), CONVERSION_DPI) if not slide_images: print("Error: No slides found") sys.exit(1) print(f"Found {len(slide_images)} slides") # Create grids (max cols×(cols+1) images per grid) grid_files = create_grids( slide_images, cols, THUMBNAIL_WIDTH, output_path, placeholder_regions, slide_dimensions, ) # Print saved files print(f"Created {len(grid_files)} grid(s):") for grid_file in grid_files: print(f" - {grid_file}") except Exception as e: print(f"Error: {e}") sys.exit(1) def create_hidden_slide_placeholder(size): img = Image.new("RGB", size, color="#F0F0F0") draw = ImageDraw.Draw(img) line_width = max(5, min(size) // 100) draw.line([(0, 0), size], fill="#CCCCCC", width=line_width) draw.line([(size[0], 0), (0, size[1])], fill="#CCCCCC", width=line_width) return img def get_placeholder_regions(pptx_path): prs = Presentation(str(pptx_path)) inventory = extract_text_inventory(pptx_path, prs) placeholder_regions = {} # Get actual slide dimensions in inches (EMU to inches conversion) slide_width_inches = (prs.slide_width or 9144000) / 914400.0 slide_height_inches = (prs.slide_height or 5143500) / 914400.0 for slide_key, shapes in inventory.items(): # Extract slide index from "slide-N" format slide_idx = int(slide_key.split("-")[1]) regions = [] for shape_key, shape_data in shapes.items(): # The inventory only contains shapes with text, so all shapes should be highlighted regions.append( { "left": shape_data.left, "top": shape_data.top, "width": shape_data.width, "height": shape_data.height, } ) if regions: placeholder_regions[slide_idx] = regions return placeholder_regions, (slide_width_inches, slide_height_inches) def convert_to_images(pptx_path, temp_dir, dpi): # Detect hidden slides print("Analyzing presentation...") prs = Presentation(str(pptx_path)) total_slides = len(prs.slides) # Find hidden slides (1-based indexing for display) hidden_slides = { idx + 1 for idx, slide in enumerate(prs.slides) if slide.element.get("show") == "0" } print(f"Total slides: {total_slides}") if hidden_slides: print(f"Hidden slides: {sorted(hidden_slides)}") pdf_path = temp_dir / f"{pptx_path.stem}.pdf" # Convert to PDF print("Converting to PDF...") result = subprocess.run( [ "soffice", "--headless", "--convert-to", "pdf", "--outdir", str(temp_dir), str(pptx_path), ], capture_output=True, text=True, ) if result.returncode != 0 or not pdf_path.exists(): raise RuntimeError("PDF conversion failed") # Convert PDF to images print(f"Converting to images at {dpi} DPI...") result = subprocess.run( ["pdftoppm", "-jpeg", "-r", str(dpi), str(pdf_path), str(temp_dir / "slide")], capture_output=True, text=True, ) if result.returncode != 0: raise RuntimeError("Image conversion failed") visible_images = sorted(temp_dir.glob("slide-*.jpg")) # Create full list with placeholders for hidden slides all_images = [] visible_idx = 0 # Get placeholder dimensions from first visible slide if visible_images: with Image.open(visible_images[0]) as img: placeholder_size = img.size else: placeholder_size = (1920, 1080) for slide_num in range(1, total_slides + 1): if slide_num in hidden_slides: # Create placeholder image for hidden slide placeholder_path = temp_dir / f"hidden-{slide_num:03d}.jpg" placeholder_img = create_hidden_slide_placeholder(placeholder_size) placeholder_img.save(placeholder_path, "JPEG") all_images.append(placeholder_path) else: # Use the actual visible slide image if visible_idx < len(visible_images): all_images.append(visible_images[visible_idx]) visible_idx += 1 return all_images def create_grids( image_paths, cols, width, output_path, placeholder_regions=None, slide_dimensions=None, ): # Maximum images per grid is cols × (cols + 1) for better proportions max_images_per_grid = cols * (cols + 1) grid_files = [] print( f"Creating grids with {cols} columns (max {max_images_per_grid} images per grid)" ) # Split images into chunks for chunk_idx, start_idx in enumerate( range(0, len(image_paths), max_images_per_grid) ): end_idx = min(start_idx + max_images_per_grid, len(image_paths)) chunk_images = image_paths[start_idx:end_idx] # Create grid for this chunk grid = create_grid( chunk_images, cols, width, start_idx, placeholder_regions, slide_dimensions ) # Generate output filename if len(image_paths) <= max_images_per_grid: # Single grid - use base filename without suffix grid_filename = output_path else: # Multiple grids - insert index before extension with dash stem = output_path.stem suffix = output_path.suffix grid_filename = output_path.parent / f"{stem}-{chunk_idx + 1}{suffix}" # Save grid grid_filename.parent.mkdir(parents=True, exist_ok=True) grid.save(str(grid_filename), quality=JPEG_QUALITY) grid_files.append(str(grid_filename)) return grid_files def create_grid( image_paths, cols, width, start_slide_num=0, placeholder_regions=None, slide_dimensions=None, ): font_size = int(width * FONT_SIZE_RATIO) label_padding = int(font_size * LABEL_PADDING_RATIO) # Get dimensions with Image.open(image_paths[0]) as img: aspect = img.height / img.width height = int(width * aspect) # Calculate grid size rows = (len(image_paths) + cols - 1) // cols grid_w = cols * width + (cols + 1) * GRID_PADDING grid_h = rows * (height + font_size + label_padding * 2) + (rows + 1) * GRID_PADDING # Create grid grid = Image.new("RGB", (grid_w, grid_h), "white") draw = ImageDraw.Draw(grid) # Load font with size based on thumbnail width try: # Use Pillow's default font with size font = ImageFont.load_default(size=font_size) except Exception: # Fall back to basic default font if size parameter not supported font = ImageFont.load_default() # Place thumbnails for i, img_path in enumerate(image_paths): row, col = i // cols, i % cols x = col * width + (col + 1) * GRID_PADDING y_base = ( row * (height + font_size + label_padding * 2) + (row + 1) * GRID_PADDING ) # Add label with actual slide number label = f"{start_slide_num + i}" bbox = draw.textbbox((0, 0), label, font=font) text_w = bbox[2] - bbox[0] draw.text( (x + (width - text_w) // 2, y_base + label_padding), label, fill="black", font=font, ) # Add thumbnail below label with proportional spacing y_thumbnail = y_base + label_padding + font_size + label_padding with Image.open(img_path) as img: # Get original dimensions before thumbnail orig_w, orig_h = img.size # Apply placeholder outlines if enabled if placeholder_regions and (start_slide_num + i) in placeholder_regions: # Convert to RGBA for transparency support if img.mode != "RGBA": img = img.convert("RGBA") # Get the regions for this slide regions = placeholder_regions[start_slide_num + i] # Calculate scale factors using actual slide dimensions if slide_dimensions: slide_width_inches, slide_height_inches = slide_dimensions else: # Fallback: estimate from image size at CONVERSION_DPI slide_width_inches = orig_w / CONVERSION_DPI slide_height_inches = orig_h / CONVERSION_DPI x_scale = orig_w / slide_width_inches y_scale = orig_h / slide_height_inches # Create a highlight overlay overlay = Image.new("RGBA", img.size, (255, 255, 255, 0)) overlay_draw = ImageDraw.Draw(overlay) # Highlight each placeholder region for region in regions: # Convert from inches to pixels in the original image px_left = int(region["left"] * x_scale) px_top = int(region["top"] * y_scale) px_width = int(region["width"] * x_scale) px_height = int(region["height"] * y_scale) # Draw highlight outline with red color and thick stroke # Using a bright red outline instead of fill stroke_width = max( 5, min(orig_w, orig_h) // 150 ) # Thicker proportional stroke width overlay_draw.rectangle( [(px_left, px_top), (px_left + px_width, px_top + px_height)], outline=(255, 0, 0, 255), # Bright red, fully opaque width=stroke_width, ) # Composite the overlay onto the image using alpha blending img = Image.alpha_composite(img, overlay) # Convert back to RGB for JPEG saving img = img.convert("RGB") img.thumbnail((width, height), Image.Resampling.LANCZOS) w, h = img.size tx = x + (width - w) // 2 ty = y_thumbnail + (height - h) // 2 grid.paste(img, (tx, ty)) # Add border if BORDER_WIDTH > 0: draw.rectangle( [ (tx - BORDER_WIDTH, ty - BORDER_WIDTH), (tx + w + BORDER_WIDTH - 1, ty + h + BORDER_WIDTH - 1), ], outline="gray", width=BORDER_WIDTH, ) return grid if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,44 @@ #!/usr/bin/env python3 +""" +Create thumbnail grids from PowerPoint presentation slides. + +Creates a grid layout of slide thumbnails with configurable columns (max 6). +Each grid contains up to cols×(cols+1) images. For presentations with more +slides, multiple numbered grid files are created automatically. + +The program outputs the names of all files created. + +Output: +- Single grid: {prefix}.jpg (if slides fit in one grid) +- Multiple grids: {prefix}-1.jpg, {prefix}-2.jpg, etc. + +Grid limits by column count: +- 3 cols: max 12 slides per grid (3×4) +- 4 cols: max 20 slides per grid (4×5) +- 5 cols: max 30 slides per grid (5×6) [default] +- 6 cols: max 42 slides per grid (6×7) + +Usage: + python thumbnail.py input.pptx [output_prefix] [--cols N] [--outline-placeholders] + +Examples: + python thumbnail.py presentation.pptx + # Creates: thumbnails.jpg (using default prefix) + # Outputs: + # Created 1 grid(s): + # - thumbnails.jpg + + python thumbnail.py large-deck.pptx grid --cols 4 + # Creates: grid-1.jpg, grid-2.jpg, grid-3.jpg + # Outputs: + # Created 3 grid(s): + # - grid-1.jpg + # - grid-2.jpg + # - grid-3.jpg + + python thumbnail.py template.pptx analysis --outline-placeholders + # Creates thumbnail grids with red outlines around text placeholders +""" import argparse import subprocess @@ -107,6 +147,7 @@ def create_hidden_slide_placeholder(size): + """Create placeholder image for hidden slides.""" img = Image.new("RGB", size, color="#F0F0F0") draw = ImageDraw.Draw(img) line_width = max(5, min(size) // 100) @@ -116,6 +157,13 @@ def get_placeholder_regions(pptx_path): + """Extract ALL text regions from the presentation. + + Returns a tuple of (placeholder_regions, slide_dimensions). + text_regions is a dict mapping slide indices to lists of text regions. + Each region is a dict with 'left', 'top', 'width', 'height' in inches. + slide_dimensions is a tuple of (width_inches, height_inches). + """ prs = Presentation(str(pptx_path)) inventory = extract_text_inventory(pptx_path, prs) placeholder_regions = {} @@ -147,6 +195,7 @@ def convert_to_images(pptx_path, temp_dir, dpi): + """Convert PowerPoint to images via PDF, handling hidden slides.""" # Detect hidden slides print("Analyzing presentation...") prs = Presentation(str(pptx_path)) @@ -230,6 +279,7 @@ placeholder_regions=None, slide_dimensions=None, ): + """Create multiple thumbnail grids from slide images, max cols×(cols+1) images per grid.""" # Maximum images per grid is cols × (cols + 1) for better proportions max_images_per_grid = cols * (cols + 1) grid_files = [] @@ -276,6 +326,7 @@ placeholder_regions=None, slide_dimensions=None, ): + """Create thumbnail grid from slide images with optional placeholder outlining.""" font_size = int(width * FONT_SIZE_RATIO) label_padding = int(font_size * LABEL_PADDING_RATIO) @@ -396,4 +447,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/thumbnail.py
Write docstrings that follow conventions
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced, draw_circle from core.easing import interpolate def create_spin_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 30, rotation_type: str = 'clockwise', # 'clockwise', 'counterclockwise', 'wobble', 'pendulum' full_rotations: float = 1.0, easing: str = 'linear', center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] # Default object data if object_data is None: if object_type == 'emoji': object_data = {'emoji': '🔄', 'size': 100} for i in range(num_frames): frame = create_blank_frame(frame_width, frame_height, bg_color) t = i / (num_frames - 1) if num_frames > 1 else 0 # Calculate rotation angle if rotation_type == 'clockwise': angle = interpolate(0, 360 * full_rotations, t, easing) elif rotation_type == 'counterclockwise': angle = interpolate(0, -360 * full_rotations, t, easing) elif rotation_type == 'wobble': # Back and forth rotation angle = math.sin(t * full_rotations * 2 * math.pi) * 45 elif rotation_type == 'pendulum': # Smooth pendulum swing angle = math.sin(t * full_rotations * 2 * math.pi) * 90 else: angle = interpolate(0, 360 * full_rotations, t, easing) # Create object on transparent background to rotate if object_type == 'emoji': # For emoji, we need to create a larger canvas to avoid clipping during rotation emoji_size = object_data['size'] canvas_size = int(emoji_size * 1.5) emoji_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) # Draw emoji in center of canvas from core.frame_composer import draw_emoji_enhanced draw_emoji_enhanced( emoji_canvas, emoji=object_data['emoji'], position=(canvas_size // 2 - emoji_size // 2, canvas_size // 2 - emoji_size // 2), size=emoji_size, shadow=False ) # Rotate the canvas rotated = emoji_canvas.rotate(angle, resample=Image.BICUBIC, expand=False) # Paste onto frame paste_x = center_pos[0] - canvas_size // 2 paste_y = center_pos[1] - canvas_size // 2 frame.paste(rotated, (paste_x, paste_y), rotated) elif object_type == 'text': from core.typography import draw_text_with_outline # Similar approach - create canvas, draw text, rotate text = object_data.get('text', 'SPIN!') font_size = object_data.get('font_size', 50) canvas_size = max(frame_width, frame_height) text_canvas = Image.new('RGBA', (canvas_size, canvas_size), (0, 0, 0, 0)) # Draw text text_canvas_rgb = text_canvas.convert('RGB') text_canvas_rgb.paste(bg_color, (0, 0, canvas_size, canvas_size)) draw_text_with_outline( text_canvas_rgb, text, position=(canvas_size // 2, canvas_size // 2), font_size=font_size, text_color=object_data.get('text_color', (0, 0, 0)), outline_color=object_data.get('outline_color', (255, 255, 255)), outline_width=3, centered=True ) # Convert back to RGBA for rotation text_canvas = text_canvas_rgb.convert('RGBA') # Make background transparent data = text_canvas.getdata() new_data = [] for item in data: if item[:3] == bg_color: new_data.append((255, 255, 255, 0)) else: new_data.append(item) text_canvas.putdata(new_data) # Rotate rotated = text_canvas.rotate(angle, resample=Image.BICUBIC, expand=False) # Composite onto frame frame_rgba = frame.convert('RGBA') frame_rgba = Image.alpha_composite(frame_rgba, rotated) frame = frame_rgba.convert('RGB') frames.append(frame) return frames def create_loading_spinner( num_frames: int = 20, spinner_type: str = 'dots', # 'dots', 'arc', 'emoji' size: int = 100, color: tuple[int, int, int] = (100, 150, 255), frame_width: int = 128, frame_height: int = 128, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: from PIL import ImageDraw frames = [] center = (frame_width // 2, frame_height // 2) for i in range(num_frames): frame = create_blank_frame(frame_width, frame_height, bg_color) draw = ImageDraw.Draw(frame) angle_offset = (i / num_frames) * 360 if spinner_type == 'dots': # Circular dots num_dots = 8 for j in range(num_dots): angle = (j / num_dots * 360 + angle_offset) * math.pi / 180 x = center[0] + size * 0.4 * math.cos(angle) y = center[1] + size * 0.4 * math.sin(angle) # Fade based on position alpha = 1.0 - (j / num_dots) dot_color = tuple(int(c * alpha) for c in color) dot_radius = int(size * 0.1) draw.ellipse( [x - dot_radius, y - dot_radius, x + dot_radius, y + dot_radius], fill=dot_color ) elif spinner_type == 'arc': # Rotating arc start_angle = angle_offset end_angle = angle_offset + 270 arc_width = int(size * 0.15) bbox = [ center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2 ] draw.arc(bbox, start_angle, end_angle, fill=color, width=arc_width) elif spinner_type == 'emoji': # Rotating emoji spinner angle = angle_offset emoji_canvas = Image.new('RGBA', (frame_width, frame_height), (0, 0, 0, 0)) draw_emoji_enhanced( emoji_canvas, emoji='⏳', position=(center[0] - size // 2, center[1] - size // 2), size=size, shadow=False ) rotated = emoji_canvas.rotate(angle, center=center, resample=Image.BICUBIC) frame.paste(rotated, (0, 0), rotated) frames.append(frame) return frames # Example usage if __name__ == '__main__': print("Creating spin animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Clockwise spin frames = create_spin_animation( object_type='emoji', object_data={'emoji': '🔄', 'size': 100}, num_frames=30, rotation_type='clockwise', full_rotations=2 ) builder.add_frames(frames) builder.save('spin_clockwise.gif', num_colors=128) # Example 2: Wobble builder.clear() frames = create_spin_animation( object_type='emoji', object_data={'emoji': '🎯', 'size': 100}, num_frames=30, rotation_type='wobble', full_rotations=3 ) builder.add_frames(frames) builder.save('spin_wobble.gif', num_colors=128) # Example 3: Loading spinner builder = GIFBuilder(width=128, height=128, fps=15) frames = create_loading_spinner(num_frames=20, spinner_type='dots') builder.add_frames(frames) builder.save('loading_spinner.gif', num_colors=64, optimize_for_emoji=True) print("Created spin animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Spin Animation - Rotate objects continuously or with variation. + +Creates spinning, rotating, and wobbling effects. +""" import sys from pathlib import Path @@ -24,6 +29,24 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create spinning/rotating animation. + + Args: + object_type: 'emoji', 'image', 'text' + object_data: Object configuration + num_frames: Number of frames + rotation_type: Type of rotation + full_rotations: Number of complete 360° rotations + easing: Easing function for rotation speed + center_pos: Center position for rotation + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -132,6 +155,21 @@ frame_height: int = 128, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create a loading spinner animation. + + Args: + num_frames: Number of frames + spinner_type: Type of spinner + size: Spinner size + color: Spinner color + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ from PIL import ImageDraw frames = [] center = (frame_width // 2, frame_height // 2) @@ -228,4 +266,4 @@ builder.add_frames(frames) builder.save('loading_spinner.gif', num_colors=64, optimize_for_emoji=True) - print("Created spin animations!")+ print("Created spin animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/spin.py
Write docstrings describing each step
#!/usr/bin/env python3 from pathlib import Path from typing import Optional import imageio.v3 as imageio from PIL import Image import numpy as np class GIFBuilder: def __init__(self, width: int = 480, height: int = 480, fps: int = 15): self.width = width self.height = height self.fps = fps self.frames: list[np.ndarray] = [] def add_frame(self, frame: np.ndarray | Image.Image): if isinstance(frame, Image.Image): frame = np.array(frame.convert('RGB')) # Ensure frame is correct size if frame.shape[:2] != (self.height, self.width): pil_frame = Image.fromarray(frame) pil_frame = pil_frame.resize((self.width, self.height), Image.Resampling.LANCZOS) frame = np.array(pil_frame) self.frames.append(frame) def add_frames(self, frames: list[np.ndarray | Image.Image]): for frame in frames: self.add_frame(frame) def optimize_colors(self, num_colors: int = 128, use_global_palette: bool = True) -> list[np.ndarray]: optimized = [] if use_global_palette and len(self.frames) > 1: # Create a global palette from all frames # Sample frames to build palette sample_size = min(5, len(self.frames)) sample_indices = [int(i * len(self.frames) / sample_size) for i in range(sample_size)] sample_frames = [self.frames[i] for i in sample_indices] # Combine sample frames into a single image for palette generation # Flatten each frame to get all pixels, then stack them all_pixels = np.vstack([f.reshape(-1, 3) for f in sample_frames]) # (total_pixels, 3) # Create a properly-shaped RGB image from the pixel data # We'll make a roughly square image from all the pixels total_pixels = len(all_pixels) width = min(512, int(np.sqrt(total_pixels))) # Reasonable width, max 512 height = (total_pixels + width - 1) // width # Ceiling division # Pad if necessary to fill the rectangle pixels_needed = width * height if pixels_needed > total_pixels: padding = np.zeros((pixels_needed - total_pixels, 3), dtype=np.uint8) all_pixels = np.vstack([all_pixels, padding]) # Reshape to proper RGB image format (H, W, 3) img_array = all_pixels[:pixels_needed].reshape(height, width, 3).astype(np.uint8) combined_img = Image.fromarray(img_array, mode='RGB') # Generate global palette global_palette = combined_img.quantize(colors=num_colors, method=2) # Apply global palette to all frames for frame in self.frames: pil_frame = Image.fromarray(frame) quantized = pil_frame.quantize(palette=global_palette, dither=1) optimized.append(np.array(quantized.convert('RGB'))) else: # Use per-frame quantization for frame in self.frames: pil_frame = Image.fromarray(frame) quantized = pil_frame.quantize(colors=num_colors, method=2, dither=1) optimized.append(np.array(quantized.convert('RGB'))) return optimized def deduplicate_frames(self, threshold: float = 0.995) -> int: if len(self.frames) < 2: return 0 deduplicated = [self.frames[0]] removed_count = 0 for i in range(1, len(self.frames)): # Compare with previous frame prev_frame = np.array(deduplicated[-1], dtype=np.float32) curr_frame = np.array(self.frames[i], dtype=np.float32) # Calculate similarity (normalized) diff = np.abs(prev_frame - curr_frame) similarity = 1.0 - (np.mean(diff) / 255.0) # Keep frame if sufficiently different # High threshold (0.995) means only remove truly identical frames if similarity < threshold: deduplicated.append(self.frames[i]) else: removed_count += 1 self.frames = deduplicated return removed_count def save(self, output_path: str | Path, num_colors: int = 128, optimize_for_emoji: bool = False, remove_duplicates: bool = True) -> dict: if not self.frames: raise ValueError("No frames to save. Add frames with add_frame() first.") output_path = Path(output_path) original_frame_count = len(self.frames) # Remove duplicate frames to reduce file size if remove_duplicates: removed = self.deduplicate_frames(threshold=0.98) if removed > 0: print(f" Removed {removed} duplicate frames") # Optimize for emoji if requested if optimize_for_emoji: if self.width > 128 or self.height > 128: print(f" Resizing from {self.width}x{self.height} to 128x128 for emoji") self.width = 128 self.height = 128 # Resize all frames resized_frames = [] for frame in self.frames: pil_frame = Image.fromarray(frame) pil_frame = pil_frame.resize((128, 128), Image.Resampling.LANCZOS) resized_frames.append(np.array(pil_frame)) self.frames = resized_frames num_colors = min(num_colors, 48) # More aggressive color limit for emoji # More aggressive FPS reduction for emoji if len(self.frames) > 12: print(f" Reducing frames from {len(self.frames)} to ~12 for emoji size") # Keep every nth frame to get close to 12 frames keep_every = max(1, len(self.frames) // 12) self.frames = [self.frames[i] for i in range(0, len(self.frames), keep_every)] # Optimize colors with global palette optimized_frames = self.optimize_colors(num_colors, use_global_palette=True) # Calculate frame duration in milliseconds frame_duration = 1000 / self.fps # Save GIF imageio.imwrite( output_path, optimized_frames, duration=frame_duration, loop=0 # Infinite loop ) # Get file info file_size_kb = output_path.stat().st_size / 1024 file_size_mb = file_size_kb / 1024 info = { 'path': str(output_path), 'size_kb': file_size_kb, 'size_mb': file_size_mb, 'dimensions': f'{self.width}x{self.height}', 'frame_count': len(optimized_frames), 'fps': self.fps, 'duration_seconds': len(optimized_frames) / self.fps, 'colors': num_colors } # Print info print(f"\n✓ GIF created successfully!") print(f" Path: {output_path}") print(f" Size: {file_size_kb:.1f} KB ({file_size_mb:.2f} MB)") print(f" Dimensions: {self.width}x{self.height}") print(f" Frames: {len(optimized_frames)} @ {self.fps} fps") print(f" Duration: {info['duration_seconds']:.1f}s") print(f" Colors: {num_colors}") # Warnings if optimize_for_emoji and file_size_kb > 64: print(f"\n⚠️ WARNING: Emoji file size ({file_size_kb:.1f} KB) exceeds 64 KB limit") print(" Try: fewer frames, fewer colors, or simpler design") elif not optimize_for_emoji and file_size_kb > 2048: print(f"\n⚠️ WARNING: File size ({file_size_kb:.1f} KB) is large for Slack") print(" Try: fewer frames, smaller dimensions, or fewer colors") return info def clear(self): self.frames = []
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +GIF Builder - Core module for assembling frames into GIFs optimized for Slack. + +This module provides the main interface for creating GIFs from programmatically +generated frames, with automatic optimization for Slack's requirements. +""" from pathlib import Path from typing import Optional @@ -8,14 +14,29 @@ class GIFBuilder: + """Builder for creating optimized GIFs from frames.""" def __init__(self, width: int = 480, height: int = 480, fps: int = 15): + """ + Initialize GIF builder. + + Args: + width: Frame width in pixels + height: Frame height in pixels + fps: Frames per second + """ self.width = width self.height = height self.fps = fps self.frames: list[np.ndarray] = [] def add_frame(self, frame: np.ndarray | Image.Image): + """ + Add a frame to the GIF. + + Args: + frame: Frame as numpy array or PIL Image (will be converted to RGB) + """ if isinstance(frame, Image.Image): frame = np.array(frame.convert('RGB')) @@ -28,10 +49,21 @@ self.frames.append(frame) def add_frames(self, frames: list[np.ndarray | Image.Image]): + """Add multiple frames at once.""" for frame in frames: self.add_frame(frame) def optimize_colors(self, num_colors: int = 128, use_global_palette: bool = True) -> list[np.ndarray]: + """ + Reduce colors in all frames using quantization. + + Args: + num_colors: Target number of colors (8-256) + use_global_palette: Use a single palette for all frames (better compression) + + Returns: + List of color-optimized frames + """ optimized = [] if use_global_palette and len(self.frames) > 1: @@ -79,6 +111,15 @@ return optimized def deduplicate_frames(self, threshold: float = 0.995) -> int: + """ + Remove duplicate or near-duplicate consecutive frames. + + Args: + threshold: Similarity threshold (0.0-1.0). Higher = more strict (0.995 = very similar). + + Returns: + Number of frames removed + """ if len(self.frames) < 2: return 0 @@ -106,6 +147,18 @@ def save(self, output_path: str | Path, num_colors: int = 128, optimize_for_emoji: bool = False, remove_duplicates: bool = True) -> dict: + """ + Save frames as optimized GIF for Slack. + + Args: + output_path: Where to save the GIF + num_colors: Number of colors to use (fewer = smaller file) + optimize_for_emoji: If True, optimize for <64KB emoji size + remove_duplicates: Remove duplicate consecutive frames + + Returns: + Dictionary with file info (path, size, dimensions, frame_count) + """ if not self.frames: raise ValueError("No frames to save. Add frames with add_frame() first.") @@ -189,4 +242,5 @@ return info def clear(self): + """Clear all frames (useful for creating multiple GIFs).""" self.frames = []
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/gif_builder.py
Add return value explanations in docstrings
#!/usr/bin/env python3 import sys from pathlib import Path import math sys.path.append(str(Path(__file__).parent.parent)) from PIL import Image from core.gif_builder import GIFBuilder from core.frame_composer import create_blank_frame, draw_emoji_enhanced, draw_circle from core.easing import interpolate def create_pulse_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 30, pulse_type: str = 'smooth', # 'smooth', 'heartbeat', 'throb', 'pop' scale_range: tuple[float, float] = (0.8, 1.2), pulses: float = 2.0, center_pos: tuple[int, int] = (240, 240), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: frames = [] # Default object data if object_data is None: if object_type == 'emoji': object_data = {'emoji': '❤️', 'size': 100} elif object_type == 'circle': object_data = {'radius': 50, 'color': (255, 100, 100)} min_scale, max_scale = scale_range for i in range(num_frames): frame = create_blank_frame(frame_width, frame_height, bg_color) t = i / (num_frames - 1) if num_frames > 1 else 0 # Calculate scale based on pulse type if pulse_type == 'smooth': # Simple sinusoidal pulse scale = min_scale + (max_scale - min_scale) * ( 0.5 + 0.5 * math.sin(t * pulses * 2 * math.pi - math.pi / 2) ) elif pulse_type == 'heartbeat': # Double pump like a heartbeat phase = (t * pulses) % 1.0 if phase < 0.15: # First pump scale = interpolate(min_scale, max_scale, phase / 0.15, 'ease_out') elif phase < 0.25: # First release scale = interpolate(max_scale, min_scale, (phase - 0.15) / 0.10, 'ease_in') elif phase < 0.35: # Second pump (smaller) scale = interpolate(min_scale, (min_scale + max_scale) / 2, (phase - 0.25) / 0.10, 'ease_out') elif phase < 0.45: # Second release scale = interpolate((min_scale + max_scale) / 2, min_scale, (phase - 0.35) / 0.10, 'ease_in') else: # Rest period scale = min_scale elif pulse_type == 'throb': # Sharp pulse with quick return phase = (t * pulses) % 1.0 if phase < 0.2: scale = interpolate(min_scale, max_scale, phase / 0.2, 'ease_out') else: scale = interpolate(max_scale, min_scale, (phase - 0.2) / 0.8, 'ease_in') elif pulse_type == 'pop': # Pop out and back with overshoot phase = (t * pulses) % 1.0 if phase < 0.3: # Pop out with overshoot scale = interpolate(min_scale, max_scale * 1.1, phase / 0.3, 'elastic_out') else: # Settle back scale = interpolate(max_scale * 1.1, min_scale, (phase - 0.3) / 0.7, 'ease_out') else: scale = min_scale + (max_scale - min_scale) * ( 0.5 + 0.5 * math.sin(t * pulses * 2 * math.pi) ) # Draw object at calculated scale if object_type == 'emoji': base_size = object_data['size'] current_size = int(base_size * scale) draw_emoji_enhanced( frame, emoji=object_data['emoji'], position=(center_pos[0] - current_size // 2, center_pos[1] - current_size // 2), size=current_size, shadow=object_data.get('shadow', True) ) elif object_type == 'circle': base_radius = object_data['radius'] current_radius = int(base_radius * scale) draw_circle( frame, center=center_pos, radius=current_radius, fill_color=object_data['color'] ) elif object_type == 'text': from core.typography import draw_text_with_outline base_size = object_data.get('font_size', 50) current_size = int(base_size * scale) draw_text_with_outline( frame, text=object_data.get('text', 'PULSE'), position=center_pos, font_size=current_size, text_color=object_data.get('text_color', (255, 100, 100)), outline_color=object_data.get('outline_color', (0, 0, 0)), outline_width=3, centered=True ) frames.append(frame) return frames def create_attention_pulse( emoji: str = '⚠️', num_frames: int = 20, frame_size: int = 128, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: return create_pulse_animation( object_type='emoji', object_data={'emoji': emoji, 'size': 80, 'shadow': False}, num_frames=num_frames, pulse_type='throb', scale_range=(0.85, 1.15), pulses=2, center_pos=(frame_size // 2, frame_size // 2), frame_width=frame_size, frame_height=frame_size, bg_color=bg_color ) def create_breathing_animation( object_type: str = 'emoji', object_data: dict | None = None, num_frames: int = 60, breaths: float = 2.0, scale_range: tuple[float, float] = (0.9, 1.1), frame_width: int = 480, frame_height: int = 480, bg_color: tuple[int, int, int] = (240, 248, 255) ) -> list[Image.Image]: if object_data is None: object_data = {'emoji': '😌', 'size': 100} return create_pulse_animation( object_type=object_type, object_data=object_data, num_frames=num_frames, pulse_type='smooth', scale_range=scale_range, pulses=breaths, center_pos=(frame_width // 2, frame_height // 2), frame_width=frame_width, frame_height=frame_height, bg_color=bg_color ) # Example usage if __name__ == '__main__': print("Creating pulse animations...") builder = GIFBuilder(width=480, height=480, fps=20) # Example 1: Smooth pulse frames = create_pulse_animation( object_type='emoji', object_data={'emoji': '❤️', 'size': 100}, num_frames=40, pulse_type='smooth', scale_range=(0.8, 1.2), pulses=2 ) builder.add_frames(frames) builder.save('pulse_smooth.gif', num_colors=128) # Example 2: Heartbeat builder.clear() frames = create_pulse_animation( object_type='emoji', object_data={'emoji': '💓', 'size': 100}, num_frames=60, pulse_type='heartbeat', scale_range=(0.85, 1.2), pulses=3 ) builder.add_frames(frames) builder.save('pulse_heartbeat.gif', num_colors=128) # Example 3: Attention pulse (emoji size) builder = GIFBuilder(width=128, height=128, fps=15) frames = create_attention_pulse(emoji='⚠️', num_frames=20) builder.add_frames(frames) builder.save('pulse_attention.gif', num_colors=48, optimize_for_emoji=True) print("Created pulse animations!")
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Pulse Animation - Scale objects rhythmically for emphasis. + +Creates pulsing, heartbeat, and throbbing effects. +""" import sys from pathlib import Path @@ -24,6 +29,24 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create pulsing/scaling animation. + + Args: + object_type: 'emoji', 'circle', 'text' + object_data: Object configuration + num_frames: Number of frames + pulse_type: Type of pulsing motion + scale_range: (min_scale, max_scale) tuple + pulses: Number of pulses in animation + center_pos: Center position + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ frames = [] # Default object data @@ -136,6 +159,18 @@ frame_size: int = 128, bg_color: tuple[int, int, int] = (255, 255, 255) ) -> list[Image.Image]: + """ + Create attention-grabbing pulse (good for emoji GIFs). + + Args: + emoji: Emoji to pulse + num_frames: Number of frames + frame_size: Frame size (square) + bg_color: Background color + + Returns: + List of frames optimized for emoji size + """ return create_pulse_animation( object_type='emoji', object_data={'emoji': emoji, 'size': 80, 'shadow': False}, @@ -160,6 +195,22 @@ frame_height: int = 480, bg_color: tuple[int, int, int] = (240, 248, 255) ) -> list[Image.Image]: + """ + Create slow, calming breathing animation (in and out). + + Args: + object_type: Type of object + object_data: Object configuration + num_frames: Number of frames + breaths: Number of breathing cycles + scale_range: Min/max scale + frame_width: Frame width + frame_height: Frame height + bg_color: Background color + + Returns: + List of frames + """ if object_data is None: object_data = {'emoji': '😌', 'size': 100} @@ -214,4 +265,4 @@ builder.add_frames(frames) builder.save('pulse_attention.gif', num_colors=48, optimize_for_emoji=True) - print("Created pulse animations!")+ print("Created pulse animations!")
https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/pulse.py
Write docstrings for algorithm functions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import json import os from datetime import datetime from pathlib import Path from core import search, DATA_DIR # ============ CONFIGURATION ============ REASONING_FILE = "ui-reasoning.csv" SEARCH_CONFIG = { "product": {"max_results": 1}, "style": {"max_results": 3}, "color": {"max_results": 2}, "landing": {"max_results": 2}, "typography": {"max_results": 2} } # ============ DESIGN SYSTEM GENERATOR ============ class DesignSystemGenerator: def __init__(self): self.reasoning_data = self._load_reasoning() def _load_reasoning(self) -> list: filepath = DATA_DIR / REASONING_FILE if not filepath.exists(): return [] with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _multi_domain_search(self, query: str, style_priority: list = None) -> dict: results = {} for domain, config in SEARCH_CONFIG.items(): if domain == "style" and style_priority: # For style, also search with priority keywords priority_query = " ".join(style_priority[:2]) if style_priority else query combined_query = f"{query} {priority_query}" results[domain] = search(combined_query, domain, config["max_results"]) else: results[domain] = search(query, domain, config["max_results"]) return results def _find_reasoning_rule(self, category: str) -> dict: category_lower = category.lower() # Try exact match first for rule in self.reasoning_data: if rule.get("UI_Category", "").lower() == category_lower: return rule # Try partial match for rule in self.reasoning_data: ui_cat = rule.get("UI_Category", "").lower() if ui_cat in category_lower or category_lower in ui_cat: return rule # Try keyword match for rule in self.reasoning_data: ui_cat = rule.get("UI_Category", "").lower() keywords = ui_cat.replace("/", " ").replace("-", " ").split() if any(kw in category_lower for kw in keywords): return rule return {} def _apply_reasoning(self, category: str, search_results: dict) -> dict: rule = self._find_reasoning_rule(category) if not rule: return { "pattern": "Hero + Features + CTA", "style_priority": ["Minimalism", "Flat Design"], "color_mood": "Professional", "typography_mood": "Clean", "key_effects": "Subtle hover transitions", "anti_patterns": "", "decision_rules": {}, "severity": "MEDIUM" } # Parse decision rules JSON decision_rules = {} try: decision_rules = json.loads(rule.get("Decision_Rules", "{}")) except json.JSONDecodeError: pass return { "pattern": rule.get("Recommended_Pattern", ""), "style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")], "color_mood": rule.get("Color_Mood", ""), "typography_mood": rule.get("Typography_Mood", ""), "key_effects": rule.get("Key_Effects", ""), "anti_patterns": rule.get("Anti_Patterns", ""), "decision_rules": decision_rules, "severity": rule.get("Severity", "MEDIUM") } def _select_best_match(self, results: list, priority_keywords: list) -> dict: if not results: return {} if not priority_keywords: return results[0] # First: try exact style name match for priority in priority_keywords: priority_lower = priority.lower().strip() for result in results: style_name = result.get("Style Category", "").lower() if priority_lower in style_name or style_name in priority_lower: return result # Second: score by keyword match in all fields scored = [] for result in results: result_str = str(result).lower() score = 0 for kw in priority_keywords: kw_lower = kw.lower().strip() # Higher score for style name match if kw_lower in result.get("Style Category", "").lower(): score += 10 # Lower score for keyword field match elif kw_lower in result.get("Keywords", "").lower(): score += 3 # Even lower for other field matches elif kw_lower in result_str: score += 1 scored.append((score, result)) scored.sort(key=lambda x: x[0], reverse=True) return scored[0][1] if scored and scored[0][0] > 0 else results[0] def _extract_results(self, search_result: dict) -> list: return search_result.get("results", []) def generate(self, query: str, project_name: str = None) -> dict: # Step 1: First search product to get category product_result = search(query, "product", 1) product_results = product_result.get("results", []) category = "General" if product_results: category = product_results[0].get("Product Type", "General") # Step 2: Get reasoning rules for this category reasoning = self._apply_reasoning(category, {}) style_priority = reasoning.get("style_priority", []) # Step 3: Multi-domain search with style priority hints search_results = self._multi_domain_search(query, style_priority) search_results["product"] = product_result # Reuse product search # Step 4: Select best matches from each domain using priority style_results = self._extract_results(search_results.get("style", {})) color_results = self._extract_results(search_results.get("color", {})) typography_results = self._extract_results(search_results.get("typography", {})) landing_results = self._extract_results(search_results.get("landing", {})) best_style = self._select_best_match(style_results, reasoning.get("style_priority", [])) best_color = color_results[0] if color_results else {} best_typography = typography_results[0] if typography_results else {} best_landing = landing_results[0] if landing_results else {} # Step 5: Build final recommendation # Combine effects from both reasoning and style search style_effects = best_style.get("Effects & Animation", "") reasoning_effects = reasoning.get("key_effects", "") combined_effects = style_effects if style_effects else reasoning_effects return { "project_name": project_name or query.upper(), "category": category, "pattern": { "name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")), "sections": best_landing.get("Section Order", "Hero > Features > CTA"), "cta_placement": best_landing.get("Primary CTA Placement", "Above fold"), "color_strategy": best_landing.get("Color Strategy", ""), "conversion": best_landing.get("Conversion Optimization", "") }, "style": { "name": best_style.get("Style Category", "Minimalism"), "type": best_style.get("Type", "General"), "effects": style_effects, "keywords": best_style.get("Keywords", ""), "best_for": best_style.get("Best For", ""), "performance": best_style.get("Performance", ""), "accessibility": best_style.get("Accessibility", "") }, "colors": { "primary": best_color.get("Primary (Hex)", "#2563EB"), "secondary": best_color.get("Secondary (Hex)", "#3B82F6"), "cta": best_color.get("CTA (Hex)", "#F97316"), "background": best_color.get("Background (Hex)", "#F8FAFC"), "text": best_color.get("Text (Hex)", "#1E293B"), "notes": best_color.get("Notes", "") }, "typography": { "heading": best_typography.get("Heading Font", "Inter"), "body": best_typography.get("Body Font", "Inter"), "mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")), "best_for": best_typography.get("Best For", ""), "google_fonts_url": best_typography.get("Google Fonts URL", ""), "css_import": best_typography.get("CSS Import", "") }, "key_effects": combined_effects, "anti_patterns": reasoning.get("anti_patterns", ""), "decision_rules": reasoning.get("decision_rules", {}), "severity": reasoning.get("severity", "MEDIUM") } # ============ OUTPUT FORMATTERS ============ BOX_WIDTH = 90 # Wider box for more content def format_ascii_box(design_system: dict) -> str: project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) colors = design_system.get("colors", {}) typography = design_system.get("typography", {}) effects = design_system.get("key_effects", "") anti_patterns = design_system.get("anti_patterns", "") def wrap_text(text: str, prefix: str, width: int) -> list: if not text: return [] words = text.split() lines = [] current_line = prefix for word in words: if len(current_line) + len(word) + 1 <= width - 2: current_line += (" " if current_line != prefix else "") + word else: if current_line != prefix: lines.append(current_line) current_line = prefix + word if current_line != prefix: lines.append(current_line) return lines # Build sections from pattern sections = pattern.get("sections", "").split(">") sections = [s.strip() for s in sections if s.strip()] # Build output lines lines = [] w = BOX_WIDTH - 1 lines.append("+" + "-" * w + "+") lines.append(f"| TARGET: {project} - RECOMMENDED DESIGN SYSTEM".ljust(BOX_WIDTH) + "|") lines.append("+" + "-" * w + "+") lines.append("|" + " " * BOX_WIDTH + "|") # Pattern section lines.append(f"| PATTERN: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "|") if pattern.get('conversion'): lines.append(f"| Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "|") if pattern.get('cta_placement'): lines.append(f"| CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "|") lines.append("| Sections:".ljust(BOX_WIDTH) + "|") for i, section in enumerate(sections, 1): lines.append(f"| {i}. {section}".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Style section lines.append(f"| STYLE: {style.get('name', '')}".ljust(BOX_WIDTH) + "|") if style.get("keywords"): for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if style.get("best_for"): for line in wrap_text(f"Best For: {style.get('best_for', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if style.get("performance") or style.get("accessibility"): perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}" lines.append(f"| {perf_a11y}".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Colors section lines.append("| COLORS:".ljust(BOX_WIDTH) + "|") lines.append(f"| Primary: {colors.get('primary', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| Secondary: {colors.get('secondary', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| CTA: {colors.get('cta', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| Background: {colors.get('background', '')}".ljust(BOX_WIDTH) + "|") lines.append(f"| Text: {colors.get('text', '')}".ljust(BOX_WIDTH) + "|") if colors.get("notes"): for line in wrap_text(f"Notes: {colors.get('notes', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Typography section lines.append(f"| TYPOGRAPHY: {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "|") if typography.get("mood"): for line in wrap_text(f"Mood: {typography.get('mood', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if typography.get("best_for"): for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") if typography.get("google_fonts_url"): lines.append(f"| Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "|") if typography.get("css_import"): lines.append(f"| CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Key Effects section if effects: lines.append("| KEY EFFECTS:".ljust(BOX_WIDTH) + "|") for line in wrap_text(effects, "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Anti-patterns section if anti_patterns: lines.append("| AVOID (Anti-patterns):".ljust(BOX_WIDTH) + "|") for line in wrap_text(anti_patterns, "| ", BOX_WIDTH): lines.append(line.ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") # Pre-Delivery Checklist section lines.append("| PRE-DELIVERY CHECKLIST:".ljust(BOX_WIDTH) + "|") checklist_items = [ "[ ] No emojis as icons (use SVG: Heroicons/Lucide)", "[ ] cursor-pointer on all clickable elements", "[ ] Hover states with smooth transitions (150-300ms)", "[ ] Light mode: text contrast 4.5:1 minimum", "[ ] Focus states visible for keyboard nav", "[ ] prefers-reduced-motion respected", "[ ] Responsive: 375px, 768px, 1024px, 1440px" ] for item in checklist_items: lines.append(f"| {item}".ljust(BOX_WIDTH) + "|") lines.append("|" + " " * BOX_WIDTH + "|") lines.append("+" + "-" * w + "+") return "\n".join(lines) def format_markdown(design_system: dict) -> str: project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) colors = design_system.get("colors", {}) typography = design_system.get("typography", {}) effects = design_system.get("key_effects", "") anti_patterns = design_system.get("anti_patterns", "") lines = [] lines.append(f"## Design System: {project}") lines.append("") # Pattern section lines.append("### Pattern") lines.append(f"- **Name:** {pattern.get('name', '')}") if pattern.get('conversion'): lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}") if pattern.get('cta_placement'): lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}") if pattern.get('color_strategy'): lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}") lines.append(f"- **Sections:** {pattern.get('sections', '')}") lines.append("") # Style section lines.append("### Style") lines.append(f"- **Name:** {style.get('name', '')}") if style.get('keywords'): lines.append(f"- **Keywords:** {style.get('keywords', '')}") if style.get('best_for'): lines.append(f"- **Best For:** {style.get('best_for', '')}") if style.get('performance') or style.get('accessibility'): lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}") lines.append("") # Colors section lines.append("### Colors") lines.append(f"| Role | Hex |") lines.append(f"|------|-----|") lines.append(f"| Primary | {colors.get('primary', '')} |") lines.append(f"| Secondary | {colors.get('secondary', '')} |") lines.append(f"| CTA | {colors.get('cta', '')} |") lines.append(f"| Background | {colors.get('background', '')} |") lines.append(f"| Text | {colors.get('text', '')} |") if colors.get("notes"): lines.append(f"\n*Notes: {colors.get('notes', '')}*") lines.append("") # Typography section lines.append("### Typography") lines.append(f"- **Heading:** {typography.get('heading', '')}") lines.append(f"- **Body:** {typography.get('body', '')}") if typography.get("mood"): lines.append(f"- **Mood:** {typography.get('mood', '')}") if typography.get("best_for"): lines.append(f"- **Best For:** {typography.get('best_for', '')}") if typography.get("google_fonts_url"): lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}") if typography.get("css_import"): lines.append(f"- **CSS Import:**") lines.append(f"```css") lines.append(f"{typography.get('css_import', '')}") lines.append(f"```") lines.append("") # Key Effects section if effects: lines.append("### Key Effects") lines.append(f"{effects}") lines.append("") # Anti-patterns section if anti_patterns: lines.append("### Avoid (Anti-patterns)") newline_bullet = '\n- ' lines.append(f"- {anti_patterns.replace(' + ', newline_bullet)}") lines.append("") # Pre-Delivery Checklist section lines.append("### Pre-Delivery Checklist") lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)") lines.append("- [ ] cursor-pointer on all clickable elements") lines.append("- [ ] Hover states with smooth transitions (150-300ms)") lines.append("- [ ] Light mode: text contrast 4.5:1 minimum") lines.append("- [ ] Focus states visible for keyboard nav") lines.append("- [ ] prefers-reduced-motion respected") lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px") lines.append("") return "\n".join(lines) # ============ MAIN ENTRY POINT ============ def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii", persist: bool = False, page: str = None, output_dir: str = None) -> str: generator = DesignSystemGenerator() design_system = generator.generate(query, project_name) # Persist to files if requested if persist: persist_design_system(design_system, page, output_dir, query) if output_format == "markdown": return format_markdown(design_system) return format_ascii_box(design_system) # ============ PERSISTENCE FUNCTIONS ============ def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict: base_dir = Path(output_dir) if output_dir else Path.cwd() # Use project name for project-specific folder project_name = design_system.get("project_name", "default") project_slug = project_name.lower().replace(' ', '-') design_system_dir = base_dir / "design-system" / project_slug pages_dir = design_system_dir / "pages" created_files = [] # Create directories design_system_dir.mkdir(parents=True, exist_ok=True) pages_dir.mkdir(parents=True, exist_ok=True) master_file = design_system_dir / "MASTER.md" # Generate and write MASTER.md master_content = format_master_md(design_system) with open(master_file, 'w', encoding='utf-8') as f: f.write(master_content) created_files.append(str(master_file)) # If page is specified, create page override file with intelligent content if page: page_file = pages_dir / f"{page.lower().replace(' ', '-')}.md" page_content = format_page_override_md(design_system, page, page_query) with open(page_file, 'w', encoding='utf-8') as f: f.write(page_content) created_files.append(str(page_file)) return { "status": "success", "design_system_dir": str(design_system_dir), "created_files": created_files } def format_master_md(design_system: dict) -> str: project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) colors = design_system.get("colors", {}) typography = design_system.get("typography", {}) effects = design_system.get("key_effects", "") anti_patterns = design_system.get("anti_patterns", "") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") lines = [] # Logic header lines.append("# Design System Master File") lines.append("") lines.append("> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.") lines.append("> If that file exists, its rules **override** this Master file.") lines.append("> If not, strictly follow the rules below.") lines.append("") lines.append("---") lines.append("") lines.append(f"**Project:** {project}") lines.append(f"**Generated:** {timestamp}") lines.append(f"**Category:** {design_system.get('category', 'General')}") lines.append("") lines.append("---") lines.append("") # Global Rules section lines.append("## Global Rules") lines.append("") # Color Palette lines.append("### Color Palette") lines.append("") lines.append("| Role | Hex | CSS Variable |") lines.append("|------|-----|--------------|") lines.append(f"| Primary | `{colors.get('primary', '#2563EB')}` | `--color-primary` |") lines.append(f"| Secondary | `{colors.get('secondary', '#3B82F6')}` | `--color-secondary` |") lines.append(f"| CTA/Accent | `{colors.get('cta', '#F97316')}` | `--color-cta` |") lines.append(f"| Background | `{colors.get('background', '#F8FAFC')}` | `--color-background` |") lines.append(f"| Text | `{colors.get('text', '#1E293B')}` | `--color-text` |") lines.append("") if colors.get("notes"): lines.append(f"**Color Notes:** {colors.get('notes', '')}") lines.append("") # Typography lines.append("### Typography") lines.append("") lines.append(f"- **Heading Font:** {typography.get('heading', 'Inter')}") lines.append(f"- **Body Font:** {typography.get('body', 'Inter')}") if typography.get("mood"): lines.append(f"- **Mood:** {typography.get('mood', '')}") if typography.get("google_fonts_url"): lines.append(f"- **Google Fonts:** [{typography.get('heading', '')} + {typography.get('body', '')}]({typography.get('google_fonts_url', '')})") lines.append("") if typography.get("css_import"): lines.append("**CSS Import:**") lines.append("```css") lines.append(typography.get("css_import", "")) lines.append("```") lines.append("") # Spacing Variables lines.append("### Spacing Variables") lines.append("") lines.append("| Token | Value | Usage |") lines.append("|-------|-------|-------|") lines.append("| `--space-xs` | `4px` / `0.25rem` | Tight gaps |") lines.append("| `--space-sm` | `8px` / `0.5rem` | Icon gaps, inline spacing |") lines.append("| `--space-md` | `16px` / `1rem` | Standard padding |") lines.append("| `--space-lg` | `24px` / `1.5rem` | Section padding |") lines.append("| `--space-xl` | `32px` / `2rem` | Large gaps |") lines.append("| `--space-2xl` | `48px` / `3rem` | Section margins |") lines.append("| `--space-3xl` | `64px` / `4rem` | Hero padding |") lines.append("") # Shadow Depths lines.append("### Shadow Depths") lines.append("") lines.append("| Level | Value | Usage |") lines.append("|-------|-------|-------|") lines.append("| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |") lines.append("| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |") lines.append("| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |") lines.append("| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |") lines.append("") # Component Specs section lines.append("---") lines.append("") lines.append("## Component Specs") lines.append("") # Buttons lines.append("### Buttons") lines.append("") lines.append("```css") lines.append("/* Primary Button */") lines.append(".btn-primary {") lines.append(f" background: {colors.get('cta', '#F97316')};") lines.append(" color: white;") lines.append(" padding: 12px 24px;") lines.append(" border-radius: 8px;") lines.append(" font-weight: 600;") lines.append(" transition: all 200ms ease;") lines.append(" cursor: pointer;") lines.append("}") lines.append("") lines.append(".btn-primary:hover {") lines.append(" opacity: 0.9;") lines.append(" transform: translateY(-1px);") lines.append("}") lines.append("") lines.append("/* Secondary Button */") lines.append(".btn-secondary {") lines.append(f" background: transparent;") lines.append(f" color: {colors.get('primary', '#2563EB')};") lines.append(f" border: 2px solid {colors.get('primary', '#2563EB')};") lines.append(" padding: 12px 24px;") lines.append(" border-radius: 8px;") lines.append(" font-weight: 600;") lines.append(" transition: all 200ms ease;") lines.append(" cursor: pointer;") lines.append("}") lines.append("```") lines.append("") # Cards lines.append("### Cards") lines.append("") lines.append("```css") lines.append(".card {") lines.append(f" background: {colors.get('background', '#FFFFFF')};") lines.append(" border-radius: 12px;") lines.append(" padding: 24px;") lines.append(" box-shadow: var(--shadow-md);") lines.append(" transition: all 200ms ease;") lines.append(" cursor: pointer;") lines.append("}") lines.append("") lines.append(".card:hover {") lines.append(" box-shadow: var(--shadow-lg);") lines.append(" transform: translateY(-2px);") lines.append("}") lines.append("```") lines.append("") # Inputs lines.append("### Inputs") lines.append("") lines.append("```css") lines.append(".input {") lines.append(" padding: 12px 16px;") lines.append(" border: 1px solid #E2E8F0;") lines.append(" border-radius: 8px;") lines.append(" font-size: 16px;") lines.append(" transition: border-color 200ms ease;") lines.append("}") lines.append("") lines.append(".input:focus {") lines.append(f" border-color: {colors.get('primary', '#2563EB')};") lines.append(" outline: none;") lines.append(f" box-shadow: 0 0 0 3px {colors.get('primary', '#2563EB')}20;") lines.append("}") lines.append("```") lines.append("") # Modals lines.append("### Modals") lines.append("") lines.append("```css") lines.append(".modal-overlay {") lines.append(" background: rgba(0, 0, 0, 0.5);") lines.append(" backdrop-filter: blur(4px);") lines.append("}") lines.append("") lines.append(".modal {") lines.append(" background: white;") lines.append(" border-radius: 16px;") lines.append(" padding: 32px;") lines.append(" box-shadow: var(--shadow-xl);") lines.append(" max-width: 500px;") lines.append(" width: 90%;") lines.append("}") lines.append("```") lines.append("") # Style section lines.append("---") lines.append("") lines.append("## Style Guidelines") lines.append("") lines.append(f"**Style:** {style.get('name', 'Minimalism')}") lines.append("") if style.get("keywords"): lines.append(f"**Keywords:** {style.get('keywords', '')}") lines.append("") if style.get("best_for"): lines.append(f"**Best For:** {style.get('best_for', '')}") lines.append("") if effects: lines.append(f"**Key Effects:** {effects}") lines.append("") # Layout Pattern lines.append("### Page Pattern") lines.append("") lines.append(f"**Pattern Name:** {pattern.get('name', '')}") lines.append("") if pattern.get('conversion'): lines.append(f"- **Conversion Strategy:** {pattern.get('conversion', '')}") if pattern.get('cta_placement'): lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}") lines.append(f"- **Section Order:** {pattern.get('sections', '')}") lines.append("") # Anti-Patterns section lines.append("---") lines.append("") lines.append("## Anti-Patterns (Do NOT Use)") lines.append("") if anti_patterns: anti_list = [a.strip() for a in anti_patterns.split("+")] for anti in anti_list: if anti: lines.append(f"- ❌ {anti}") lines.append("") lines.append("### Additional Forbidden Patterns") lines.append("") lines.append("- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)") lines.append("- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer") lines.append("- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout") lines.append("- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio") lines.append("- ❌ **Instant state changes** — Always use transitions (150-300ms)") lines.append("- ❌ **Invisible focus states** — Focus states must be visible for a11y") lines.append("") # Pre-Delivery Checklist lines.append("---") lines.append("") lines.append("## Pre-Delivery Checklist") lines.append("") lines.append("Before delivering any UI code, verify:") lines.append("") lines.append("- [ ] No emojis used as icons (use SVG instead)") lines.append("- [ ] All icons from consistent icon set (Heroicons/Lucide)") lines.append("- [ ] `cursor-pointer` on all clickable elements") lines.append("- [ ] Hover states with smooth transitions (150-300ms)") lines.append("- [ ] Light mode: text contrast 4.5:1 minimum") lines.append("- [ ] Focus states visible for keyboard navigation") lines.append("- [ ] `prefers-reduced-motion` respected") lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px") lines.append("- [ ] No content hidden behind fixed navbars") lines.append("- [ ] No horizontal scroll on mobile") lines.append("") return "\n".join(lines) def format_page_override_md(design_system: dict, page_name: str, page_query: str = None) -> str: project = design_system.get("project_name", "PROJECT") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") page_title = page_name.replace("-", " ").replace("_", " ").title() # Detect page type and generate intelligent overrides page_overrides = _generate_intelligent_overrides(page_name, page_query, design_system) lines = [] lines.append(f"# {page_title} Page Overrides") lines.append("") lines.append(f"> **PROJECT:** {project}") lines.append(f"> **Generated:** {timestamp}") lines.append(f"> **Page Type:** {page_overrides.get('page_type', 'General')}") lines.append("") lines.append("> ⚠️ **IMPORTANT:** Rules in this file **override** the Master file (`design-system/MASTER.md`).") lines.append("> Only deviations from the Master are documented here. For all other rules, refer to the Master.") lines.append("") lines.append("---") lines.append("") # Page-specific rules with actual content lines.append("## Page-Specific Rules") lines.append("") # Layout Overrides lines.append("### Layout Overrides") lines.append("") layout = page_overrides.get("layout", {}) if layout: for key, value in layout.items(): lines.append(f"- **{key}:** {value}") else: lines.append("- No overrides — use Master layout") lines.append("") # Spacing Overrides lines.append("### Spacing Overrides") lines.append("") spacing = page_overrides.get("spacing", {}) if spacing: for key, value in spacing.items(): lines.append(f"- **{key}:** {value}") else: lines.append("- No overrides — use Master spacing") lines.append("") # Typography Overrides lines.append("### Typography Overrides") lines.append("") typography = page_overrides.get("typography", {}) if typography: for key, value in typography.items(): lines.append(f"- **{key}:** {value}") else: lines.append("- No overrides — use Master typography") lines.append("") # Color Overrides lines.append("### Color Overrides") lines.append("") colors = page_overrides.get("colors", {}) if colors: for key, value in colors.items(): lines.append(f"- **{key}:** {value}") else: lines.append("- No overrides — use Master colors") lines.append("") # Component Overrides lines.append("### Component Overrides") lines.append("") components = page_overrides.get("components", []) if components: for comp in components: lines.append(f"- {comp}") else: lines.append("- No overrides — use Master component specs") lines.append("") # Page-Specific Components lines.append("---") lines.append("") lines.append("## Page-Specific Components") lines.append("") unique_components = page_overrides.get("unique_components", []) if unique_components: for comp in unique_components: lines.append(f"- {comp}") else: lines.append("- No unique components for this page") lines.append("") # Recommendations lines.append("---") lines.append("") lines.append("## Recommendations") lines.append("") recommendations = page_overrides.get("recommendations", []) if recommendations: for rec in recommendations: lines.append(f"- {rec}") lines.append("") return "\n".join(lines) def _generate_intelligent_overrides(page_name: str, page_query: str, design_system: dict) -> dict: from core import search page_lower = page_name.lower() query_lower = (page_query or "").lower() combined_context = f"{page_lower} {query_lower}" # Search across multiple domains for page-specific guidance style_search = search(combined_context, "style", max_results=1) ux_search = search(combined_context, "ux", max_results=3) landing_search = search(combined_context, "landing", max_results=1) # Extract results from search response style_results = style_search.get("results", []) ux_results = ux_search.get("results", []) landing_results = landing_search.get("results", []) # Detect page type from search results or context page_type = _detect_page_type(combined_context, style_results) # Build overrides from search results layout = {} spacing = {} typography = {} colors = {} components = [] unique_components = [] recommendations = [] # Extract style-based overrides if style_results: style = style_results[0] style_name = style.get("Style Category", "") keywords = style.get("Keywords", "") best_for = style.get("Best For", "") effects = style.get("Effects & Animation", "") # Infer layout from style keywords if any(kw in keywords.lower() for kw in ["data", "dense", "dashboard", "grid"]): layout["Max Width"] = "1400px or full-width" layout["Grid"] = "12-column grid for data flexibility" spacing["Content Density"] = "High — optimize for information display" elif any(kw in keywords.lower() for kw in ["minimal", "simple", "clean", "single"]): layout["Max Width"] = "800px (narrow, focused)" layout["Layout"] = "Single column, centered" spacing["Content Density"] = "Low — focus on clarity" else: layout["Max Width"] = "1200px (standard)" layout["Layout"] = "Full-width sections, centered content" if effects: recommendations.append(f"Effects: {effects}") # Extract UX guidelines as recommendations for ux in ux_results: category = ux.get("Category", "") do_text = ux.get("Do", "") dont_text = ux.get("Don't", "") if do_text: recommendations.append(f"{category}: {do_text}") if dont_text: components.append(f"Avoid: {dont_text}") # Extract landing pattern info for section structure if landing_results: landing = landing_results[0] sections = landing.get("Section Order", "") cta_placement = landing.get("Primary CTA Placement", "") color_strategy = landing.get("Color Strategy", "") if sections: layout["Sections"] = sections if cta_placement: recommendations.append(f"CTA Placement: {cta_placement}") if color_strategy: colors["Strategy"] = color_strategy # Add page-type specific defaults if no search results if not layout: layout["Max Width"] = "1200px" layout["Layout"] = "Responsive grid" if not recommendations: recommendations = [ "Refer to MASTER.md for all design rules", "Add specific overrides as needed for this page" ] return { "page_type": page_type, "layout": layout, "spacing": spacing, "typography": typography, "colors": colors, "components": components, "unique_components": unique_components, "recommendations": recommendations } def _detect_page_type(context: str, style_results: list) -> str: context_lower = context.lower() # Check for common page type patterns page_patterns = [ (["dashboard", "admin", "analytics", "data", "metrics", "stats", "monitor", "overview"], "Dashboard / Data View"), (["checkout", "payment", "cart", "purchase", "order", "billing"], "Checkout / Payment"), (["settings", "profile", "account", "preferences", "config"], "Settings / Profile"), (["landing", "marketing", "homepage", "hero", "home", "promo"], "Landing / Marketing"), (["login", "signin", "signup", "register", "auth", "password"], "Authentication"), (["pricing", "plans", "subscription", "tiers", "packages"], "Pricing / Plans"), (["blog", "article", "post", "news", "content", "story"], "Blog / Article"), (["product", "item", "detail", "pdp", "shop", "store"], "Product Detail"), (["search", "results", "browse", "filter", "catalog", "list"], "Search Results"), (["empty", "404", "error", "not found", "zero"], "Empty State"), ] for keywords, page_type in page_patterns: if any(kw in context_lower for kw in keywords): return page_type # Fallback: try to infer from style results if style_results: style_name = style_results[0].get("Style Category", "").lower() best_for = style_results[0].get("Best For", "").lower() if "dashboard" in best_for or "data" in best_for: return "Dashboard / Data View" elif "landing" in best_for or "marketing" in best_for: return "Landing / Marketing" return "General" # ============ CLI SUPPORT ============ if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Generate Design System") parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')") parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name") parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format") args = parser.parse_args() result = generate_design_system(args.query, args.project_name, args.format) print(result)
--- +++ @@ -1,5 +1,17 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Design System Generator - Aggregates search results and applies reasoning +to generate comprehensive design system recommendations. + +Usage: + from design_system import generate_design_system + result = generate_design_system("SaaS dashboard", "My Project") + + # With persistence (Master + Overrides pattern) + result = generate_design_system("SaaS dashboard", "My Project", persist=True) + result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard") +""" import csv import json @@ -23,11 +35,13 @@ # ============ DESIGN SYSTEM GENERATOR ============ class DesignSystemGenerator: + """Generates design system recommendations from aggregated searches.""" def __init__(self): self.reasoning_data = self._load_reasoning() def _load_reasoning(self) -> list: + """Load reasoning rules from CSV.""" filepath = DATA_DIR / REASONING_FILE if not filepath.exists(): return [] @@ -35,6 +49,7 @@ return list(csv.DictReader(f)) def _multi_domain_search(self, query: str, style_priority: list = None) -> dict: + """Execute searches across multiple domains.""" results = {} for domain, config in SEARCH_CONFIG.items(): if domain == "style" and style_priority: @@ -47,6 +62,7 @@ return results def _find_reasoning_rule(self, category: str) -> dict: + """Find matching reasoning rule for a category.""" category_lower = category.lower() # Try exact match first @@ -70,6 +86,7 @@ return {} def _apply_reasoning(self, category: str, search_results: dict) -> dict: + """Apply reasoning rules to search results.""" rule = self._find_reasoning_rule(category) if not rule: @@ -103,6 +120,7 @@ } def _select_best_match(self, results: list, priority_keywords: list) -> dict: + """Select best matching result based on priority keywords.""" if not results: return {} @@ -139,9 +157,11 @@ return scored[0][1] if scored and scored[0][0] > 0 else results[0] def _extract_results(self, search_result: dict) -> list: + """Extract results list from search result dict.""" return search_result.get("results", []) def generate(self, query: str, project_name: str = None) -> dict: + """Generate complete design system recommendation.""" # Step 1: First search product to get category product_result = search(query, "product", 1) product_results = product_result.get("results", []) @@ -220,6 +240,7 @@ BOX_WIDTH = 90 # Wider box for more content def format_ascii_box(design_system: dict) -> str: + """Format design system as ASCII box with emojis (MCP-style).""" project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) @@ -229,6 +250,7 @@ anti_patterns = design_system.get("anti_patterns", "") def wrap_text(text: str, prefix: str, width: int) -> list: + """Wrap long text into multiple lines.""" if not text: return [] words = text.split() @@ -343,6 +365,7 @@ def format_markdown(design_system: dict) -> str: + """Format design system as markdown.""" project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) @@ -438,6 +461,20 @@ # ============ MAIN ENTRY POINT ============ def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii", persist: bool = False, page: str = None, output_dir: str = None) -> str: + """ + Main entry point for design system generation. + + Args: + query: Search query (e.g., "SaaS dashboard", "e-commerce luxury") + project_name: Optional project name for output header + output_format: "ascii" (default) or "markdown" + persist: If True, save design system to design-system/ folder + page: Optional page name for page-specific override file + output_dir: Optional output directory (defaults to current working directory) + + Returns: + Formatted design system string + """ generator = DesignSystemGenerator() design_system = generator.generate(query, project_name) @@ -452,6 +489,18 @@ # ============ PERSISTENCE FUNCTIONS ============ def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict: + """ + Persist design system to design-system/<project>/ folder using Master + Overrides pattern. + + Args: + design_system: The generated design system dictionary + page: Optional page name for page-specific override file + output_dir: Optional output directory (defaults to current working directory) + page_query: Optional query string for intelligent page override generation + + Returns: + dict with created file paths and status + """ base_dir = Path(output_dir) if output_dir else Path.cwd() # Use project name for project-specific folder @@ -491,6 +540,7 @@ def format_master_md(design_system: dict) -> str: + """Format design system as MASTER.md with hierarchical override logic.""" project = design_system.get("project_name", "PROJECT") pattern = design_system.get("pattern", {}) style = design_system.get("style", {}) @@ -753,6 +803,7 @@ def format_page_override_md(design_system: dict, page_name: str, page_query: str = None) -> str: + """Format a page-specific override file with intelligent AI-generated content.""" project = design_system.get("project_name", "PROJECT") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") page_title = page_name.replace("-", " ").replace("_", " ").title() @@ -861,6 +912,12 @@ def _generate_intelligent_overrides(page_name: str, page_query: str, design_system: dict) -> dict: + """ + Generate intelligent overrides based on page type using layered search. + + Uses the existing search infrastructure to find relevant style, UX, and layout + data instead of hardcoded page types. + """ from core import search page_lower = page_name.lower() @@ -961,6 +1018,7 @@ def _detect_page_type(context: str, style_results: list) -> str: + """Detect page type from context and search results.""" context_lower = context.lower() # Check for common page type patterns @@ -1006,4 +1064,4 @@ args = parser.parse_args() result = generate_design_system(args.query, args.project_name, args.format) - print(result)+ print(result)
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/cli/assets/scripts/design_system.py
Generate docstrings with parameter types
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import json import sys from pathlib import Path # Add parent directory for imports sys.path.insert(0, str(Path(__file__).parent)) from core import search, search_all, get_cip_brief, CSV_CONFIG def format_results(results, domain): if not results: return "No results found." output = [] for i, item in enumerate(results, 1): output.append(f"\n{'='*60}") output.append(f"Result {i}:") for key, value in item.items(): if value: output.append(f" {key}: {value}") return "\n".join(output) def format_brief(brief): output = [] output.append(f"\n{'='*60}") output.append(f"CIP DESIGN BRIEF: {brief['brand_name']}") output.append(f"{'='*60}") if brief.get("industry"): output.append(f"\n📊 INDUSTRY: {brief['industry'].get('Industry', 'N/A')}") output.append(f" Style: {brief['industry'].get('CIP Style', 'N/A')}") output.append(f" Mood: {brief['industry'].get('Mood', 'N/A')}") if brief.get("style"): output.append(f"\n🎨 DESIGN STYLE: {brief['style'].get('Style Name', 'N/A')}") output.append(f" Description: {brief['style'].get('Description', 'N/A')}") output.append(f" Materials: {brief['style'].get('Materials', 'N/A')}") output.append(f" Finishes: {brief['style'].get('Finishes', 'N/A')}") if brief.get("color_system"): output.append(f"\n🎯 COLOR SYSTEM:") output.append(f" Primary: {brief['color_system'].get('primary', 'N/A')}") output.append(f" Secondary: {brief['color_system'].get('secondary', 'N/A')}") output.append(f"\n✏️ TYPOGRAPHY: {brief.get('typography', 'N/A')}") if brief.get("recommended_deliverables"): output.append(f"\n📦 RECOMMENDED DELIVERABLES:") for d in brief["recommended_deliverables"]: output.append(f" • {d.get('Deliverable', 'N/A')}: {d.get('Description', '')[:60]}...") return "\n".join(output) def main(): parser = argparse.ArgumentParser( description="Search CIP design guidelines", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Search deliverables python search.py "business card" # Search specific domain python search.py "luxury elegant" --domain style # Generate CIP brief python search.py "tech startup" --cip-brief -b "TechFlow" # Search all domains python search.py "corporate professional" --all # JSON output python search.py "vehicle branding" --json """ ) parser.add_argument("query", help="Search query") parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain (auto-detected if not specified)") parser.add_argument("--max", "-m", type=int, default=3, help="Max results (default: 3)") parser.add_argument("--all", "-a", action="store_true", help="Search all domains") parser.add_argument("--cip-brief", "-c", action="store_true", help="Generate CIP brief") parser.add_argument("--brand", "-b", default="BrandName", help="Brand name for CIP brief") parser.add_argument("--style", "-s", help="Style override for CIP brief") parser.add_argument("--json", "-j", action="store_true", help="Output as JSON") args = parser.parse_args() if args.cip_brief: brief = get_cip_brief(args.brand, args.query, args.style) if args.json: print(json.dumps(brief, indent=2)) else: print(format_brief(brief)) elif args.all: results = search_all(args.query, args.max) if args.json: print(json.dumps(results, indent=2)) else: for domain, items in results.items(): print(f"\n{'#'*60}") print(f"# {domain.upper()}") print(format_results(items, domain)) else: result = search(args.query, args.domain, args.max) if args.json: print(json.dumps(result, indent=2)) else: print(f"\nDomain: {result['domain']}") print(f"Query: {result['query']}") print(f"Results: {result['count']}") print(format_results(result.get("results", []), result["domain"])) if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +CIP Design Search CLI - Search corporate identity design guidelines +""" import argparse import json @@ -12,6 +15,7 @@ def format_results(results, domain): + """Format search results for display""" if not results: return "No results found." @@ -26,6 +30,7 @@ def format_brief(brief): + """Format CIP brief for display""" output = [] output.append(f"\n{'='*60}") output.append(f"CIP DESIGN BRIEF: {brief['brand_name']}") @@ -119,4 +124,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/search.py
Annotate my code with docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import re from pathlib import Path from math import log from collections import defaultdict # ============ CONFIGURATION ============ DATA_DIR = Path(__file__).parent.parent / "data" MAX_RESULTS = 3 CSV_CONFIG = { "style": { "file": "styles.csv", "search_cols": ["Style Category", "Keywords", "Best For", "Type", "AI Prompt Keywords"], "output_cols": ["Style Category", "Type", "Keywords", "Primary Colors", "Effects & Animation", "Best For", "Performance", "Accessibility", "Framework Compatibility", "Complexity", "AI Prompt Keywords", "CSS/Technical Keywords", "Implementation Checklist", "Design System Variables"] }, "color": { "file": "colors.csv", "search_cols": ["Product Type", "Notes"], "output_cols": ["Product Type", "Primary", "On Primary", "Secondary", "On Secondary", "Accent", "On Accent", "Background", "Foreground", "Card", "Card Foreground", "Muted", "Muted Foreground", "Border", "Destructive", "On Destructive", "Ring", "Notes"] }, "chart": { "file": "charts.csv", "search_cols": ["Data Type", "Keywords", "Best Chart Type", "When to Use", "When NOT to Use", "Accessibility Notes"], "output_cols": ["Data Type", "Keywords", "Best Chart Type", "Secondary Options", "When to Use", "When NOT to Use", "Data Volume Threshold", "Color Guidance", "Accessibility Grade", "Accessibility Notes", "A11y Fallback", "Library Recommendation", "Interactive Level"] }, "landing": { "file": "landing.csv", "search_cols": ["Pattern Name", "Keywords", "Conversion Optimization", "Section Order"], "output_cols": ["Pattern Name", "Keywords", "Section Order", "Primary CTA Placement", "Color Strategy", "Conversion Optimization"] }, "product": { "file": "products.csv", "search_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Key Considerations"], "output_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Secondary Styles", "Landing Page Pattern", "Dashboard Style (if applicable)", "Color Palette Focus"] }, "ux": { "file": "ux-guidelines.csv", "search_cols": ["Category", "Issue", "Description", "Platform"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "typography": { "file": "typography.csv", "search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"], "output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"] }, "icons": { "file": "icons.csv", "search_cols": ["Category", "Icon Name", "Keywords", "Best For"], "output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"] }, "react": { "file": "react-performance.csv", "search_cols": ["Category", "Issue", "Keywords", "Description"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "web": { "file": "app-interface.csv", "search_cols": ["Category", "Issue", "Keywords", "Description"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "google-fonts": { "file": "google-fonts.csv", "search_cols": ["Family", "Category", "Stroke", "Classifications", "Keywords", "Subsets", "Designers"], "output_cols": ["Family", "Category", "Stroke", "Classifications", "Styles", "Variable Axes", "Subsets", "Designers", "Popularity Rank", "Google Fonts URL"] } } STACK_CONFIG = { "react-native": {"file": "stacks/react-native.csv"}, } # Common columns for all stacks _STACK_COLS = { "search_cols": ["Category", "Guideline", "Description", "Do", "Don't"], "output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"] } AVAILABLE_STACKS = list(STACK_CONFIG.keys()) # ============ BM25 IMPLEMENTATION ============ class BM25: def __init__(self, k1=1.5, b=0.75): self.k1 = k1 self.b = b self.corpus = [] self.doc_lengths = [] self.avgdl = 0 self.idf = {} self.doc_freqs = defaultdict(int) self.N = 0 def tokenize(self, text): text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: return self.doc_lengths = [len(doc) for doc in self.corpus] self.avgdl = sum(self.doc_lengths) / self.N for doc in self.corpus: seen = set() for word in doc: if word not in seen: self.doc_freqs[word] += 1 seen.add(word) for word, freq in self.doc_freqs.items(): self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): query_tokens = self.tokenize(query) scores = [] for idx, doc in enumerate(self.corpus): score = 0 doc_len = self.doc_lengths[idx] term_freqs = defaultdict(int) for word in doc: term_freqs[word] += 1 for token in query_tokens: if token in self.idf: tf = term_freqs[token] idf = self.idf[token] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl) score += idf * numerator / denominator scores.append((idx, score)) return sorted(scores, key=lambda x: x[1], reverse=True) # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): if not filepath.exists(): return [] data = _load_csv(filepath) # Build documents from search columns documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data] # BM25 search bm25 = BM25() bm25.fit(documents) ranked = bm25.score(query) # Get top results with score > 0 results = [] for idx, score in ranked[:max_results]: if score > 0: row = data[idx] results.append({col: row.get(col, "") for col in output_cols if col in row}) return results def detect_domain(query): query_lower = query.lower() domain_keywords = { "color": ["color", "palette", "hex", "#", "rgb", "token", "semantic", "accent", "destructive", "muted", "foreground"], "chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"], "landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"], "product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard", "fitness", "restaurant", "hotel", "travel", "music", "education", "learning", "legal", "insurance", "medical", "beauty", "pharmacy", "dental", "pet", "dating", "wedding", "recipe", "delivery", "ride", "booking", "calendar", "timer", "tracker", "diary", "note", "chat", "messenger", "crm", "invoice", "parking", "transit", "vpn", "alarm", "weather", "sleep", "meditation", "fasting", "habit", "grocery", "meme", "wardrobe", "plant care", "reading", "flashcard", "puzzle", "trivia", "arcade", "photography", "streaming", "podcast", "newsletter", "marketplace", "freelancer", "coworking", "airline", "museum", "theater", "church", "non-profit", "charity", "kindergarten", "daycare", "senior care", "veterinary", "florist", "bakery", "brewery", "construction", "automotive", "real estate", "logistics", "agriculture", "coding bootcamp"], "style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"], "ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"], "typography": ["font pairing", "typography pairing", "heading font", "body font"], "google-fonts": ["google font", "font family", "font weight", "font style", "variable font", "noto", "font for", "find font", "font subset", "font language", "monospace font", "serif font", "sans serif font", "display font", "handwriting font", "font", "typography", "serif", "sans"], "icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"], "react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"], "web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"] } scores = {domain: sum(1 for kw in keywords if re.search(r'\b' + re.escape(kw) + r'\b', query_lower)) for domain, keywords in domain_keywords.items()} best = max(scores, key=scores.get) return best if scores[best] > 0 else "style" def search(query, domain=None, max_results=MAX_RESULTS): if domain is None: domain = detect_domain(query) config = CSV_CONFIG.get(domain, CSV_CONFIG["style"]) filepath = DATA_DIR / config["file"] if not filepath.exists(): return {"error": f"File not found: {filepath}", "domain": domain} results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results) return { "domain": domain, "query": query, "file": config["file"], "count": len(results), "results": results } def search_stack(query, stack, max_results=MAX_RESULTS): if stack not in STACK_CONFIG: return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"} filepath = DATA_DIR / STACK_CONFIG[stack]["file"] if not filepath.exists(): return {"error": f"Stack file not found: {filepath}", "stack": stack} results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results) return { "domain": "stack", "stack": stack, "query": query, "file": STACK_CONFIG[stack]["file"], "count": len(results), "results": results }
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +UI/UX Pro Max Core - BM25 search engine for UI/UX style guides +""" import csv import re @@ -84,6 +87,7 @@ # ============ BM25 IMPLEMENTATION ============ class BM25: + """BM25 ranking algorithm for text search""" def __init__(self, k1=1.5, b=0.75): self.k1 = k1 @@ -96,10 +100,12 @@ self.N = 0 def tokenize(self, text): + """Lowercase, split, remove punctuation, filter short words""" text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): + """Build BM25 index from documents""" self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: @@ -118,6 +124,7 @@ self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): + """Score all documents against query""" query_tokens = self.tokenize(query) scores = [] @@ -143,11 +150,13 @@ # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): + """Load CSV and return list of dicts""" with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): + """Core search function using BM25""" if not filepath.exists(): return [] @@ -172,6 +181,7 @@ def detect_domain(query): + """Auto-detect the most relevant domain from query""" query_lower = query.lower() domain_keywords = { @@ -194,6 +204,7 @@ def search(query, domain=None, max_results=MAX_RESULTS): + """Main search function with auto-domain detection""" if domain is None: domain = detect_domain(query) @@ -215,6 +226,7 @@ def search_stack(query, stack, max_results=MAX_RESULTS): + """Search stack-specific guidelines""" if stack not in STACK_CONFIG: return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"} @@ -232,4 +244,4 @@ "file": STACK_CONFIG[stack]["file"], "count": len(results), "results": results - }+ }
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/src/ui-ux-pro-max/scripts/core.py
Generate consistent documentation across files
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import sys import io from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack from design_system import generate_design_system, persist_design_system # Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default) if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8': sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8': sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') def format_output(result): if "error" in result: return f"Error: {result['error']}" output = [] if result.get("stack"): output.append(f"## UI Pro Max Stack Guidelines") output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}") else: output.append(f"## UI Pro Max Search Results") output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}") output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n") for i, row in enumerate(result['results'], 1): output.append(f"### Result {i}") for key, value in row.items(): value_str = str(value) if len(value_str) > 300: value_str = value_str[:300] + "..." output.append(f"- **{key}:** {value_str}") output.append("") return "\n".join(output) if __name__ == "__main__": parser = argparse.ArgumentParser(description="UI Pro Max Search") parser.add_argument("query", help="Search query") parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain") parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)") parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)") parser.add_argument("--json", action="store_true", help="Output as JSON") # Design system generation parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation") parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output") parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system") # Persistence (Master + Overrides pattern) parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)") parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/") parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)") args = parser.parse_args() # Design system takes priority if args.design_system: result = generate_design_system( args.query, args.project_name, args.format, persist=args.persist, page=args.page, output_dir=args.output_dir ) print(result) # Print persistence confirmation if args.persist: project_slug = args.project_name.lower().replace(' ', '-') if args.project_name else "default" print("\n" + "=" * 60) print(f"✅ Design system persisted to design-system/{project_slug}/") print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)") if args.page: page_filename = args.page.lower().replace(' ', '-') print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)") print("") print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.") print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.") print("=" * 60) # Stack search elif args.stack: result = search_stack(args.query, args.stack, args.max_results) if args.json: import json print(json.dumps(result, indent=2, ensure_ascii=False)) else: print(format_output(result)) # Domain search else: result = search(args.query, args.domain, args.max_results) if args.json: import json print(json.dumps(result, indent=2, ensure_ascii=False)) else: print(format_output(result))
--- +++ @@ -1,100 +1,114 @@-#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -import argparse -import sys -import io -from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack -from design_system import generate_design_system, persist_design_system - -# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default) -if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8': - sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') -if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8': - sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') - - -def format_output(result): - if "error" in result: - return f"Error: {result['error']}" - - output = [] - if result.get("stack"): - output.append(f"## UI Pro Max Stack Guidelines") - output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}") - else: - output.append(f"## UI Pro Max Search Results") - output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}") - output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n") - - for i, row in enumerate(result['results'], 1): - output.append(f"### Result {i}") - for key, value in row.items(): - value_str = str(value) - if len(value_str) > 300: - value_str = value_str[:300] + "..." - output.append(f"- **{key}:** {value_str}") - output.append("") - - return "\n".join(output) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="UI Pro Max Search") - parser.add_argument("query", help="Search query") - parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain") - parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)") - parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)") - parser.add_argument("--json", action="store_true", help="Output as JSON") - # Design system generation - parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation") - parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output") - parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system") - # Persistence (Master + Overrides pattern) - parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)") - parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/") - parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)") - - args = parser.parse_args() - - # Design system takes priority - if args.design_system: - result = generate_design_system( - args.query, - args.project_name, - args.format, - persist=args.persist, - page=args.page, - output_dir=args.output_dir - ) - print(result) - - # Print persistence confirmation - if args.persist: - project_slug = args.project_name.lower().replace(' ', '-') if args.project_name else "default" - print("\n" + "=" * 60) - print(f"✅ Design system persisted to design-system/{project_slug}/") - print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)") - if args.page: - page_filename = args.page.lower().replace(' ', '-') - print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)") - print("") - print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.") - print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.") - print("=" * 60) - # Stack search - elif args.stack: - result = search_stack(args.query, args.stack, args.max_results) - if args.json: - import json - print(json.dumps(result, indent=2, ensure_ascii=False)) - else: - print(format_output(result)) - # Domain search - else: - result = search(args.query, args.domain, args.max_results) - if args.json: - import json - print(json.dumps(result, indent=2, ensure_ascii=False)) - else: - print(format_output(result))+#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +UI/UX Pro Max Search - BM25 search engine for UI/UX style guides +Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3] + python search.py "<query>" --design-system [-p "Project Name"] + python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"] + +Domains: style, prompt, color, chart, landing, product, ux, typography, google-fonts +Stacks: html-tailwind, react, nextjs + +Persistence (Master + Overrides pattern): + --persist Save design system to design-system/MASTER.md + --page Also create a page-specific override file in design-system/pages/ +""" + +import argparse +import sys +import io +from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack +from design_system import generate_design_system, persist_design_system + +# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default) +if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8': + sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') +if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8': + sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') + + +def format_output(result): + """Format results for Claude consumption (token-optimized)""" + if "error" in result: + return f"Error: {result['error']}" + + output = [] + if result.get("stack"): + output.append(f"## UI Pro Max Stack Guidelines") + output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}") + else: + output.append(f"## UI Pro Max Search Results") + output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}") + output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n") + + for i, row in enumerate(result['results'], 1): + output.append(f"### Result {i}") + for key, value in row.items(): + value_str = str(value) + if len(value_str) > 300: + value_str = value_str[:300] + "..." + output.append(f"- **{key}:** {value_str}") + output.append("") + + return "\n".join(output) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="UI Pro Max Search") + parser.add_argument("query", help="Search query") + parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain") + parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)") + parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)") + parser.add_argument("--json", action="store_true", help="Output as JSON") + # Design system generation + parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation") + parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output") + parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system") + # Persistence (Master + Overrides pattern) + parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)") + parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/") + parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)") + + args = parser.parse_args() + + # Design system takes priority + if args.design_system: + result = generate_design_system( + args.query, + args.project_name, + args.format, + persist=args.persist, + page=args.page, + output_dir=args.output_dir + ) + print(result) + + # Print persistence confirmation + if args.persist: + project_slug = args.project_name.lower().replace(' ', '-') if args.project_name else "default" + print("\n" + "=" * 60) + print(f"✅ Design system persisted to design-system/{project_slug}/") + print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)") + if args.page: + page_filename = args.page.lower().replace(' ', '-') + print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)") + print("") + print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.") + print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.") + print("=" * 60) + # Stack search + elif args.stack: + result = search_stack(args.query, args.stack, args.max_results) + if args.json: + import json + print(json.dumps(result, indent=2, ensure_ascii=False)) + else: + print(format_output(result)) + # Domain search + else: + result = search(args.query, args.domain, args.max_results) + if args.json: + import json + print(json.dumps(result, indent=2, ensure_ascii=False)) + else: + print(format_output(result))
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/src/ui-ux-pro-max/scripts/search.py
Create docstrings for all classes and functions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import re from pathlib import Path from math import log from collections import defaultdict # ============ CONFIGURATION ============ DATA_DIR = Path(__file__).parent.parent / "data" MAX_RESULTS = 3 CSV_CONFIG = { "strategy": { "file": "slide-strategies.csv", "search_cols": ["strategy_name", "keywords", "goal", "audience", "narrative_arc"], "output_cols": ["strategy_name", "keywords", "slide_count", "structure", "goal", "audience", "tone", "narrative_arc", "sources"] }, "layout": { "file": "slide-layouts.csv", "search_cols": ["layout_name", "keywords", "use_case", "recommended_for"], "output_cols": ["layout_name", "keywords", "use_case", "content_zones", "visual_weight", "cta_placement", "recommended_for", "avoid_for", "css_structure"] }, "copy": { "file": "slide-copy.csv", "search_cols": ["formula_name", "keywords", "use_case", "emotion_trigger", "slide_type"], "output_cols": ["formula_name", "keywords", "components", "use_case", "example_template", "emotion_trigger", "slide_type", "source"] }, "chart": { "file": "slide-charts.csv", "search_cols": ["chart_type", "keywords", "best_for", "when_to_use", "slide_context"], "output_cols": ["chart_type", "keywords", "best_for", "data_type", "when_to_use", "when_to_avoid", "max_categories", "slide_context", "css_implementation", "accessibility_notes"] } } AVAILABLE_DOMAINS = list(CSV_CONFIG.keys()) # ============ BM25 IMPLEMENTATION ============ class BM25: def __init__(self, k1=1.5, b=0.75): self.k1 = k1 self.b = b self.corpus = [] self.doc_lengths = [] self.avgdl = 0 self.idf = {} self.doc_freqs = defaultdict(int) self.N = 0 def tokenize(self, text): text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: return self.doc_lengths = [len(doc) for doc in self.corpus] self.avgdl = sum(self.doc_lengths) / self.N for doc in self.corpus: seen = set() for word in doc: if word not in seen: self.doc_freqs[word] += 1 seen.add(word) for word, freq in self.doc_freqs.items(): self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): query_tokens = self.tokenize(query) scores = [] for idx, doc in enumerate(self.corpus): score = 0 doc_len = self.doc_lengths[idx] term_freqs = defaultdict(int) for word in doc: term_freqs[word] += 1 for token in query_tokens: if token in self.idf: tf = term_freqs[token] idf = self.idf[token] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl) score += idf * numerator / denominator scores.append((idx, score)) return sorted(scores, key=lambda x: x[1], reverse=True) # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): if not filepath.exists(): return [] data = _load_csv(filepath) # Build documents from search columns documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data] # BM25 search bm25 = BM25() bm25.fit(documents) ranked = bm25.score(query) # Get top results with score > 0 results = [] for idx, score in ranked[:max_results]: if score > 0: row = data[idx] results.append({col: row.get(col, "") for col in output_cols if col in row}) return results def detect_domain(query): query_lower = query.lower() domain_keywords = { "strategy": ["pitch", "deck", "investor", "yc", "seed", "series", "demo", "sales", "webinar", "conference", "board", "qbr", "all-hands", "duarte", "kawasaki", "structure"], "layout": ["slide", "layout", "grid", "column", "title", "hero", "section", "cta", "screenshot", "quote", "timeline", "comparison", "pricing", "team"], "copy": ["headline", "copy", "formula", "aida", "pas", "hook", "cta", "benefit", "objection", "proof", "testimonial", "urgency", "scarcity"], "chart": ["chart", "graph", "bar", "line", "pie", "funnel", "metrics", "data", "visualization", "kpi", "trend", "comparison", "heatmap", "gauge"] } scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()} best = max(scores, key=scores.get) return best if scores[best] > 0 else "strategy" def search(query, domain=None, max_results=MAX_RESULTS): if domain is None: domain = detect_domain(query) config = CSV_CONFIG.get(domain, CSV_CONFIG["strategy"]) filepath = DATA_DIR / config["file"] if not filepath.exists(): return {"error": f"File not found: {filepath}", "domain": domain} results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results) return { "domain": domain, "query": query, "file": config["file"], "count": len(results), "results": results } def search_all(query, max_results=2): all_results = {} for domain in AVAILABLE_DOMAINS: result = search(query, domain, max_results) if result.get("count", 0) > 0: all_results[domain] = result return all_results # ============ CONTEXTUAL SEARCH (Premium Slide System) ============ # New CSV configurations for decision system DECISION_CSV_CONFIG = { "layout-logic": { "file": "slide-layout-logic.csv", "key_col": "goal" }, "typography": { "file": "slide-typography.csv", "key_col": "content_type" }, "color-logic": { "file": "slide-color-logic.csv", "key_col": "emotion" }, "backgrounds": { "file": "slide-backgrounds.csv", "key_col": "slide_type" } } def _load_decision_csv(csv_type): config = DECISION_CSV_CONFIG.get(csv_type) if not config: return {} filepath = DATA_DIR / config["file"] if not filepath.exists(): return {} data = _load_csv(filepath) return {row[config["key_col"]]: row for row in data if config["key_col"] in row} def get_layout_for_goal(goal, previous_emotion=None): layouts = _load_decision_csv("layout-logic") row = layouts.get(goal, layouts.get("features", {})) result = dict(row) if row else {} # Apply pattern-breaking logic if result.get("break_pattern") == "true" and previous_emotion: result["_pattern_break"] = True result["_contrast_with"] = previous_emotion return result def get_typography_for_slide(slide_type, has_metrics=False, has_quote=False): typography = _load_decision_csv("typography") if has_metrics: return typography.get("metric-callout", {}) if has_quote: return typography.get("quote-block", {}) # Map slide types to typography type_map = { "hero": "hero-statement", "hook": "hero-statement", "title": "title-only", "problem": "subtitle-heavy", "agitation": "metric-callout", "solution": "subtitle-heavy", "features": "feature-grid", "proof": "metric-callout", "traction": "data-insight", "social": "quote-block", "testimonial": "testimonial", "pricing": "pricing", "team": "team", "cta": "cta-action", "comparison": "comparison", "timeline": "timeline", } content_type = type_map.get(slide_type, "feature-grid") return typography.get(content_type, {}) def get_color_for_emotion(emotion): colors = _load_decision_csv("color-logic") return colors.get(emotion, colors.get("clarity", {})) def get_background_config(slide_type): backgrounds = _load_decision_csv("backgrounds") return backgrounds.get(slide_type, {}) def should_use_full_bleed(slide_index, total_slides, emotion): high_emotion_beats = ["hope", "urgency", "fear", "curiosity"] if emotion not in high_emotion_beats: return False if total_slides < 3: return False third = total_slides // 3 strategic_positions = [1, third, third * 2, total_slides - 1] return slide_index in strategic_positions def calculate_pattern_break(slide_index, total_slides, previous_emotion=None): # Pattern breaks at strategic positions if total_slides < 5: return False # Break at 1/3 and 2/3 points third = total_slides // 3 if slide_index in [third, third * 2]: return True # Break when switching between frustration and hope contrasting_emotions = { "frustration": ["hope", "relief"], "hope": ["frustration", "fear"], "fear": ["hope", "relief"], } if previous_emotion in contrasting_emotions: return True return False def search_with_context(query, slide_position=1, total_slides=9, previous_emotion=None): # Get base results from existing BM25 search base_results = search_all(query, max_results=2) # Detect likely slide goal from query goal = detect_domain(query.lower()) if "problem" in query.lower(): goal = "problem" elif "solution" in query.lower(): goal = "solution" elif "cta" in query.lower() or "call to action" in query.lower(): goal = "cta" elif "hook" in query.lower() or "title" in query.lower(): goal = "hook" elif "traction" in query.lower() or "metric" in query.lower(): goal = "traction" # Enrich with contextual recommendations context = { "slide_position": slide_position, "total_slides": total_slides, "previous_emotion": previous_emotion, "inferred_goal": goal, } # Get layout recommendation layout = get_layout_for_goal(goal, previous_emotion) if layout: context["recommended_layout"] = layout.get("layout_pattern") context["layout_direction"] = layout.get("direction") context["visual_weight"] = layout.get("visual_weight") context["use_background_image"] = layout.get("use_bg_image") == "true" # Get typography recommendation typography = get_typography_for_slide(goal) if typography: context["typography"] = { "primary_size": typography.get("primary_size"), "secondary_size": typography.get("secondary_size"), "weight_contrast": typography.get("weight_contrast"), } # Get color treatment emotion = layout.get("emotion", "clarity") if layout else "clarity" color = get_color_for_emotion(emotion) if color: context["color_treatment"] = { "background": color.get("background"), "text_color": color.get("text_color"), "accent_usage": color.get("accent_usage"), "card_style": color.get("card_style"), } # Calculate pattern breaking context["should_break_pattern"] = calculate_pattern_break( slide_position, total_slides, previous_emotion ) context["should_use_full_bleed"] = should_use_full_bleed( slide_position, total_slides, emotion ) # Get background config if needed if context.get("use_background_image"): bg_config = get_background_config(goal) if bg_config: context["background"] = { "image_category": bg_config.get("image_category"), "overlay_style": bg_config.get("overlay_style"), "search_keywords": bg_config.get("search_keywords"), } # Suggested animation classes animation_map = { "hook": "animate-fade-up", "problem": "animate-fade-up", "agitation": "animate-count animate-stagger", "solution": "animate-scale", "features": "animate-stagger", "traction": "animate-chart animate-count", "proof": "animate-stagger-scale", "social": "animate-fade-up", "cta": "animate-pulse", } context["animation_class"] = animation_map.get(goal, "animate-fade-up") return { "query": query, "context": context, "base_results": base_results, }
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Slide Search Core - BM25 search engine for slide design databases +""" import csv import re @@ -39,6 +42,7 @@ # ============ BM25 IMPLEMENTATION ============ class BM25: + """BM25 ranking algorithm for text search""" def __init__(self, k1=1.5, b=0.75): self.k1 = k1 @@ -51,10 +55,12 @@ self.N = 0 def tokenize(self, text): + """Lowercase, split, remove punctuation, filter short words""" text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): + """Build BM25 index from documents""" self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: @@ -73,6 +79,7 @@ self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): + """Score all documents against query""" query_tokens = self.tokenize(query) scores = [] @@ -98,11 +105,13 @@ # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): + """Load CSV and return list of dicts""" with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): + """Core search function using BM25""" if not filepath.exists(): return [] @@ -127,6 +136,7 @@ def detect_domain(query): + """Auto-detect the most relevant domain from query""" query_lower = query.lower() domain_keywords = { @@ -146,6 +156,7 @@ def search(query, domain=None, max_results=MAX_RESULTS): + """Main search function with auto-domain detection""" if domain is None: domain = detect_domain(query) @@ -167,6 +178,7 @@ def search_all(query, max_results=2): + """Search across all domains for comprehensive results""" all_results = {} for domain in AVAILABLE_DOMAINS: @@ -201,6 +213,7 @@ def _load_decision_csv(csv_type): + """Load a decision CSV and return as dict keyed by primary column.""" config = DECISION_CSV_CONFIG.get(csv_type) if not config: return {} @@ -214,6 +227,10 @@ def get_layout_for_goal(goal, previous_emotion=None): + """ + Get layout recommendation based on slide goal. + Uses slide-layout-logic.csv for decision. + """ layouts = _load_decision_csv("layout-logic") row = layouts.get(goal, layouts.get("features", {})) @@ -228,6 +245,10 @@ def get_typography_for_slide(slide_type, has_metrics=False, has_quote=False): + """ + Get typography recommendation based on slide content. + Uses slide-typography.csv for decision. + """ typography = _load_decision_csv("typography") if has_metrics: @@ -260,16 +281,33 @@ def get_color_for_emotion(emotion): + """ + Get color treatment based on emotional beat. + Uses slide-color-logic.csv for decision. + """ colors = _load_decision_csv("color-logic") return colors.get(emotion, colors.get("clarity", {})) def get_background_config(slide_type): + """ + Get background image configuration. + Uses slide-backgrounds.csv for decision. + """ backgrounds = _load_decision_csv("backgrounds") return backgrounds.get(slide_type, {}) def should_use_full_bleed(slide_index, total_slides, emotion): + """ + Determine if slide should use full-bleed background. + Premium decks use 2-3 full-bleed slides strategically. + + Rules: + 1. Never consecutive full-bleed + 2. One in first third, one in middle, one at end + 3. Reserved for high-emotion beats (hope, urgency, fear) + """ high_emotion_beats = ["hope", "urgency", "fear", "curiosity"] if emotion not in high_emotion_beats: @@ -285,6 +323,10 @@ def calculate_pattern_break(slide_index, total_slides, previous_emotion=None): + """ + Determine if this slide should break the visual pattern. + Used for emotional contrast (Duarte Sparkline technique). + """ # Pattern breaks at strategic positions if total_slides < 5: return False @@ -308,6 +350,18 @@ def search_with_context(query, slide_position=1, total_slides=9, previous_emotion=None): + """ + Enhanced search that considers deck context. + + Args: + query: Search query + slide_position: Current slide index (1-based) + total_slides: Total slides in deck + previous_emotion: Emotion of previous slide (for contrast) + + Returns: + Search results enriched with contextual recommendations + """ # Get base results from existing BM25 search base_results = search_all(query, max_results=2) @@ -396,4 +450,4 @@ "query": query, "context": context, "base_results": base_results, - }+ }
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/slide_search_core.py
Add docstrings following best practices
#!/usr/bin/env python3 import csv, os, json BASE = os.path.dirname(os.path.abspath(__file__)) # ─── Color derivation helpers ──────────────────────────────────────────────── def h2r(h): h = h.lstrip("#") return tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) def r2h(r, g, b): return f"#{max(0,min(255,int(r))):02X}{max(0,min(255,int(g))):02X}{max(0,min(255,int(b))):02X}" def lum(h): r, g, b = [x/255.0 for x in h2r(h)] r, g, b = [(x/12.92 if x<=0.03928 else ((x+0.055)/1.055)**2.4) for x in (r, g, b)] return 0.2126*r + 0.7152*g + 0.0722*b def is_dark(bg): return lum(bg) < 0.18 def on_color(bg): return "#FFFFFF" if lum(bg) < 0.4 else "#0F172A" def blend(a, b, f=0.15): ra, ga, ba = h2r(a) rb, gb, bb = h2r(b) return r2h(ra+(rb-ra)*f, ga+(gb-ga)*f, ba+(bb-ba)*f) def shift(h, n): r, g, b = h2r(h) return r2h(r+n, g+n, b+n) def derive_row(pt, pri, sec, acc, bg, notes=""): dark = is_dark(bg) fg = "#FFFFFF" if dark else "#0F172A" on_pri = on_color(pri) on_sec = on_color(sec) on_acc = on_color(acc) card = shift(bg, 10) if dark else "#FFFFFF" card_fg = "#FFFFFF" if dark else "#0F172A" muted = blend(bg, pri, 0.08) if dark else blend("#FFFFFF", pri, 0.06) muted_fg = "#94A3B8" if dark else "#64748B" border = f"rgba(255,255,255,0.08)" if dark else blend("#FFFFFF", pri, 0.12) destr = "#DC2626" on_destr = "#FFFFFF" ring = pri return [pt, pri, on_pri, sec, on_sec, acc, on_acc, bg, fg, card, card_fg, muted, muted_fg, border, destr, on_destr, ring, notes] # ─── Rename maps ───────────────────────────────────────────────────────────── COLOR_RENAMES = { "Quantum Computing": "Quantum Computing Interface", "Biohacking / Longevity": "Biohacking / Longevity App", "Autonomous Systems": "Autonomous Drone Fleet Manager", "Generative AI Art": "Generative Art Platform", "Spatial / Vision OS": "Spatial Computing OS / App", "Climate Tech": "Sustainable Energy / Climate Tech", } UI_RENAMES = { "Architecture/Interior": "Architecture / Interior", "Autonomous Drone Fleet": "Autonomous Drone Fleet Manager", "B2B SaaS Enterprise": "B2B Service", "Biohacking/Longevity App": "Biohacking / Longevity App", "Biotech/Life Sciences": "Biotech / Life Sciences", "Developer Tool/IDE": "Developer Tool / IDE", "Education": "Educational App", "Fintech (Banking)": "Fintech/Crypto", "Government/Public": "Government/Public Service", "Home Services": "Home Services (Plumber/Electrician)", "Micro-Credentials/Badges": "Micro-Credentials/Badges Platform", "Music/Entertainment": "Music Streaming", "Quantum Computing": "Quantum Computing Interface", "Real Estate": "Real Estate/Property", "Remote Work/Collaboration": "Remote Work/Collaboration Tool", "Restaurant/Food": "Restaurant/Food Service", "SaaS Dashboard": "Analytics Dashboard", "Space Tech/Aerospace": "Space Tech / Aerospace", "Spatial Computing OS": "Spatial Computing OS / App", "Startup Landing": "Micro SaaS", "Sustainable Energy/Climate": "Sustainable Energy / Climate Tech", "Travel/Tourism": "Travel/Tourism Agency", "Wellness/Mental Health": "Mental Health App", } REMOVE_TYPES = { "Service Landing Page", "Sustainability/ESG Platform", "Cleaning Service", "Coffee Shop", "Consulting Firm", "Conference/Webinar Platform", } # ─── New color definitions: (primary, secondary, accent, bg, notes) ────────── # Grouped by category for clarity. Each tuple generates a full 16-token row. NEW_COLORS = { # ── Old #97-#116 that never got colors ── "Todo & Task Manager": ("#2563EB","#3B82F6","#059669","#F8FAFC","Functional blue + progress green"), "Personal Finance Tracker": ("#1E40AF","#3B82F6","#059669","#0F172A","Trust blue + profit green on dark"), "Chat & Messaging App": ("#2563EB","#6366F1","#059669","#FFFFFF","Messenger blue + online green"), "Notes & Writing App": ("#78716C","#A8A29E","#D97706","#FFFBEB","Warm ink + amber accent on cream"), "Habit Tracker": ("#D97706","#F59E0B","#059669","#FFFBEB","Streak amber + habit green"), "Food Delivery / On-Demand": ("#EA580C","#F97316","#2563EB","#FFF7ED","Appetizing orange + trust blue"), "Ride Hailing / Transportation":("#1E293B","#334155","#2563EB","#0F172A","Map dark + route blue"), "Recipe & Cooking App": ("#9A3412","#C2410C","#059669","#FFFBEB","Warm terracotta + fresh green"), "Meditation & Mindfulness": ("#7C3AED","#8B5CF6","#059669","#FAF5FF","Calm lavender + mindful green"), "Weather App": ("#0284C7","#0EA5E9","#F59E0B","#F0F9FF","Sky blue + sun amber"), "Diary & Journal App": ("#92400E","#A16207","#6366F1","#FFFBEB","Warm journal brown + ink violet"), "CRM & Client Management": ("#2563EB","#3B82F6","#059669","#F8FAFC","Professional blue + deal green"), "Inventory & Stock Management":("#334155","#475569","#059669","#F8FAFC","Industrial slate + stock green"), "Flashcard & Study Tool": ("#7C3AED","#8B5CF6","#059669","#FAF5FF","Study purple + correct green"), "Booking & Appointment App": ("#0284C7","#0EA5E9","#059669","#F0F9FF","Calendar blue + available green"), "Invoice & Billing Tool": ("#1E3A5F","#2563EB","#059669","#F8FAFC","Navy professional + paid green"), "Grocery & Shopping List": ("#059669","#10B981","#D97706","#ECFDF5","Fresh green + food amber"), "Timer & Pomodoro": ("#DC2626","#EF4444","#059669","#0F172A","Focus red on dark + break green"), "Parenting & Baby Tracker": ("#EC4899","#F472B6","#0284C7","#FDF2F8","Soft pink + trust blue"), "Scanner & Document Manager": ("#1E293B","#334155","#2563EB","#F8FAFC","Document grey + scan blue"), # ── A. Utility / Productivity ── "Calendar & Scheduling App": ("#2563EB","#3B82F6","#059669","#F8FAFC","Calendar blue + event green"), "Password Manager": ("#1E3A5F","#334155","#059669","#0F172A","Vault dark blue + secure green"), "Expense Splitter / Bill Split":("#059669","#10B981","#DC2626","#F8FAFC","Balance green + owe red"), "Voice Recorder & Memo": ("#DC2626","#EF4444","#2563EB","#FFFFFF","Recording red + waveform blue"), "Bookmark & Read-Later": ("#D97706","#F59E0B","#2563EB","#FFFBEB","Warm amber + link blue"), "Translator App": ("#2563EB","#0891B2","#EA580C","#F8FAFC","Global blue + teal + accent orange"), "Calculator & Unit Converter": ("#EA580C","#F97316","#2563EB","#1C1917","Operation orange on dark"), "Alarm & World Clock": ("#D97706","#F59E0B","#6366F1","#0F172A","Time amber + night indigo on dark"), "File Manager & Transfer": ("#2563EB","#3B82F6","#D97706","#F8FAFC","Folder blue + file amber"), "Email Client": ("#2563EB","#3B82F6","#DC2626","#FFFFFF","Inbox blue + priority red"), # ── B. Games ── "Casual Puzzle Game": ("#EC4899","#8B5CF6","#F59E0B","#FDF2F8","Cheerful pink + reward gold"), "Trivia & Quiz Game": ("#2563EB","#7C3AED","#F59E0B","#EFF6FF","Quiz blue + gold leaderboard"), "Card & Board Game": ("#15803D","#166534","#D97706","#0F172A","Felt green + gold on dark"), "Idle & Clicker Game": ("#D97706","#F59E0B","#7C3AED","#FFFBEB","Coin gold + prestige purple"), "Word & Crossword Game": ("#15803D","#059669","#D97706","#FFFFFF","Word green + letter amber"), "Arcade & Retro Game": ("#DC2626","#2563EB","#22C55E","#0F172A","Neon red+blue on dark + score green"), # ── C. Creator Tools ── "Photo Editor & Filters": ("#7C3AED","#6366F1","#0891B2","#0F172A","Editor violet + filter cyan on dark"), "Short Video Editor": ("#EC4899","#DB2777","#2563EB","#0F172A","Video pink on dark + timeline blue"), "Drawing & Sketching Canvas": ("#7C3AED","#8B5CF6","#0891B2","#1C1917","Canvas purple + tool teal on dark"), "Music Creation & Beat Maker": ("#7C3AED","#6366F1","#22C55E","#0F172A","Studio purple + waveform green on dark"), "Meme & Sticker Maker": ("#EC4899","#F59E0B","#2563EB","#FFFFFF","Viral pink + comedy yellow + share blue"), "AI Photo & Avatar Generator": ("#7C3AED","#6366F1","#EC4899","#FAF5FF","AI purple + generation pink"), "Link-in-Bio Page Builder": ("#2563EB","#7C3AED","#EC4899","#FFFFFF","Brand blue + creator purple"), # ── D. Personal Life ── "Wardrobe & Outfit Planner": ("#BE185D","#EC4899","#D97706","#FDF2F8","Fashion rose + gold accent"), "Plant Care Tracker": ("#15803D","#059669","#D97706","#F0FDF4","Nature green + sun yellow"), "Book & Reading Tracker": ("#78716C","#92400E","#D97706","#FFFBEB","Book brown + page amber"), "Couple & Relationship App": ("#BE185D","#EC4899","#DC2626","#FDF2F8","Romance rose + love red"), "Family Calendar & Chores": ("#2563EB","#059669","#D97706","#F8FAFC","Family blue + chore green"), "Mood Tracker": ("#7C3AED","#6366F1","#D97706","#FAF5FF","Mood purple + insight amber"), "Gift & Wishlist": ("#DC2626","#D97706","#EC4899","#FFF1F2","Gift red + gold + surprise pink"), # ── E. Health ── "Running & Cycling GPS": ("#EA580C","#F97316","#059669","#0F172A","Energetic orange + pace green on dark"), "Yoga & Stretching Guide": ("#6B7280","#78716C","#0891B2","#F5F5F0","Sage neutral + calm teal"), "Sleep Tracker": ("#4338CA","#6366F1","#7C3AED","#0F172A","Night indigo + dream violet on dark"), "Calorie & Nutrition Counter": ("#059669","#10B981","#EA580C","#ECFDF5","Healthy green + macro orange"), "Period & Cycle Tracker": ("#BE185D","#EC4899","#7C3AED","#FDF2F8","Blush rose + fertility lavender"), "Medication & Pill Reminder": ("#0284C7","#0891B2","#DC2626","#F0F9FF","Medical blue + alert red"), "Water & Hydration Reminder": ("#0284C7","#06B6D4","#0891B2","#F0F9FF","Refreshing blue + water cyan"), "Fasting & Intermittent Timer":("#6366F1","#4338CA","#059669","#0F172A","Fasting indigo on dark + eating green"), # ── F. Social ── "Anonymous Community / Confession":("#475569","#334155","#0891B2","#0F172A","Protective grey + subtle teal on dark"), "Local Events & Discovery": ("#EA580C","#F97316","#2563EB","#FFF7ED","Event orange + map blue"), "Study Together / Virtual Coworking":("#2563EB","#3B82F6","#059669","#F8FAFC","Focus blue + session green"), # ── G. Education ── "Coding Challenge & Practice": ("#22C55E","#059669","#D97706","#0F172A","Code green + difficulty amber on dark"), "Kids Learning (ABC & Math)": ("#2563EB","#F59E0B","#EC4899","#EFF6FF","Learning blue + play yellow + fun pink"), "Music Instrument Learning": ("#DC2626","#9A3412","#D97706","#FFFBEB","Musical red + warm amber"), # ── H. Transport ── "Parking Finder": ("#2563EB","#059669","#DC2626","#F0F9FF","Available blue/green + occupied red"), "Public Transit Guide": ("#2563EB","#0891B2","#EA580C","#F8FAFC","Transit blue + line colors"), "Road Trip Planner": ("#EA580C","#0891B2","#D97706","#FFF7ED","Adventure orange + map teal"), # ── I. Safety & Lifestyle ── "VPN & Privacy Tool": ("#1E3A5F","#334155","#22C55E","#0F172A","Shield dark + connected green"), "Emergency SOS & Safety": ("#DC2626","#EF4444","#2563EB","#FFF1F2","Alert red + safety blue"), "Wallpaper & Theme App": ("#7C3AED","#EC4899","#2563EB","#FAF5FF","Aesthetic purple + trending pink"), "White Noise & Ambient Sound": ("#475569","#334155","#4338CA","#0F172A","Ambient grey + deep indigo on dark"), "Home Decoration & Interior Design":("#78716C","#A8A29E","#D97706","#FAF5F2","Interior warm grey + gold accent"), } # ─── 1. REBUILD colors.csv ─────────────────────────────────────────────────── def rebuild_colors(): src = os.path.join(BASE, "colors.csv") with open(src, newline="", encoding="utf-8") as f: reader = csv.DictReader(f) headers = reader.fieldnames existing = list(reader) # Build lookup: Product Type -> row data color_map = {} for row in existing: pt = row.get("Product Type", "").strip() if not pt: continue # Remove deleted types if pt in REMOVE_TYPES: print(f" [colors] REMOVE: {pt}") continue # Rename mismatched types if pt in COLOR_RENAMES: new_name = COLOR_RENAMES[pt] print(f" [colors] RENAME: {pt} → {new_name}") row["Product Type"] = new_name pt = new_name color_map[pt] = row # Read products.csv to get the correct order with open(os.path.join(BASE, "products.csv"), newline="", encoding="utf-8") as f: products = list(csv.DictReader(f)) # Build final rows in products.csv order final_rows = [] added = 0 for i, prod in enumerate(products, 1): pt = prod["Product Type"] if pt in color_map: row = color_map[pt] row["No"] = str(i) final_rows.append(row) elif pt in NEW_COLORS: pri, sec, acc, bg, notes = NEW_COLORS[pt] new_row = derive_row(pt, pri, sec, acc, bg, notes) d = dict(zip(headers, [str(i)] + new_row)) final_rows.append(d) added += 1 else: print(f" [colors] WARNING: No color data for '{pt}' - using defaults") new_row = derive_row(pt, "#2563EB", "#3B82F6", "#059669", "#F8FAFC", "Auto-generated default") d = dict(zip(headers, [str(i)] + new_row)) final_rows.append(d) added += 1 # Write with open(src, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=headers) writer.writeheader() writer.writerows(final_rows) product_count = len(products) print(f"\n ✅ colors.csv: {len(final_rows)} rows ({product_count} products)") print(f" Added: {added} new color rows") # ─── 2. REBUILD ui-reasoning.csv ───────────────────────────────────────────── def derive_ui_reasoning(prod): pt = prod["Product Type"] style = prod.get("Primary Style Recommendation", "") landing = prod.get("Landing Page Pattern", "") color_focus = prod.get("Color Palette Focus", "") considerations = prod.get("Key Considerations", "") keywords = prod.get("Keywords", "") # Typography mood derived from style typo_map = { "Minimalism": "Professional + Clean hierarchy", "Glassmorphism": "Modern + Clear hierarchy", "Brutalism": "Bold + Oversized + Monospace", "Claymorphism": "Playful + Rounded + Friendly", "Dark Mode": "High contrast + Light on dark", "Neumorphism": "Subtle + Soft + Monochromatic", "Flat Design": "Bold + Clean + Sans-serif", "Vibrant": "Energetic + Bold + Large", "Aurora": "Elegant + Gradient-friendly", "AI-Native": "Conversational + Minimal chrome", "Organic": "Warm + Humanist + Natural", "Motion": "Dynamic + Hierarchy-shifting", "Accessible": "Large + High contrast + Clear", "Soft UI": "Modern + Accessible + Balanced", "Trust": "Professional + Serif accents", "Swiss": "Grid-based + Mathematical + Helvetica", "3D": "Immersive + Spatial + Variable", "Retro": "Nostalgic + Monospace + Neon", "Cyberpunk": "Terminal + Monospace + Neon", "Pixel": "Retro + Blocky + 8-bit", } typo_mood = "Professional + Clear hierarchy" for key, val in typo_map.items(): if key.lower() in style.lower(): typo_mood = val break # Key effects from style eff_map = { "Glassmorphism": "Backdrop blur (10-20px) + Translucent overlays", "Neumorphism": "Dual shadows (light+dark) + Soft press 150ms", "Claymorphism": "Multi-layer shadows + Spring bounce + Soft press 200ms", "Brutalism": "No transitions + Hard borders + Instant feedback", "Dark Mode": "Subtle glow + Neon accents + High contrast", "Flat Design": "Color shift hover + Fast 150ms transitions + No shadows", "Minimalism": "Subtle hover 200ms + Smooth transitions + Clean", "Motion-Driven": "Scroll animations + Parallax + Page transitions", "Micro-interactions": "Haptic feedback + Small 50-100ms animations", "Vibrant": "Large section gaps 48px+ + Color shift hover + Scroll-snap", "Aurora": "Flowing gradients 8-12s + Color morphing", "AI-Native": "Typing indicator + Streaming text + Context reveal", "Organic": "Rounded 16-24px + Natural shadows + Flowing SVG", "Soft UI": "Improved shadows + Modern 200-300ms + Focus visible", "3D": "WebGL/Three.js + Parallax 3-5 layers + Physics 300-400ms", "Trust": "Clear focus rings + Badge hover + Metric pulse", "Accessible": "Focus rings 3-4px + ARIA + Reduced motion", } key_effects = "Subtle hover (200ms) + Smooth transitions" for key, val in eff_map.items(): if key.lower() in style.lower(): key_effects = val break # Decision rules rules = {} if "dark" in style.lower() or "oled" in style.lower(): rules["if_light_mode_needed"] = "provide-theme-toggle" if "glass" in style.lower(): rules["if_low_performance"] = "fallback-to-flat" if "conversion" in landing.lower(): rules["if_conversion_focused"] = "add-urgency-colors" if "social" in landing.lower(): rules["if_trust_needed"] = "add-testimonials" if "data" in keywords.lower() or "dashboard" in keywords.lower(): rules["if_data_heavy"] = "prioritize-data-density" if not rules: rules["if_ux_focused"] = "prioritize-clarity" rules["if_mobile"] = "optimize-touch-targets" # Anti-patterns anti_patterns = [] if "minimalism" in style.lower() or "minimal" in style.lower(): anti_patterns.append("Excessive decoration") if "dark" in style.lower(): anti_patterns.append("Pure white backgrounds") if "flat" in style.lower(): anti_patterns.append("Complex shadows + 3D effects") if "vibrant" in style.lower(): anti_patterns.append("Muted colors + Low energy") if "accessible" in style.lower(): anti_patterns.append("Color-only indicators") if not anti_patterns: anti_patterns = ["Inconsistent styling", "Poor contrast ratios"] anti_str = " + ".join(anti_patterns[:2]) return { "UI_Category": pt, "Recommended_Pattern": landing, "Style_Priority": style, "Color_Mood": color_focus, "Typography_Mood": typo_mood, "Key_Effects": key_effects, "Decision_Rules": json.dumps(rules), "Anti_Patterns": anti_str, "Severity": "HIGH" } def rebuild_ui_reasoning(): src = os.path.join(BASE, "ui-reasoning.csv") with open(src, newline="", encoding="utf-8") as f: reader = csv.DictReader(f) headers = reader.fieldnames existing = list(reader) # Build lookup ui_map = {} for row in existing: cat = row.get("UI_Category", "").strip() if not cat: continue if cat in REMOVE_TYPES: print(f" [ui-reason] REMOVE: {cat}") continue if cat in UI_RENAMES: new_name = UI_RENAMES[cat] print(f" [ui-reason] RENAME: {cat} → {new_name}") row["UI_Category"] = new_name cat = new_name ui_map[cat] = row with open(os.path.join(BASE, "products.csv"), newline="", encoding="utf-8") as f: products = list(csv.DictReader(f)) final_rows = [] added = 0 for i, prod in enumerate(products, 1): pt = prod["Product Type"] if pt in ui_map: row = ui_map[pt] row["No"] = str(i) final_rows.append(row) else: row = derive_ui_reasoning(prod) row["No"] = str(i) final_rows.append(row) added += 1 with open(src, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=headers) writer.writeheader() writer.writerows(final_rows) print(f"\n ✅ ui-reasoning.csv: {len(final_rows)} rows") print(f" Added: {added} new reasoning rows") # ─── MAIN ──────────────────────────────────────────────────────────────────── if __name__ == "__main__": print("=== Rebuilding colors.csv ===") rebuild_colors() print("\n=== Rebuilding ui-reasoning.csv ===") rebuild_ui_reasoning() print("\n🎉 Done!")
--- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3 +""" +Sync colors.csv and ui-reasoning.csv with the updated products.csv (161 entries). +- Remove deleted product types +- Rename mismatched entries +- Add new entries for missing product types +- Keep colors.csv aligned 1:1 with products.csv +- Renumber everything +""" import csv, os, json BASE = os.path.dirname(os.path.abspath(__file__)) @@ -32,6 +40,7 @@ return r2h(r+n, g+n, b+n) def derive_row(pt, pri, sec, acc, bg, notes=""): + """Generate full 16-token color row from 4 base colors.""" dark = is_dark(bg) fg = "#FFFFFF" if dark else "#0F172A" on_pri = on_color(pri) @@ -239,6 +248,7 @@ # ─── 2. REBUILD ui-reasoning.csv ───────────────────────────────────────────── def derive_ui_reasoning(prod): + """Generate ui-reasoning row from products.csv row.""" pt = prod["Product Type"] style = prod.get("Primary Style Recommendation", "") landing = prod.get("Landing Page Pattern", "") @@ -401,4 +411,4 @@ rebuild_colors() print("\n=== Rebuilding ui-reasoning.csv ===") rebuild_ui_reasoning() - print("\n🎉 Done!")+ print("\n🎉 Done!")
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/src/ui-ux-pro-max/data/_sync_all.py
Improve documentation using docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import json import os import re import sys import time from pathlib import Path from datetime import datetime def load_env(): env_paths = [ Path(__file__).parent.parent.parent / ".env", Path.home() / ".claude" / "skills" / ".env", Path.home() / ".claude" / ".env" ] for env_path in env_paths: if env_path.exists(): with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) if key not in os.environ: os.environ[key] = value.strip('"\'') load_env() try: from google import genai from google.genai import types except ImportError: print("Error: google-genai package not installed.") print("Install with: pip install google-genai") sys.exit(1) # ============ CONFIGURATION ============ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") MODEL = "gemini-3.1-pro-preview" # Icon styles with SVG-specific instructions ICON_STYLES = { "outlined": "outlined stroke icons, 2px stroke width, no fill, clean open paths", "filled": "solid filled icons, no stroke, flat color fills, bold shapes", "duotone": "duotone style with primary color at full opacity and secondary color at 30% opacity, layered shapes", "thin": "thin line icons, 1px or 1.5px stroke width, delicate minimalist lines", "bold": "bold thick line icons, 3px stroke width, heavy weight, impactful", "rounded": "rounded icons with round line caps and joins, soft corners, friendly feel", "sharp": "sharp angular icons, square line caps and mitered joins, precise edges", "flat": "flat design icons, solid fills, no gradients or shadows, geometric simplicity", "gradient": "linear or radial gradient fills, modern vibrant color transitions", "glassmorphism": "glassmorphism style with semi-transparent fills, blur backdrop effect simulation, frosted glass", "pixel": "pixel art style icons on a grid, retro 8-bit aesthetic, crisp edges", "hand-drawn": "hand-drawn sketch style, slightly irregular strokes, organic feel, imperfect lines", "isometric": "isometric 3D projection, 30-degree angles, dimensional depth", "glyph": "simple glyph style, single solid shape, minimal detail, pictogram", "animated-ready": "animated-ready SVG with named groups and IDs for CSS/JS animation targets", } ICON_CATEGORIES = { "navigation": "arrows, menus, hamburger, chevrons, home, back, forward, breadcrumb", "action": "edit, delete, save, download, upload, share, copy, paste, print, search", "communication": "email, chat, phone, video call, notification, bell, message bubble", "media": "play, pause, stop, skip, volume, microphone, camera, image, gallery", "file": "document, folder, archive, attachment, cloud, database, storage", "user": "person, group, avatar, profile, settings, lock, key, shield", "commerce": "cart, bag, wallet, credit card, receipt, tag, gift, store", "data": "chart, graph, analytics, dashboard, table, filter, sort, calendar", "development": "code, terminal, bug, git, API, server, database, deploy", "social": "heart, star, thumbs up, bookmark, flag, trophy, badge, crown", "weather": "sun, moon, cloud, rain, snow, wind, thunder, temperature", "map": "pin, location, compass, globe, route, directions, map marker", } # SVG generation prompt template SVG_PROMPT_TEMPLATE = """Generate a clean, production-ready SVG icon. Requirements: - Output ONLY valid SVG code, nothing else - ViewBox: "0 0 {viewbox} {viewbox}" - Use currentColor for strokes/fills (inherits CSS color) - No embedded fonts or text elements unless specifically requested - No raster images or external references - Optimized paths with minimal nodes - Accessible: include <title> element with icon description {style_instructions} {color_instructions} {size_instructions} Icon to generate: {prompt} Output the SVG code only, wrapped in ```svg``` code block.""" SVG_BATCH_PROMPT_TEMPLATE = """Generate {count} distinct SVG icon variations for: {prompt} Requirements for EACH icon: - Output ONLY valid SVG code - ViewBox: "0 0 {viewbox} {viewbox}" - Use currentColor for strokes/fills (inherits CSS color) - No embedded fonts, raster images, or external references - Optimized paths with minimal nodes - Include <title> element with icon description {style_instructions} {color_instructions} Generate {count} different visual interpretations. Output each SVG in a separate ```svg``` code block. Label each variation (e.g., "Variation 1: [brief description]").""" def extract_svgs(text): svgs = [] # Try ```svg code blocks first pattern = r'```svg\s*\n(.*?)```' matches = re.findall(pattern, text, re.DOTALL) if matches: svgs.extend(matches) # Fallback: try ```xml code blocks if not svgs: pattern = r'```xml\s*\n(.*?)```' matches = re.findall(pattern, text, re.DOTALL) svgs.extend(matches) # Fallback: try bare <svg> tags if not svgs: pattern = r'(<svg[^>]*>.*?</svg>)' matches = re.findall(pattern, text, re.DOTALL) svgs.extend(matches) # Clean up extracted SVGs cleaned = [] for svg in svgs: svg = svg.strip() if not svg.startswith('<svg'): # Try to find <svg> within the extracted text match = re.search(r'(<svg[^>]*>.*?</svg>)', svg, re.DOTALL) if match: svg = match.group(1) else: continue cleaned.append(svg) return cleaned def apply_color(svg_code, color): if color: # Replace currentColor with the specified color svg_code = svg_code.replace('currentColor', color) # If no currentColor was present, add fill/stroke color if color not in svg_code: svg_code = svg_code.replace('<svg', f'<svg color="{color}"', 1) return svg_code def apply_viewbox_size(svg_code, size): if size: # Update width/height attributes if present svg_code = re.sub(r'width="[^"]*"', f'width="{size}"', svg_code) svg_code = re.sub(r'height="[^"]*"', f'height="{size}"', svg_code) # Add width/height if not present if 'width=' not in svg_code: svg_code = svg_code.replace('<svg', f'<svg width="{size}" height="{size}"', 1) return svg_code def generate_icon(prompt, style=None, category=None, name=None, color=None, size=24, output_path=None, viewbox=24): if not GEMINI_API_KEY: print("Error: GEMINI_API_KEY not set") print("Set it with: export GEMINI_API_KEY='your-key'") return None client = genai.Client(api_key=GEMINI_API_KEY) # Build style instructions style_instructions = "" if style and style in ICON_STYLES: style_instructions = f"- Style: {ICON_STYLES[style]}" # Build color instructions color_instructions = "- Use currentColor for all strokes and fills" if color: color_instructions = f"- Use color: {color} for primary elements, currentColor for secondary" # Build size instructions size_instructions = f"- Design for {size}px display size, optimize detail level accordingly" # Build final prompt icon_prompt = prompt if category and category in ICON_CATEGORIES: icon_prompt = f"{prompt} (category: {ICON_CATEGORIES[category]})" if name: icon_prompt = f"'{name}' icon: {icon_prompt}" full_prompt = SVG_PROMPT_TEMPLATE.format( prompt=icon_prompt, viewbox=viewbox, style_instructions=style_instructions, color_instructions=color_instructions, size_instructions=size_instructions ) print(f"Generating icon with {MODEL}...") print(f"Prompt: {prompt}") if style: print(f"Style: {style}") print() try: response = client.models.generate_content( model=MODEL, contents=full_prompt, config=types.GenerateContentConfig( temperature=0.7, max_output_tokens=4096, ) ) # Extract SVG from response response_text = response.text if hasattr(response, 'text') else "" if not response_text: for part in response.candidates[0].content.parts: if hasattr(part, 'text') and part.text: response_text += part.text svgs = extract_svgs(response_text) if not svgs: print("No valid SVG generated. Model response:") print(response_text[:500]) return None svg_code = svgs[0] # Apply color if specified svg_code = apply_color(svg_code, color) # Apply size svg_code = apply_viewbox_size(svg_code, size) # Determine output path if output_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") slug = name or prompt.split()[0] if prompt else "icon" slug = re.sub(r'[^a-zA-Z0-9_-]', '_', slug.lower()) style_suffix = f"_{style}" if style else "" output_path = f"{slug}{style_suffix}_{timestamp}.svg" # Save SVG with open(output_path, "w", encoding="utf-8") as f: f.write(svg_code) print(f"Icon saved to: {output_path}") return output_path except Exception as e: print(f"Error generating icon: {e}") return None def generate_batch(prompt, count, output_dir, style=None, color=None, viewbox=24, name=None): if not GEMINI_API_KEY: print("Error: GEMINI_API_KEY not set") return [] client = genai.Client(api_key=GEMINI_API_KEY) os.makedirs(output_dir, exist_ok=True) # Build instructions style_instructions = "" if style and style in ICON_STYLES: style_instructions = f"- Style: {ICON_STYLES[style]}" color_instructions = "- Use currentColor for all strokes and fills" if color: color_instructions = f"- Use color: {color} for primary elements" full_prompt = SVG_BATCH_PROMPT_TEMPLATE.format( prompt=prompt, count=count, viewbox=viewbox, style_instructions=style_instructions, color_instructions=color_instructions ) print(f"\n{'='*60}") print(f" BATCH ICON GENERATION") print(f" Model: {MODEL}") print(f" Prompt: {prompt}") print(f" Variants: {count}") print(f" Output: {output_dir}") print(f"{'='*60}\n") try: response = client.models.generate_content( model=MODEL, contents=full_prompt, config=types.GenerateContentConfig( temperature=0.9, max_output_tokens=16384, ) ) response_text = response.text if hasattr(response, 'text') else "" if not response_text: for part in response.candidates[0].content.parts: if hasattr(part, 'text') and part.text: response_text += part.text svgs = extract_svgs(response_text) if not svgs: print("No valid SVGs generated.") print(response_text[:500]) return [] results = [] slug = name or re.sub(r'[^a-zA-Z0-9_-]', '_', prompt.split()[0].lower()) style_suffix = f"_{style}" if style else "" for i, svg_code in enumerate(svgs[:count]): svg_code = apply_color(svg_code, color) filename = f"{slug}{style_suffix}_{i+1:02d}.svg" filepath = os.path.join(output_dir, filename) with open(filepath, "w", encoding="utf-8") as f: f.write(svg_code) results.append(filepath) print(f" [{i+1}/{len(svgs[:count])}] Saved: {filename}") print(f"\n{'='*60}") print(f" BATCH COMPLETE: {len(results)}/{count} icons generated") print(f"{'='*60}\n") return results except Exception as e: print(f"Error generating icons: {e}") return [] def generate_sizes(prompt, sizes, style=None, color=None, output_dir=None, name=None): if output_dir is None: output_dir = "." os.makedirs(output_dir, exist_ok=True) results = [] slug = name or re.sub(r'[^a-zA-Z0-9_-]', '_', prompt.split()[0].lower()) style_suffix = f"_{style}" if style else "" for size in sizes: print(f"Generating {size}px variant...") filename = f"{slug}{style_suffix}_{size}px.svg" filepath = os.path.join(output_dir, filename) result = generate_icon( prompt=prompt, style=style, color=color, size=size, output_path=filepath, viewbox=size ) if result: results.append(result) time.sleep(1) return results def main(): parser = argparse.ArgumentParser( description="Generate SVG icons using Gemini 3.1 Pro Preview" ) parser.add_argument("--prompt", "-p", type=str, help="Icon description") parser.add_argument("--name", "-n", type=str, help="Icon name (for filename)") parser.add_argument("--style", "-s", choices=list(ICON_STYLES.keys()), help="Icon style") parser.add_argument("--category", "-c", choices=list(ICON_CATEGORIES.keys()), help="Icon category for context") parser.add_argument("--color", type=str, help="Primary color (hex, e.g. #6366F1). Default: currentColor") parser.add_argument("--size", type=int, default=24, help="Icon size in px (default: 24)") parser.add_argument("--viewbox", type=int, default=24, help="SVG viewBox size (default: 24)") parser.add_argument("--output", "-o", type=str, help="Output file path") parser.add_argument("--output-dir", type=str, help="Output directory for batch") parser.add_argument("--batch", type=int, help="Number of icon variants to generate") parser.add_argument("--sizes", type=str, help="Comma-separated sizes (e.g. '16,24,32,48')") parser.add_argument("--list-styles", action="store_true", help="List available icon styles") parser.add_argument("--list-categories", action="store_true", help="List available icon categories") args = parser.parse_args() if args.list_styles: print("Available icon styles:") for style, desc in ICON_STYLES.items(): print(f" {style}: {desc[:70]}...") return if args.list_categories: print("Available icon categories:") for cat, desc in ICON_CATEGORIES.items(): print(f" {cat}: {desc}") return if not args.prompt and not args.name: parser.error("Either --prompt or --name is required") prompt = args.prompt or args.name # Multi-size mode if args.sizes: sizes = [int(s.strip()) for s in args.sizes.split(",")] generate_sizes( prompt=prompt, sizes=sizes, style=args.style, color=args.color, output_dir=args.output_dir or "./icons", name=args.name ) # Batch mode elif args.batch: output_dir = args.output_dir or "./icons" generate_batch( prompt=prompt, count=args.batch, output_dir=output_dir, style=args.style, color=args.color, viewbox=args.viewbox, name=args.name ) # Single icon else: generate_icon( prompt=prompt, style=args.style, category=args.category, name=args.name, color=args.color, size=args.size, output_path=args.output, viewbox=args.viewbox ) if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,18 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Icon Generation Script using Gemini 3.1 Pro Preview API +Generates SVG icons via text generation (SVG is XML text format) + +Model: gemini-3.1-pro-preview - best thinking, token efficiency, factual consistency + +Usage: + python generate.py --prompt "settings gear icon" --style outlined + python generate.py --prompt "shopping cart" --style filled --color "#6366F1" + python generate.py --name "dashboard" --category navigation --style duotone + python generate.py --prompt "cloud upload" --batch 4 --output-dir ./icons + python generate.py --prompt "user profile" --sizes "16,24,32,48" +""" import argparse import json @@ -12,6 +25,7 @@ def load_env(): + """Load .env files in priority order""" env_paths = [ Path(__file__).parent.parent.parent / ".env", Path.home() / ".claude" / "skills" / ".env", @@ -112,6 +126,7 @@ def extract_svgs(text): + """Extract SVG code blocks from model response""" svgs = [] # Try ```svg code blocks first @@ -149,6 +164,7 @@ def apply_color(svg_code, color): + """Replace currentColor with specific color if provided""" if color: # Replace currentColor with the specified color svg_code = svg_code.replace('currentColor', color) @@ -159,6 +175,7 @@ def apply_viewbox_size(svg_code, size): + """Adjust SVG viewBox to target size""" if size: # Update width/height attributes if present svg_code = re.sub(r'width="[^"]*"', f'width="{size}"', svg_code) @@ -171,6 +188,7 @@ def generate_icon(prompt, style=None, category=None, name=None, color=None, size=24, output_path=None, viewbox=24): + """Generate a single SVG icon using Gemini 3.1 Pro Preview""" if not GEMINI_API_KEY: print("Error: GEMINI_API_KEY not set") @@ -267,6 +285,7 @@ def generate_batch(prompt, count, output_dir, style=None, color=None, viewbox=24, name=None): + """Generate multiple icon variations""" if not GEMINI_API_KEY: print("Error: GEMINI_API_KEY not set") @@ -350,6 +369,7 @@ def generate_sizes(prompt, sizes, style=None, color=None, output_dir=None, name=None): + """Generate same icon at multiple sizes""" if output_dir is None: output_dir = "." os.makedirs(output_dir, exist_ok=True) @@ -464,4 +484,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/icon/generate.py
Auto-generate documentation strings for this file
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import os import sys import time from pathlib import Path from datetime import datetime # Load environment variables def load_env(): env_paths = [ Path(__file__).parent.parent.parent / ".env", Path.home() / ".claude" / "skills" / ".env", Path.home() / ".claude" / ".env" ] for env_path in env_paths: if env_path.exists(): with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) if key not in os.environ: os.environ[key] = value.strip('"\'') load_env() try: from google import genai from google.genai import types except ImportError: print("Error: google-genai package not installed.") print("Install with: pip install google-genai") sys.exit(1) # ============ CONFIGURATION ============ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") # Gemini "Nano Banana" model configurations for image generation GEMINI_FLASH = "gemini-2.5-flash-image" # Nano Banana: fast, high-volume, low-latency GEMINI_PRO = "gemini-3-pro-image-preview" # Nano Banana Pro: professional quality, advanced reasoning # Supported aspect ratios ASPECT_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4"] DEFAULT_ASPECT_RATIO = "1:1" # Square is ideal for logos # Logo-specific prompt templates LOGO_PROMPT_TEMPLATE = """Generate a professional logo image: {prompt} Style requirements: - Clean vector-style illustration suitable for a logo - Simple, scalable design that works at any size - Clear silhouette and recognizable shape - Professional quality suitable for business use - Centered composition on plain white or transparent background - No text unless specifically requested - High contrast and clear edges - Square format, perfectly centered - Output as a clean, high-quality logo image """ STYLE_MODIFIERS = { "minimalist": "minimalist, simple geometric shapes, clean lines, lots of white space, single color or limited palette", "vintage": "vintage, retro, badge style, distressed texture, heritage feel, warm earth tones", "modern": "modern, sleek, gradient colors, tech-forward, innovative feel", "luxury": "luxury, elegant, gold accents, refined, premium feel, serif typography", "playful": "playful, fun, colorful, friendly, approachable, rounded shapes", "corporate": "corporate, professional, trustworthy, stable, conservative colors", "organic": "organic, natural, flowing lines, earth tones, sustainable feel", "geometric": "geometric, abstract, mathematical precision, symmetrical", "hand-drawn": "hand-drawn, artisan, sketch-like, authentic, imperfect lines", "3d": "3D, dimensional, depth, shadows, isometric perspective", "abstract": "abstract mark, conceptual, symbolic, non-literal representation, artistic interpretation", "lettermark": "lettermark, single letter or initials, typographic, monogram style, distinctive character", "wordmark": "wordmark, logotype, custom typography, brand name as logo, distinctive lettering", "emblem": "emblem, badge, crest style, enclosed design, traditional, authoritative feel", "mascot": "mascot, character, friendly face, personified, memorable figure", "gradient": "gradient, color transition, vibrant, modern digital feel, smooth color flow", "lineart": "line art, single stroke, continuous line, elegant simplicity, wire-frame style", "negative-space": "negative space, clever use of white space, hidden meaning, dual imagery, optical illusion" } INDUSTRY_PROMPTS = { "tech": "technology company, digital, innovative, modern, circuit-like elements", "healthcare": "healthcare, medical, caring, trust, cross or heart symbol", "finance": "financial services, stable, trustworthy, growth, upward elements", "food": "food and beverage, appetizing, warm colors, welcoming", "fashion": "fashion brand, elegant, stylish, refined, artistic", "fitness": "fitness and sports, dynamic, energetic, powerful, movement", "eco": "eco-friendly, sustainable, natural, green, leaf or earth elements", "education": "education, knowledge, growth, learning, book or cap symbol", "real-estate": "real estate, property, home, roof or building silhouette", "creative": "creative agency, artistic, unique, expressive, colorful" } def enhance_prompt(base_prompt, style=None, industry=None, brand_name=None): prompt_parts = [base_prompt] if style and style in STYLE_MODIFIERS: prompt_parts.append(STYLE_MODIFIERS[style]) if industry and industry in INDUSTRY_PROMPTS: prompt_parts.append(INDUSTRY_PROMPTS[industry]) if brand_name: prompt_parts.insert(0, f"Logo for '{brand_name}':") combined = ", ".join(prompt_parts) return LOGO_PROMPT_TEMPLATE.format(prompt=combined) def generate_logo(prompt, style=None, industry=None, brand_name=None, output_path=None, use_pro=False, aspect_ratio=None): if not GEMINI_API_KEY: print("Error: GEMINI_API_KEY not set") print("Set it with: export GEMINI_API_KEY='your-key'") return None # Initialize client client = genai.Client(api_key=GEMINI_API_KEY) # Enhance the prompt full_prompt = enhance_prompt(prompt, style, industry, brand_name) # Select model model = GEMINI_PRO if use_pro else GEMINI_FLASH model_label = "Nano Banana Pro (gemini-3-pro-image-preview)" if use_pro else "Nano Banana (gemini-2.5-flash-image)" # Set aspect ratio (default to 1:1 for logos) ratio = aspect_ratio if aspect_ratio in ASPECT_RATIOS else DEFAULT_ASPECT_RATIO print(f"Generating logo with {model_label}...") print(f"Aspect ratio: {ratio}") print(f"Prompt: {full_prompt[:150]}...") print() try: # Generate image using Gemini with image generation capability response = client.models.generate_content( model=model, contents=full_prompt, config=types.GenerateContentConfig( response_modalities=["IMAGE", "TEXT"], image_config=types.ImageConfig( aspect_ratio=ratio ), safety_settings=[ types.SafetySetting( category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_LOW_AND_ABOVE" ), types.SafetySetting( category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_LOW_AND_ABOVE" ), types.SafetySetting( category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_LOW_AND_ABOVE" ), types.SafetySetting( category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_LOW_AND_ABOVE" ), ] ) ) # Extract image from response image_data = None for part in response.candidates[0].content.parts: if hasattr(part, 'inline_data') and part.inline_data: if part.inline_data.mime_type.startswith('image/'): image_data = part.inline_data.data break if not image_data: print("No image generated. The model may not have produced an image.") print("Try a different prompt or check if the model supports image generation.") return None # Determine output path if output_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") brand_slug = brand_name.lower().replace(" ", "_") if brand_name else "logo" output_path = f"{brand_slug}_{timestamp}.png" # Save image with open(output_path, "wb") as f: f.write(image_data) print(f"Logo saved to: {output_path}") return output_path except Exception as e: print(f"Error generating logo: {e}") return None def generate_batch(prompt, brand_name, count, output_dir, use_pro=False, brand_context=None, aspect_ratio=None): # Select appropriate styles for batch generation batch_styles = [ ("minimalist", "Clean, simple geometric shape with minimal details"), ("modern", "Sleek gradient with tech-forward aesthetic"), ("geometric", "Abstract geometric patterns, mathematical precision"), ("gradient", "Vibrant color transitions, modern digital feel"), ("abstract", "Conceptual symbolic representation"), ("lettermark", "Stylized letter 'U' as monogram"), ("negative-space", "Clever use of negative space, hidden meaning"), ("lineart", "Single stroke continuous line design"), ("3d", "Dimensional design with depth and shadows"), ] # Ensure output directory exists os.makedirs(output_dir, exist_ok=True) results = [] model_label = "Pro" if use_pro else "Flash" ratio = aspect_ratio if aspect_ratio in ASPECT_RATIOS else DEFAULT_ASPECT_RATIO print(f"\n{'='*60}") print(f" BATCH LOGO GENERATION: {brand_name}") print(f" Model: Nano Banana {model_label}") print(f" Aspect Ratio: {ratio}") print(f" Variants: {count}") print(f" Output: {output_dir}") print(f"{'='*60}\n") for i in range(min(count, len(batch_styles))): style_key, style_desc = batch_styles[i] # Build enhanced prompt with brand context enhanced_prompt = f"{prompt}, {style_desc}" if brand_context: enhanced_prompt = f"{brand_context}, {enhanced_prompt}" # Generate filename filename = f"{brand_name.lower().replace(' ', '_')}_{style_key}_{i+1:02d}.png" output_path = os.path.join(output_dir, filename) print(f"[{i+1}/{count}] Generating {style_key} variant...") result = generate_logo( prompt=enhanced_prompt, style=style_key, industry="tech", brand_name=brand_name, output_path=output_path, use_pro=use_pro, aspect_ratio=aspect_ratio ) if result: results.append(result) print(f" ✓ Saved: {filename}\n") else: print(f" ✗ Failed: {style_key}\n") # Rate limiting between requests if i < count - 1: time.sleep(2) print(f"\n{'='*60}") print(f" BATCH COMPLETE: {len(results)}/{count} logos generated") print(f"{'='*60}\n") return results def main(): parser = argparse.ArgumentParser(description="Generate logos using Gemini Nano Banana models") parser.add_argument("--prompt", "-p", type=str, help="Logo description prompt") parser.add_argument("--brand", "-b", type=str, help="Brand name") parser.add_argument("--style", "-s", choices=list(STYLE_MODIFIERS.keys()), help="Logo style") parser.add_argument("--industry", "-i", choices=list(INDUSTRY_PROMPTS.keys()), help="Industry type") parser.add_argument("--output", "-o", type=str, help="Output file path") parser.add_argument("--output-dir", type=str, help="Output directory for batch generation") parser.add_argument("--batch", type=int, help="Number of logo variants to generate (batch mode)") parser.add_argument("--brand-context", type=str, help="Additional brand context for prompts") parser.add_argument("--pro", action="store_true", help="Use Nano Banana Pro (gemini-3-pro-image-preview) for professional quality") parser.add_argument("--aspect-ratio", "-r", choices=ASPECT_RATIOS, default=DEFAULT_ASPECT_RATIO, help=f"Image aspect ratio (default: {DEFAULT_ASPECT_RATIO} for logos)") parser.add_argument("--list-styles", action="store_true", help="List available styles") parser.add_argument("--list-industries", action="store_true", help="List available industries") args = parser.parse_args() if args.list_styles: print("Available styles:") for style, desc in STYLE_MODIFIERS.items(): print(f" {style}: {desc[:60]}...") return if args.list_industries: print("Available industries:") for industry, desc in INDUSTRY_PROMPTS.items(): print(f" {industry}: {desc[:60]}...") return if not args.prompt and not args.brand: parser.error("Either --prompt or --brand is required") prompt = args.prompt or "professional logo" # Batch mode if args.batch: output_dir = args.output_dir or f"./{args.brand.lower().replace(' ', '_')}_logos" generate_batch( prompt=prompt, brand_name=args.brand or "Logo", count=args.batch, output_dir=output_dir, use_pro=args.pro, brand_context=args.brand_context, aspect_ratio=args.aspect_ratio ) else: generate_logo( prompt=prompt, style=args.style, industry=args.industry, brand_name=args.brand, output_path=args.output, use_pro=args.pro, aspect_ratio=args.aspect_ratio ) if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,22 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Logo Generation Script using Gemini Nano Banana API +Uses Gemini 2.5 Flash Image and Gemini 3 Pro Image Preview models + +Models: +- Nano Banana (default): gemini-2.5-flash-image - fast, high-volume, low-latency +- Nano Banana Pro (--pro): gemini-3-pro-image-preview - professional quality, advanced reasoning + +Usage: + python generate.py --prompt "tech startup logo minimalist blue" + python generate.py --prompt "coffee shop vintage badge" --style vintage --output logo.png + python generate.py --brand "TechFlow" --industry tech --style minimalist + python generate.py --brand "TechFlow" --pro # Use Nano Banana Pro model + +Batch mode (generates multiple variants): + python generate.py --brand "Unikorn" --batch 9 --output-dir ./logos --pro +""" import argparse import os @@ -10,6 +27,7 @@ # Load environment variables def load_env(): + """Load .env files in priority order""" env_paths = [ Path(__file__).parent.parent.parent / ".env", Path.home() / ".claude" / "skills" / ".env", @@ -99,6 +117,7 @@ def enhance_prompt(base_prompt, style=None, industry=None, brand_name=None): + """Enhance the logo prompt with style and industry modifiers""" prompt_parts = [base_prompt] if style and style in STYLE_MODIFIERS: @@ -116,6 +135,12 @@ def generate_logo(prompt, style=None, industry=None, brand_name=None, output_path=None, use_pro=False, aspect_ratio=None): + """Generate a logo using Gemini models with image generation + + Args: + aspect_ratio: Image aspect ratio. Options: "1:1", "16:9", "9:16", "4:3", "3:4" + Default is "1:1" (square) for logos. + """ if not GEMINI_API_KEY: print("Error: GEMINI_API_KEY not set") @@ -203,6 +228,7 @@ def generate_batch(prompt, brand_name, count, output_dir, use_pro=False, brand_context=None, aspect_ratio=None): + """Generate multiple logo variants with different styles""" # Select appropriate styles for batch generation batch_styles = [ @@ -333,4 +359,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/logo/generate.py
Fill in missing docstrings in my code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse from core import CSV_CONFIG, MAX_RESULTS, search, search_all def format_output(result): if "error" in result: return f"Error: {result['error']}" output = [] output.append(f"## Logo Design Search Results") output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}") output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n") for i, row in enumerate(result['results'], 1): output.append(f"### Result {i}") for key, value in row.items(): value_str = str(value) if len(value_str) > 300: value_str = value_str[:300] + "..." output.append(f"- **{key}:** {value_str}") output.append("") return "\n".join(output) def generate_design_brief(query, brand_name=None): results = search_all(query, max_results=2) output = [] output.append("=" * 60) if brand_name: output.append(f" LOGO DESIGN BRIEF: {brand_name.upper()}") else: output.append(" LOGO DESIGN BRIEF") output.append("=" * 60) output.append(f" Query: {query}") output.append("=" * 60) output.append("") # Industry recommendations if "industry" in results: output.append("## INDUSTRY ANALYSIS") for r in results["industry"]: output.append(f"**Industry:** {r.get('Industry', 'N/A')}") output.append(f"- Recommended Styles: {r.get('Recommended Styles', 'N/A')}") output.append(f"- Colors: {r.get('Primary Colors', 'N/A')}") output.append(f"- Typography: {r.get('Typography', 'N/A')}") output.append(f"- Symbols: {r.get('Common Symbols', 'N/A')}") output.append(f"- Mood: {r.get('Mood', 'N/A')}") output.append(f"- Best Practices: {r.get('Best Practices', 'N/A')}") output.append(f"- Avoid: {r.get('Avoid', 'N/A')}") output.append("") # Style recommendations if "style" in results: output.append("## STYLE RECOMMENDATIONS") for r in results["style"]: output.append(f"**{r.get('Style Name', 'N/A')}** ({r.get('Category', 'N/A')})") output.append(f"- Colors: {r.get('Primary Colors', 'N/A')} | {r.get('Secondary Colors', 'N/A')}") output.append(f"- Typography: {r.get('Typography', 'N/A')}") output.append(f"- Effects: {r.get('Effects', 'N/A')}") output.append(f"- Best For: {r.get('Best For', 'N/A')}") output.append(f"- Complexity: {r.get('Complexity', 'N/A')}") output.append("") # Color recommendations if "color" in results: output.append("## COLOR PALETTE OPTIONS") for r in results["color"]: output.append(f"**{r.get('Palette Name', 'N/A')}**") output.append(f"- Primary: {r.get('Primary Hex', 'N/A')}") output.append(f"- Secondary: {r.get('Secondary Hex', 'N/A')}") output.append(f"- Accent: {r.get('Accent Hex', 'N/A')}") output.append(f"- Background: {r.get('Background Hex', 'N/A')}") output.append(f"- Psychology: {r.get('Psychology', 'N/A')}") output.append("") output.append("=" * 60) return "\n".join(output) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Logo Design Search") parser.add_argument("query", help="Search query") parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain") parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)") parser.add_argument("--json", action="store_true", help="Output as JSON") parser.add_argument("--design-brief", "-db", action="store_true", help="Generate comprehensive design brief") parser.add_argument("--brand-name", "-p", type=str, default=None, help="Brand name for design brief") args = parser.parse_args() if args.design_brief: result = generate_design_brief(args.query, args.brand_name) print(result) else: result = search(args.query, args.domain, args.max_results) if args.json: import json print(json.dumps(result, indent=2, ensure_ascii=False)) else: print(format_output(result))
--- +++ @@ -1,11 +1,19 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Logo Design Search - CLI for searching logo design guidelines +Usage: python search.py "<query>" [--domain <domain>] [--max-results 3] + python search.py "<query>" --design-brief [-p "Brand Name"] + +Domains: style, color, industry +""" import argparse from core import CSV_CONFIG, MAX_RESULTS, search, search_all def format_output(result): + """Format results for Claude consumption (token-optimized)""" if "error" in result: return f"Error: {result['error']}" @@ -27,6 +35,7 @@ def generate_design_brief(query, brand_name=None): + """Generate a comprehensive logo design brief based on query""" results = search_all(query, max_results=2) output = [] @@ -102,4 +111,4 @@ import json print(json.dumps(result, indent=2, ensure_ascii=False)) else: - print(format_output(result))+ print(format_output(result))
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/logo/search.py
Expand my code with proper documentation strings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import json import argparse from slide_search_core import ( search, search_all, AVAILABLE_DOMAINS, search_with_context, get_layout_for_goal, get_typography_for_slide, get_color_for_emotion, get_background_config ) def format_result(result, domain): output = [] if domain == "strategy": output.append(f"**{result.get('strategy_name', 'N/A')}**") output.append(f" Slides: {result.get('slide_count', 'N/A')}") output.append(f" Structure: {result.get('structure', 'N/A')}") output.append(f" Goal: {result.get('goal', 'N/A')}") output.append(f" Audience: {result.get('audience', 'N/A')}") output.append(f" Tone: {result.get('tone', 'N/A')}") output.append(f" Arc: {result.get('narrative_arc', 'N/A')}") output.append(f" Source: {result.get('sources', 'N/A')}") elif domain == "layout": output.append(f"**{result.get('layout_name', 'N/A')}**") output.append(f" Use case: {result.get('use_case', 'N/A')}") output.append(f" Zones: {result.get('content_zones', 'N/A')}") output.append(f" Visual weight: {result.get('visual_weight', 'N/A')}") output.append(f" CTA: {result.get('cta_placement', 'N/A')}") output.append(f" Recommended: {result.get('recommended_for', 'N/A')}") output.append(f" Avoid: {result.get('avoid_for', 'N/A')}") output.append(f" CSS: {result.get('css_structure', 'N/A')}") elif domain == "copy": output.append(f"**{result.get('formula_name', 'N/A')}**") output.append(f" Components: {result.get('components', 'N/A')}") output.append(f" Use case: {result.get('use_case', 'N/A')}") output.append(f" Template: {result.get('example_template', 'N/A')}") output.append(f" Emotion: {result.get('emotion_trigger', 'N/A')}") output.append(f" Slide type: {result.get('slide_type', 'N/A')}") output.append(f" Source: {result.get('source', 'N/A')}") elif domain == "chart": output.append(f"**{result.get('chart_type', 'N/A')}**") output.append(f" Best for: {result.get('best_for', 'N/A')}") output.append(f" Data type: {result.get('data_type', 'N/A')}") output.append(f" When to use: {result.get('when_to_use', 'N/A')}") output.append(f" When to avoid: {result.get('when_to_avoid', 'N/A')}") output.append(f" Max categories: {result.get('max_categories', 'N/A')}") output.append(f" Slide context: {result.get('slide_context', 'N/A')}") output.append(f" CSS: {result.get('css_implementation', 'N/A')}") output.append(f" Accessibility: {result.get('accessibility_notes', 'N/A')}") return "\n".join(output) def format_context(context): output = [] output.append(f"\n=== CONTEXTUAL RECOMMENDATIONS ===") output.append(f"Inferred Goal: {context.get('inferred_goal', 'N/A')}") output.append(f"Position: Slide {context.get('slide_position')} of {context.get('total_slides')}") if context.get('recommended_layout'): output.append(f"\n📐 Layout: {context['recommended_layout']}") output.append(f" Direction: {context.get('layout_direction', 'N/A')}") output.append(f" Visual Weight: {context.get('visual_weight', 'N/A')}") if context.get('typography'): typo = context['typography'] output.append(f"\n📝 Typography:") output.append(f" Primary: {typo.get('primary_size', 'N/A')}") output.append(f" Secondary: {typo.get('secondary_size', 'N/A')}") output.append(f" Contrast: {typo.get('weight_contrast', 'N/A')}") if context.get('color_treatment'): color = context['color_treatment'] output.append(f"\n🎨 Color Treatment:") output.append(f" Background: {color.get('background', 'N/A')}") output.append(f" Text: {color.get('text_color', 'N/A')}") output.append(f" Accent: {color.get('accent_usage', 'N/A')}") if context.get('should_break_pattern'): output.append(f"\n⚡ Pattern Break: YES (use contrasting layout)") if context.get('should_use_full_bleed'): output.append(f"\n🖼️ Full Bleed: Recommended for emotional impact") if context.get('use_background_image') and context.get('background'): bg = context['background'] output.append(f"\n📸 Background Image:") output.append(f" Category: {bg.get('image_category', 'N/A')}") output.append(f" Overlay: {bg.get('overlay_style', 'N/A')}") output.append(f" Keywords: {bg.get('search_keywords', 'N/A')}") output.append(f"\n✨ Animation: {context.get('animation_class', 'animate-fade-up')}") return "\n".join(output) def main(): parser = argparse.ArgumentParser( description="Search slide design databases", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: search-slides.py "investor pitch" # Auto-detect domain (strategy) search-slides.py "funnel conversion" -d chart search-slides.py "headline hook" -d copy search-slides.py "two column" -d layout search-slides.py "startup funding" --all # Search all domains search-slides.py "metrics dashboard" --json # JSON output Contextual Search (Premium System): search-slides.py "problem slide" --context --position 2 --total 9 search-slides.py "cta" --context --position 9 --total 9 --prev-emotion frustration """ ) parser.add_argument("query", help="Search query") parser.add_argument("-d", "--domain", choices=AVAILABLE_DOMAINS, help="Specific domain to search (auto-detected if not specified)") parser.add_argument("-n", "--max-results", type=int, default=3, help="Maximum results to return (default: 3)") parser.add_argument("--all", action="store_true", help="Search across all domains") parser.add_argument("--json", action="store_true", help="Output as JSON") # Contextual search options parser.add_argument("--context", action="store_true", help="Use contextual search with layout/typography/color recommendations") parser.add_argument("--position", type=int, default=1, help="Slide position in deck (1-based, default: 1)") parser.add_argument("--total", type=int, default=9, help="Total slides in deck (default: 9)") parser.add_argument("--prev-emotion", type=str, default=None, help="Previous slide's emotion for contrast calculation") args = parser.parse_args() # Contextual search mode if args.context: result = search_with_context( args.query, slide_position=args.position, total_slides=args.total, previous_emotion=args.prev_emotion ) if args.json: print(json.dumps(result, indent=2)) else: print(format_context(result['context'])) # Also show base search results if result.get('base_results'): print("\n\n=== RELATED SEARCH RESULTS ===") for domain, data in result['base_results'].items(): print(f"\n--- {domain.upper()} ---") for item in data['results']: print(format_result(item, domain)) print() return if args.all: results = search_all(args.query, args.max_results) if args.json: print(json.dumps(results, indent=2)) else: if not results: print(f"No results found for: {args.query}") return for domain, data in results.items(): print(f"\n=== {domain.upper()} ===") print(f"File: {data['file']}") print(f"Results: {data['count']}") print() for result in data['results']: print(format_result(result, domain)) print() else: result = search(args.query, args.domain, args.max_results) if args.json: print(json.dumps(result, indent=2)) else: if result.get("error"): print(f"Error: {result['error']}") return print(f"Domain: {result['domain']}") print(f"Query: {result['query']}") print(f"File: {result['file']}") print(f"Results: {result['count']}") print() if result['count'] == 0: print("No matching results found.") return for i, item in enumerate(result['results'], 1): print(f"--- Result {i} ---") print(format_result(item, result['domain'])) print() if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Slide Search CLI - Search slide design databases for strategies, layouts, copy, and charts +""" import sys import json @@ -12,6 +15,7 @@ def format_result(result, domain): + """Format a single search result for display""" output = [] if domain == "strategy": @@ -58,6 +62,7 @@ def format_context(context): + """Format contextual recommendations for display.""" output = [] output.append(f"\n=== CONTEXTUAL RECOMMENDATIONS ===") output.append(f"Inferred Goal: {context.get('inferred_goal', 'N/A')}") @@ -210,4 +215,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/search-slides.py
Create documentation for each function signature
#!/usr/bin/env python3 import argparse import json import sys from pathlib import Path from typing import Any, Dict, List, Optional class TailwindConfigGenerator: def __init__( self, typescript: bool = True, framework: str = "react", output_path: Optional[Path] = None, ): self.typescript = typescript self.framework = framework self.output_path = output_path or self._default_output_path() self.config: Dict[str, Any] = self._base_config() def _default_output_path(self) -> Path: ext = "ts" if self.typescript else "js" return Path.cwd() / f"tailwind.config.{ext}" def _base_config(self) -> Dict[str, Any]: return { "darkMode": ["class"], "content": self._default_content_paths(), "theme": { "extend": {} }, "plugins": [] } def _default_content_paths(self) -> List[str]: paths = { "react": [ "./src/**/*.{js,jsx,ts,tsx}", "./index.html", ], "vue": [ "./src/**/*.{vue,js,ts,jsx,tsx}", "./index.html", ], "svelte": [ "./src/**/*.{svelte,js,ts}", "./src/app.html", ], "nextjs": [ "./app/**/*.{js,ts,jsx,tsx}", "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], } return paths.get(self.framework, paths["react"]) def add_colors(self, colors: Dict[str, str]) -> None: if "colors" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["colors"] = {} self.config["theme"]["extend"]["colors"].update(colors) def add_color_palette(self, name: str, base_color: str) -> None: # For simplicity, use CSS variable approach if "colors" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["colors"] = {} self.config["theme"]["extend"]["colors"][name] = { "50": f"var(--color-{name}-50)", "100": f"var(--color-{name}-100)", "200": f"var(--color-{name}-200)", "300": f"var(--color-{name}-300)", "400": f"var(--color-{name}-400)", "500": f"var(--color-{name}-500)", "600": f"var(--color-{name}-600)", "700": f"var(--color-{name}-700)", "800": f"var(--color-{name}-800)", "900": f"var(--color-{name}-900)", "950": f"var(--color-{name}-950)", } def add_fonts(self, fonts: Dict[str, List[str]]) -> None: if "fontFamily" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["fontFamily"] = {} self.config["theme"]["extend"]["fontFamily"].update(fonts) def add_spacing(self, spacing: Dict[str, str]) -> None: if "spacing" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["spacing"] = {} self.config["theme"]["extend"]["spacing"].update(spacing) def add_breakpoints(self, breakpoints: Dict[str, str]) -> None: if "screens" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["screens"] = {} self.config["theme"]["extend"]["screens"].update(breakpoints) def add_plugins(self, plugins: List[str]) -> None: for plugin in plugins: if plugin not in self.config["plugins"]: self.config["plugins"].append(plugin) def recommend_plugins(self) -> List[str]: recommendations = [] # Always recommend animation plugin recommendations.append("tailwindcss-animate") # Framework-specific recommendations if self.framework == "nextjs": recommendations.append("@tailwindcss/typography") return recommendations def generate_config_string(self) -> str: if self.typescript: return self._generate_typescript() return self._generate_javascript() def _generate_typescript(self) -> str: plugins_str = self._format_plugins() config_json = json.dumps(self.config, indent=2) # Remove plugin array from JSON (we'll add it with require()) config_obj = self.config.copy() config_obj.pop("plugins", None) config_json = json.dumps(config_obj, indent=2) return f"""import type {{ Config }} from 'tailwindcss' const config: Config = {{ {self._indent_json(config_json, 1)} plugins: [{plugins_str}], }} export default config """ def _generate_javascript(self) -> str: plugins_str = self._format_plugins() config_obj = self.config.copy() config_obj.pop("plugins", None) config_json = json.dumps(config_obj, indent=2) return f"""/** @type {{import('tailwindcss').Config}} */ module.exports = {{ {self._indent_json(config_json, 1)} plugins: [{plugins_str}], }} """ def _format_plugins(self) -> str: if not self.config["plugins"]: return "" plugin_requires = [ f"require('{plugin}')" for plugin in self.config["plugins"] ] return ", ".join(plugin_requires) def _indent_json(self, json_str: str, level: int) -> str: indent = " " * level lines = json_str.split("\n") # Skip first and last lines (braces) indented = [indent + line for line in lines[1:-1]] return "\n".join(indented) def write_config(self) -> tuple[bool, str]: try: config_content = self.generate_config_string() self.output_path.write_text(config_content) return True, f"Configuration written to {self.output_path}" except OSError as e: return False, f"Failed to write config: {e}" def validate_config(self) -> tuple[bool, str]: # Check content paths exist if not self.config["content"]: return False, "No content paths specified" # Check if extending empty theme if not self.config["theme"]["extend"]: return True, "Warning: No theme extensions defined" return True, "Configuration valid" def main(): parser = argparse.ArgumentParser( description="Generate Tailwind CSS configuration", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Generate TypeScript config for Next.js python tailwind_config_gen.py --framework nextjs # Generate JavaScript config with custom colors python tailwind_config_gen.py --js --colors brand:#3b82f6 accent:#8b5cf6 # Add custom fonts python tailwind_config_gen.py --fonts display:"Playfair Display,serif" # Add custom spacing and breakpoints python tailwind_config_gen.py --spacing navbar:4rem --breakpoints 3xl:1920px # Add recommended plugins python tailwind_config_gen.py --plugins """, ) parser.add_argument( "--framework", choices=["react", "vue", "svelte", "nextjs"], default="react", help="Target framework (default: react)", ) parser.add_argument( "--js", action="store_true", help="Generate JavaScript config instead of TypeScript", ) parser.add_argument( "--output", type=Path, help="Output file path", ) parser.add_argument( "--colors", nargs="*", metavar="NAME:VALUE", help="Custom colors (e.g., brand:#3b82f6)", ) parser.add_argument( "--fonts", nargs="*", metavar="TYPE:FAMILY", help="Custom fonts (e.g., sans:'Inter,system-ui')", ) parser.add_argument( "--spacing", nargs="*", metavar="NAME:VALUE", help="Custom spacing (e.g., navbar:4rem)", ) parser.add_argument( "--breakpoints", nargs="*", metavar="NAME:WIDTH", help="Custom breakpoints (e.g., 3xl:1920px)", ) parser.add_argument( "--plugins", action="store_true", help="Add recommended plugins", ) parser.add_argument( "--validate-only", action="store_true", help="Validate config without writing file", ) args = parser.parse_args() # Initialize generator generator = TailwindConfigGenerator( typescript=not args.js, framework=args.framework, output_path=args.output, ) # Add custom colors if args.colors: colors = {} for color_spec in args.colors: try: name, value = color_spec.split(":", 1) colors[name] = value except ValueError: print(f"Invalid color spec: {color_spec}", file=sys.stderr) sys.exit(1) generator.add_colors(colors) # Add custom fonts if args.fonts: fonts = {} for font_spec in args.fonts: try: font_type, family = font_spec.split(":", 1) fonts[font_type] = [f.strip().strip("'\"") for f in family.split(",")] except ValueError: print(f"Invalid font spec: {font_spec}", file=sys.stderr) sys.exit(1) generator.add_fonts(fonts) # Add custom spacing if args.spacing: spacing = {} for spacing_spec in args.spacing: try: name, value = spacing_spec.split(":", 1) spacing[name] = value except ValueError: print(f"Invalid spacing spec: {spacing_spec}", file=sys.stderr) sys.exit(1) generator.add_spacing(spacing) # Add custom breakpoints if args.breakpoints: breakpoints = {} for bp_spec in args.breakpoints: try: name, width = bp_spec.split(":", 1) breakpoints[name] = width except ValueError: print(f"Invalid breakpoint spec: {bp_spec}", file=sys.stderr) sys.exit(1) generator.add_breakpoints(breakpoints) # Add recommended plugins if args.plugins: recommended = generator.recommend_plugins() generator.add_plugins(recommended) print(f"Added recommended plugins: {', '.join(recommended)}") print("\nInstall with:") print(f" npm install -D {' '.join(recommended)}") # Validate valid, message = generator.validate_config() if not valid: print(f"Validation failed: {message}", file=sys.stderr) sys.exit(1) if message.startswith("Warning"): print(message) # Validate only mode if args.validate_only: print("Configuration valid") print("\nGenerated config:") print(generator.generate_config_string()) sys.exit(0) # Write config success, message = generator.write_config() print(message) sys.exit(0 if success else 1) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +Tailwind CSS Configuration Generator + +Generate tailwind.config.js/ts with custom theme configuration. +Supports colors, fonts, spacing, breakpoints, and plugin recommendations. +""" import argparse import json @@ -8,6 +14,7 @@ class TailwindConfigGenerator: + """Generate Tailwind CSS configuration files.""" def __init__( self, @@ -15,16 +22,26 @@ framework: str = "react", output_path: Optional[Path] = None, ): + """ + Initialize generator. + + Args: + typescript: If True, generate .ts config, else .js + framework: Framework name (react, vue, svelte, nextjs) + output_path: Output file path (default: auto-detect) + """ self.typescript = typescript self.framework = framework self.output_path = output_path or self._default_output_path() self.config: Dict[str, Any] = self._base_config() def _default_output_path(self) -> Path: + """Determine default output path.""" ext = "ts" if self.typescript else "js" return Path.cwd() / f"tailwind.config.{ext}" def _base_config(self) -> Dict[str, Any]: + """Create base configuration structure.""" return { "darkMode": ["class"], "content": self._default_content_paths(), @@ -35,6 +52,7 @@ } def _default_content_paths(self) -> List[str]: + """Get default content paths for framework.""" paths = { "react": [ "./src/**/*.{js,jsx,ts,tsx}", @@ -57,12 +75,26 @@ return paths.get(self.framework, paths["react"]) def add_colors(self, colors: Dict[str, str]) -> None: + """ + Add custom colors to theme. + + Args: + colors: Dict of color_name: color_value + Value can be hex (#3b82f6) or variable (hsl(var(--primary))) + """ if "colors" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["colors"] = {} self.config["theme"]["extend"]["colors"].update(colors) def add_color_palette(self, name: str, base_color: str) -> None: + """ + Add full color palette (50-950 shades) for a base color. + + Args: + name: Color name (e.g., 'brand', 'primary') + base_color: Base color in oklch format or hex + """ # For simplicity, use CSS variable approach if "colors" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["colors"] = {} @@ -82,29 +114,63 @@ } def add_fonts(self, fonts: Dict[str, List[str]]) -> None: + """ + Add custom font families. + + Args: + fonts: Dict of font_type: [font_names] + e.g., {'sans': ['Inter', 'system-ui', 'sans-serif']} + """ if "fontFamily" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["fontFamily"] = {} self.config["theme"]["extend"]["fontFamily"].update(fonts) def add_spacing(self, spacing: Dict[str, str]) -> None: + """ + Add custom spacing values. + + Args: + spacing: Dict of name: value + e.g., {'18': '4.5rem', 'navbar': '4rem'} + """ if "spacing" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["spacing"] = {} self.config["theme"]["extend"]["spacing"].update(spacing) def add_breakpoints(self, breakpoints: Dict[str, str]) -> None: + """ + Add custom breakpoints. + + Args: + breakpoints: Dict of name: width + e.g., {'3xl': '1920px', 'tablet': '768px'} + """ if "screens" not in self.config["theme"]["extend"]: self.config["theme"]["extend"]["screens"] = {} self.config["theme"]["extend"]["screens"].update(breakpoints) def add_plugins(self, plugins: List[str]) -> None: + """ + Add plugin requirements. + + Args: + plugins: List of plugin names + e.g., ['@tailwindcss/typography', '@tailwindcss/forms'] + """ for plugin in plugins: if plugin not in self.config["plugins"]: self.config["plugins"].append(plugin) def recommend_plugins(self) -> List[str]: + """ + Get plugin recommendations based on configuration. + + Returns: + List of recommended plugin package names + """ recommendations = [] # Always recommend animation plugin @@ -117,11 +183,18 @@ return recommendations def generate_config_string(self) -> str: + """ + Generate configuration file content. + + Returns: + Configuration file as string + """ if self.typescript: return self._generate_typescript() return self._generate_javascript() def _generate_typescript(self) -> str: + """Generate TypeScript configuration.""" plugins_str = self._format_plugins() config_json = json.dumps(self.config, indent=2) @@ -142,6 +215,7 @@ """ def _generate_javascript(self) -> str: + """Generate JavaScript configuration.""" plugins_str = self._format_plugins() config_obj = self.config.copy() @@ -156,6 +230,7 @@ """ def _format_plugins(self) -> str: + """Format plugins array for config.""" if not self.config["plugins"]: return "" @@ -165,6 +240,7 @@ return ", ".join(plugin_requires) def _indent_json(self, json_str: str, level: int) -> str: + """Add indentation to JSON string.""" indent = " " * level lines = json_str.split("\n") # Skip first and last lines (braces) @@ -172,6 +248,12 @@ return "\n".join(indented) def write_config(self) -> tuple[bool, str]: + """ + Write configuration to file. + + Returns: + Tuple of (success, message) + """ try: config_content = self.generate_config_string() @@ -183,6 +265,12 @@ return False, f"Failed to write config: {e}" def validate_config(self) -> tuple[bool, str]: + """ + Validate configuration. + + Returns: + Tuple of (valid, message) + """ # Check content paths exist if not self.config["content"]: return False, "No content paths specified" @@ -195,6 +283,7 @@ def main(): + """CLI entry point.""" parser = argparse.ArgumentParser( description="Generate Tailwind CSS configuration", formatter_class=argparse.RawDescriptionHelpFormatter, @@ -364,4 +453,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/ui-styling/scripts/tailwind_config_gen.py
Provide docstrings following PEP 257
#!/usr/bin/env python3 import re import json import sys from pathlib import Path from typing import Dict, List, Tuple, Optional # Project root relative to this script PROJECT_ROOT = Path(__file__).parent.parent.parent.parent.parent TOKENS_JSON_PATH = PROJECT_ROOT / 'assets' / 'design-tokens.json' TOKENS_CSS_PATH = PROJECT_ROOT / 'assets' / 'design-tokens.css' # Asset directories to validate ASSET_DIRS = { 'slides': PROJECT_ROOT / 'assets' / 'designs' / 'slides', 'infographics': PROJECT_ROOT / 'assets' / 'infographics', } # Patterns that indicate hardcoded values (should use tokens) FORBIDDEN_PATTERNS = [ (r'#[0-9A-Fa-f]{3,8}\b', 'hex color'), (r'rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)', 'rgb color'), (r'rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)', 'rgba color'), (r'hsl\([^)]+\)', 'hsl color'), (r"font-family:\s*'[^v][^a][^r][^']*',", 'hardcoded font'), # Exclude var() (r'font-family:\s*"[^v][^a][^r][^"]*",', 'hardcoded font'), ] # Allowed rgba patterns (brand colors with transparency - CSS limitation) # These are derived from brand tokens but need rgba for transparency ALLOWED_RGBA_PATTERNS = [ r'rgba\(\s*59\s*,\s*130\s*,\s*246', # --color-primary (#3B82F6) r'rgba\(\s*245\s*,\s*158\s*,\s*11', # --color-secondary (#F59E0B) r'rgba\(\s*16\s*,\s*185\s*,\s*129', # --color-accent (#10B981) r'rgba\(\s*20\s*,\s*184\s*,\s*166', # --color-accent alt (#14B8A6) r'rgba\(\s*0\s*,\s*0\s*,\s*0', # black transparency (common) r'rgba\(\s*255\s*,\s*255\s*,\s*255', # white transparency (common) r'rgba\(\s*15\s*,\s*23\s*,\s*42', # --color-surface (#0F172A) r'rgba\(\s*7\s*,\s*11\s*,\s*20', # --color-background (#070B14) ] # Allowed exceptions (external images, etc.) ALLOWED_EXCEPTIONS = [ 'pexels.com', 'unsplash.com', 'youtube.com', 'ytimg.com', 'googlefonts', 'fonts.googleapis.com', 'fonts.gstatic.com', ] class ValidationResult: def __init__(self, file_path: Path): self.file_path = file_path self.errors: List[str] = [] self.warnings: List[str] = [] self.passed = True def add_error(self, msg: str): self.errors.append(msg) self.passed = False def add_warning(self, msg: str): self.warnings.append(msg) def load_css_variables() -> Dict[str, str]: variables = {} if TOKENS_CSS_PATH.exists(): content = TOKENS_CSS_PATH.read_text() # Extract --var-name: value patterns for match in re.finditer(r'(--[\w-]+):\s*([^;]+);', content): variables[match.group(1)] = match.group(2).strip() return variables def is_inside_block(content: str, match_pos: int, open_tag: str, close_tag: str) -> bool: pre = content[:match_pos] tag_open = pre.rfind(open_tag) tag_close = pre.rfind(close_tag) return tag_open > tag_close def is_allowed_exception(context: str) -> bool: context_lower = context.lower() return any(exc in context_lower for exc in ALLOWED_EXCEPTIONS) def is_allowed_rgba(match_text: str) -> bool: return any(re.match(pattern, match_text) for pattern in ALLOWED_RGBA_PATTERNS) def get_context(content: str, pos: int, chars: int = 100) -> str: start = max(0, pos - chars) end = min(len(content), pos + chars) return content[start:end] def validate_html(content: str, file_path: Path, verbose: bool = False) -> ValidationResult: result = ValidationResult(file_path) # 1. Check for design-tokens.css import if 'design-tokens.css' not in content: result.add_error("Missing design-tokens.css import") # 2. Check for forbidden patterns in CSS for pattern, description in FORBIDDEN_PATTERNS: for match in re.finditer(pattern, content): match_text = match.group() match_pos = match.start() context = get_context(content, match_pos) # Skip if in <script> block (Chart.js allowed) if is_inside_block(content, match_pos, '<script', '</script>'): if verbose: result.add_warning(f"Allowed in <script>: {match_text}") continue # Skip if in allowed exception context (external URLs) if is_allowed_exception(context): if verbose: result.add_warning(f"Allowed external: {match_text}") continue # Skip rgba using brand colors (needed for transparency effects) if description == 'rgba color' and is_allowed_rgba(match_text): if verbose: result.add_warning(f"Allowed brand rgba: {match_text}") continue # Skip if part of var() reference (false positive) if 'var(' in context and match_text in context: # Check if it's a fallback value in var() var_pattern = rf'var\([^)]*{re.escape(match_text)}[^)]*\)' if re.search(var_pattern, context): continue # Error if in <style> or inline style if is_inside_block(content, match_pos, '<style', '</style>'): result.add_error(f"Hardcoded {description} in <style>: {match_text}") elif 'style="' in context: result.add_error(f"Hardcoded {description} in inline style: {match_text}") # 3. Check for required var() usage indicators token_patterns = [ r'var\(--color-', r'var\(--primitive-', r'var\(--typography-', r'var\(--card-', r'var\(--button-', ] token_count = sum(len(re.findall(p, content)) for p in token_patterns) if token_count < 5: result.add_warning(f"Low token usage ({token_count} var() references). Consider using more design tokens.") return result def validate_file(file_path: Path, verbose: bool = False) -> ValidationResult: if not file_path.exists(): result = ValidationResult(file_path) result.add_error("File not found") return result content = file_path.read_text() return validate_html(content, file_path, verbose) def validate_directory(dir_path: Path, verbose: bool = False) -> List[ValidationResult]: results = [] if dir_path.exists(): for html_file in sorted(dir_path.glob('*.html')): results.append(validate_file(html_file, verbose)) return results def print_result(result: ValidationResult, verbose: bool = False): status = "✓" if result.passed else "✗" print(f" {status} {result.file_path.name}") if result.errors: for error in result.errors[:5]: # Limit output print(f" ├─ {error}") if len(result.errors) > 5: print(f" └─ ... and {len(result.errors) - 5} more errors") if verbose and result.warnings: for warning in result.warnings[:3]: print(f" [warn] {warning}") def print_summary(all_results: Dict[str, List[ValidationResult]]): total_files = 0 total_passed = 0 total_errors = 0 print("\n" + "=" * 60) print("HTML DESIGN TOKEN VALIDATION SUMMARY") print("=" * 60) for asset_type, results in all_results.items(): if not results: continue passed = sum(1 for r in results if r.passed) failed = len(results) - passed errors = sum(len(r.errors) for r in results) total_files += len(results) total_passed += passed total_errors += errors status = "✓" if failed == 0 else "✗" print(f"\n{status} {asset_type.upper()}: {passed}/{len(results)} passed") for result in results: if not result.passed: print_result(result) print("\n" + "-" * 60) if total_errors == 0: print(f"✓ ALL PASSED: {total_passed}/{total_files} files valid") else: print(f"✗ FAILED: {total_files - total_passed}/{total_files} files have issues ({total_errors} total errors)") print("-" * 60) return total_errors == 0 def main(): import argparse parser = argparse.ArgumentParser( description='Validate HTML assets for design token compliance', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: %(prog)s # Validate all HTML assets %(prog)s --type slides # Validate only slides %(prog)s --type infographics # Validate only infographics %(prog)s path/to/file.html # Validate specific file %(prog)s --colors # Show brand colors from tokens """ ) parser.add_argument('files', nargs='*', help='Specific HTML files to validate') parser.add_argument('-t', '--type', choices=['slides', 'infographics', 'all'], default='all', help='Asset type to validate') parser.add_argument('-v', '--verbose', action='store_true', help='Show warnings') parser.add_argument('--colors', action='store_true', help='Print CSS variables from tokens') parser.add_argument('--fix', action='store_true', help='Auto-fix issues (experimental)') args = parser.parse_args() # Show colors mode if args.colors: variables = load_css_variables() print("\nDesign Tokens (from design-tokens.css):") print("-" * 40) for name, value in sorted(variables.items())[:30]: print(f" {name}: {value}") if len(variables) > 30: print(f" ... and {len(variables) - 30} more") return all_results: Dict[str, List[ValidationResult]] = {} # Validate specific files if args.files: results = [] for file_path in args.files: path = Path(file_path) if path.exists(): results.append(validate_file(path, args.verbose)) else: result = ValidationResult(path) result.add_error("File not found") results.append(result) all_results['specified'] = results else: # Validate by type types_to_check = ASSET_DIRS.keys() if args.type == 'all' else [args.type] for asset_type in types_to_check: if asset_type in ASSET_DIRS: results = validate_directory(ASSET_DIRS[asset_type], args.verbose) all_results[asset_type] = results # Print results success = print_summary(all_results) if not success: sys.exit(1) if __name__ == '__main__': main()
--- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3 +""" +HTML Design Token Validator +Ensures all HTML assets (slides, infographics, etc.) use design tokens. +Source of truth: assets/design-tokens.css + +Usage: + python html-token-validator.py # Validate all HTML assets + python html-token-validator.py --type slides # Validate only slides + python html-token-validator.py --type infographics # Validate only infographics + python html-token-validator.py path/to/file.html # Validate specific file + python html-token-validator.py --fix # Auto-fix issues (WIP) +""" import re import json @@ -48,6 +60,7 @@ class ValidationResult: + """Validation result for a single file.""" def __init__(self, file_path: Path): self.file_path = file_path self.errors: List[str] = [] @@ -63,6 +76,7 @@ def load_css_variables() -> Dict[str, str]: + """Load CSS variables from design-tokens.css.""" variables = {} if TOKENS_CSS_PATH.exists(): content = TOKENS_CSS_PATH.read_text() @@ -73,6 +87,7 @@ def is_inside_block(content: str, match_pos: int, open_tag: str, close_tag: str) -> bool: + """Check if position is inside a specific HTML block.""" pre = content[:match_pos] tag_open = pre.rfind(open_tag) tag_close = pre.rfind(close_tag) @@ -80,21 +95,33 @@ def is_allowed_exception(context: str) -> bool: + """Check if the hardcoded value is in an allowed exception context.""" context_lower = context.lower() return any(exc in context_lower for exc in ALLOWED_EXCEPTIONS) def is_allowed_rgba(match_text: str) -> bool: + """Check if rgba pattern uses brand colors (allowed for transparency).""" return any(re.match(pattern, match_text) for pattern in ALLOWED_RGBA_PATTERNS) def get_context(content: str, pos: int, chars: int = 100) -> str: + """Get surrounding context for a match position.""" start = max(0, pos - chars) end = min(len(content), pos + chars) return content[start:end] def validate_html(content: str, file_path: Path, verbose: bool = False) -> ValidationResult: + """ + Validate HTML content for design token compliance. + + Checks: + 1. design-tokens.css import present + 2. No hardcoded colors in CSS (except in <script> for Chart.js) + 3. No hardcoded fonts + 4. Uses var(--token-name) pattern + """ result = ValidationResult(file_path) # 1. Check for design-tokens.css import @@ -156,6 +183,7 @@ def validate_file(file_path: Path, verbose: bool = False) -> ValidationResult: + """Validate a single HTML file.""" if not file_path.exists(): result = ValidationResult(file_path) result.add_error("File not found") @@ -166,6 +194,7 @@ def validate_directory(dir_path: Path, verbose: bool = False) -> List[ValidationResult]: + """Validate all HTML files in a directory.""" results = [] if dir_path.exists(): for html_file in sorted(dir_path.glob('*.html')): @@ -174,6 +203,7 @@ def print_result(result: ValidationResult, verbose: bool = False): + """Print validation result for a file.""" status = "✓" if result.passed else "✗" print(f" {status} {result.file_path.name}") @@ -189,6 +219,7 @@ def print_summary(all_results: Dict[str, List[ValidationResult]]): + """Print summary of all validation results.""" total_files = 0 total_passed = 0 total_errors = 0 @@ -227,6 +258,7 @@ def main(): + """CLI entry point.""" import argparse parser = argparse.ArgumentParser( @@ -292,4 +324,4 @@ if __name__ == '__main__': - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/html-token-validator.py
Write docstrings describing each step
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import re from pathlib import Path from math import log from collections import defaultdict # ============ CONFIGURATION ============ DATA_DIR = Path(__file__).parent.parent / "data" MAX_RESULTS = 3 CSV_CONFIG = { "style": { "file": "styles.csv", "search_cols": ["Style Category", "Keywords", "Best For", "Type", "AI Prompt Keywords"], "output_cols": ["Style Category", "Type", "Keywords", "Primary Colors", "Effects & Animation", "Best For", "Performance", "Accessibility", "Framework Compatibility", "Complexity", "AI Prompt Keywords", "CSS/Technical Keywords", "Implementation Checklist", "Design System Variables"] }, "color": { "file": "colors.csv", "search_cols": ["Product Type", "Notes"], "output_cols": ["Product Type", "Primary", "On Primary", "Secondary", "On Secondary", "Accent", "On Accent", "Background", "Foreground", "Card", "Card Foreground", "Muted", "Muted Foreground", "Border", "Destructive", "On Destructive", "Ring", "Notes"] }, "chart": { "file": "charts.csv", "search_cols": ["Data Type", "Keywords", "Best Chart Type", "When to Use", "When NOT to Use", "Accessibility Notes"], "output_cols": ["Data Type", "Keywords", "Best Chart Type", "Secondary Options", "When to Use", "When NOT to Use", "Data Volume Threshold", "Color Guidance", "Accessibility Grade", "Accessibility Notes", "A11y Fallback", "Library Recommendation", "Interactive Level"] }, "landing": { "file": "landing.csv", "search_cols": ["Pattern Name", "Keywords", "Conversion Optimization", "Section Order"], "output_cols": ["Pattern Name", "Keywords", "Section Order", "Primary CTA Placement", "Color Strategy", "Conversion Optimization"] }, "product": { "file": "products.csv", "search_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Key Considerations"], "output_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Secondary Styles", "Landing Page Pattern", "Dashboard Style (if applicable)", "Color Palette Focus"] }, "ux": { "file": "ux-guidelines.csv", "search_cols": ["Category", "Issue", "Description", "Platform"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "typography": { "file": "typography.csv", "search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"], "output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"] }, "icons": { "file": "icons.csv", "search_cols": ["Category", "Icon Name", "Keywords", "Best For"], "output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"] }, "react": { "file": "react-performance.csv", "search_cols": ["Category", "Issue", "Keywords", "Description"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] }, "web": { "file": "app-interface.csv", "search_cols": ["Category", "Issue", "Keywords", "Description"], "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"] } } STACK_CONFIG = { "react-native": {"file": "stacks/react-native.csv"}, } # Common columns for all stacks _STACK_COLS = { "search_cols": ["Category", "Guideline", "Description", "Do", "Don't"], "output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"] } AVAILABLE_STACKS = list(STACK_CONFIG.keys()) # ============ BM25 IMPLEMENTATION ============ class BM25: def __init__(self, k1=1.5, b=0.75): self.k1 = k1 self.b = b self.corpus = [] self.doc_lengths = [] self.avgdl = 0 self.idf = {} self.doc_freqs = defaultdict(int) self.N = 0 def tokenize(self, text): text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: return self.doc_lengths = [len(doc) for doc in self.corpus] self.avgdl = sum(self.doc_lengths) / self.N for doc in self.corpus: seen = set() for word in doc: if word not in seen: self.doc_freqs[word] += 1 seen.add(word) for word, freq in self.doc_freqs.items(): self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): query_tokens = self.tokenize(query) scores = [] for idx, doc in enumerate(self.corpus): score = 0 doc_len = self.doc_lengths[idx] term_freqs = defaultdict(int) for word in doc: term_freqs[word] += 1 for token in query_tokens: if token in self.idf: tf = term_freqs[token] idf = self.idf[token] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl) score += idf * numerator / denominator scores.append((idx, score)) return sorted(scores, key=lambda x: x[1], reverse=True) # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): if not filepath.exists(): return [] data = _load_csv(filepath) # Build documents from search columns documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data] # BM25 search bm25 = BM25() bm25.fit(documents) ranked = bm25.score(query) # Get top results with score > 0 results = [] for idx, score in ranked[:max_results]: if score > 0: row = data[idx] results.append({col: row.get(col, "") for col in output_cols if col in row}) return results def detect_domain(query): query_lower = query.lower() domain_keywords = { "color": ["color", "palette", "hex", "#", "rgb", "token", "semantic", "accent", "destructive", "muted", "foreground"], "chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"], "landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"], "product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard", "fitness", "restaurant", "hotel", "travel", "music", "education", "learning", "legal", "insurance", "medical", "beauty", "pharmacy", "dental", "pet", "dating", "wedding", "recipe", "delivery", "ride", "booking", "calendar", "timer", "tracker", "diary", "note", "chat", "messenger", "crm", "invoice", "parking", "transit", "vpn", "alarm", "weather", "sleep", "meditation", "fasting", "habit", "grocery", "meme", "wardrobe", "plant care", "reading", "flashcard", "puzzle", "trivia", "arcade", "photography", "streaming", "podcast", "newsletter", "marketplace", "freelancer", "coworking", "airline", "museum", "theater", "church", "non-profit", "charity", "kindergarten", "daycare", "senior care", "veterinary", "florist", "bakery", "brewery", "construction", "automotive", "real estate", "logistics", "agriculture", "coding bootcamp"], "style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"], "ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"], "typography": ["font", "typography", "heading", "serif", "sans"], "icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"], "react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"], "web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"] } scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()} best = max(scores, key=scores.get) return best if scores[best] > 0 else "style" def search(query, domain=None, max_results=MAX_RESULTS): if domain is None: domain = detect_domain(query) config = CSV_CONFIG.get(domain, CSV_CONFIG["style"]) filepath = DATA_DIR / config["file"] if not filepath.exists(): return {"error": f"File not found: {filepath}", "domain": domain} results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results) return { "domain": domain, "query": query, "file": config["file"], "count": len(results), "results": results } def search_stack(query, stack, max_results=MAX_RESULTS): if stack not in STACK_CONFIG: return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"} filepath = DATA_DIR / STACK_CONFIG[stack]["file"] if not filepath.exists(): return {"error": f"Stack file not found: {filepath}", "stack": stack} results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results) return { "domain": "stack", "stack": stack, "query": query, "file": STACK_CONFIG[stack]["file"], "count": len(results), "results": results }
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +UI/UX Pro Max Core - BM25 search engine for UI/UX style guides +""" import csv import re @@ -79,6 +82,7 @@ # ============ BM25 IMPLEMENTATION ============ class BM25: + """BM25 ranking algorithm for text search""" def __init__(self, k1=1.5, b=0.75): self.k1 = k1 @@ -91,10 +95,12 @@ self.N = 0 def tokenize(self, text): + """Lowercase, split, remove punctuation, filter short words""" text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): + """Build BM25 index from documents""" self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: @@ -113,6 +119,7 @@ self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): + """Score all documents against query""" query_tokens = self.tokenize(query) scores = [] @@ -138,11 +145,13 @@ # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): + """Load CSV and return list of dicts""" with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): + """Core search function using BM25""" if not filepath.exists(): return [] @@ -167,6 +176,7 @@ def detect_domain(query): + """Auto-detect the most relevant domain from query""" query_lower = query.lower() domain_keywords = { @@ -188,6 +198,7 @@ def search(query, domain=None, max_results=MAX_RESULTS): + """Main search function with auto-domain detection""" if domain is None: domain = detect_domain(query) @@ -209,6 +220,7 @@ def search_stack(query, stack, max_results=MAX_RESULTS): + """Search stack-specific guidelines""" if stack not in STACK_CONFIG: return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"} @@ -226,4 +238,4 @@ "file": STACK_CONFIG[stack]["file"], "count": len(results), "results": results - }+ }
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/cli/assets/scripts/core.py
Provide clean and structured docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import json import os import sys import base64 from pathlib import Path from datetime import datetime # Add parent directory for imports sys.path.insert(0, str(Path(__file__).parent)) from core import search, get_cip_brief # Deliverable descriptions for presentation DELIVERABLE_INFO = { "business card": { "title": "Business Card", "concept": "First impression touchpoint for professional networking", "purpose": "Creates memorable brand recall during business exchanges", "specs": "Standard 3.5 x 2 inches, premium paper stock" }, "letterhead": { "title": "Letterhead", "concept": "Official correspondence identity", "purpose": "Establishes credibility and professionalism in written communications", "specs": "A4/Letter size, digital and print versions" }, "document template": { "title": "Document Template", "concept": "Branded document system for internal and external use", "purpose": "Ensures consistent brand representation across all documents", "specs": "Multiple formats: Word, PDF, Google Docs compatible" }, "reception signage": { "title": "Reception Signage", "concept": "Brand presence in physical office environment", "purpose": "Creates strong first impression for visitors and reinforces brand identity", "specs": "3D dimensional letters, backlit LED options, premium materials" }, "office signage": { "title": "Office Signage", "concept": "Wayfinding and brand presence system", "purpose": "Guides visitors while maintaining consistent brand experience", "specs": "Modular system with directional and informational signs" }, "polo shirt": { "title": "Polo Shirt", "concept": "Professional team apparel", "purpose": "Creates unified team identity and brand ambassadorship", "specs": "Premium pique cotton, embroidered logo on left chest" }, "t-shirt": { "title": "T-Shirt", "concept": "Casual brand apparel", "purpose": "Extends brand reach through everyday wear and promotional events", "specs": "High-quality cotton, screen print or embroidery options" }, "vehicle": { "title": "Vehicle Branding", "concept": "Mobile brand advertising", "purpose": "Transforms fleet into moving billboards for maximum visibility", "specs": "Partial or full wrap, vinyl graphics, weather-resistant" }, "van": { "title": "Van Branding", "concept": "Commercial vehicle identity", "purpose": "Professional fleet presence for service and delivery operations", "specs": "Full wrap design, high-visibility contact information" }, "car": { "title": "Car Branding", "concept": "Executive vehicle identity", "purpose": "Professional presence for corporate and sales teams", "specs": "Subtle branding, door panels and rear window" }, "envelope": { "title": "Envelope", "concept": "Branded mail correspondence", "purpose": "Extends brand identity to all outgoing mail", "specs": "DL, C4, C5 sizes with logo placement" }, "folder": { "title": "Presentation Folder", "concept": "Document organization with brand identity", "purpose": "Professional presentation of proposals and materials", "specs": "A4/Letter pocket folder with die-cut design" } } def get_image_base64(image_path): try: with open(image_path, "rb") as f: return base64.b64encode(f.read()).decode('utf-8') except Exception as e: print(f"Warning: Could not load image {image_path}: {e}") return None def get_deliverable_info(filename): filename_lower = filename.lower() for key, info in DELIVERABLE_INFO.items(): if key.replace(" ", "-") in filename_lower or key.replace(" ", "_") in filename_lower: return info # Default info return { "title": filename.replace("-", " ").replace("_", " ").title(), "concept": "Brand identity application", "purpose": "Extends brand presence across touchpoints", "specs": "Custom specifications" } def generate_html(brand_name, industry, images_dir, output_path=None, style=None): images_dir = Path(images_dir) if not images_dir.exists(): print(f"Error: Directory not found: {images_dir}") return None # Get all PNG images images = sorted(images_dir.glob("*.png")) if not images: print(f"Error: No PNG images found in {images_dir}") return None # Get CIP brief for brand info brief = get_cip_brief(brand_name, industry, style) style_info = brief.get("style", {}) industry_info = brief.get("industry", {}) # Build HTML html_parts = [f'''<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{brand_name} - Corporate Identity Program</title> <style> * {{ margin: 0; padding: 0; box-sizing: border-box; }} body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif; background: #0a0a0a; color: #ffffff; line-height: 1.6; }} .hero {{ min-height: 100vh; display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; padding: 4rem 2rem; background: linear-gradient(135deg, #1a1a2e 0%, #0a0a0a 100%); }} .hero h1 {{ font-size: 4rem; font-weight: 700; letter-spacing: -0.02em; margin-bottom: 1rem; background: linear-gradient(135deg, #ffffff 0%, #888888 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }} .hero .subtitle {{ font-size: 1.5rem; color: #888; margin-bottom: 3rem; }} .hero .meta {{ display: flex; gap: 3rem; flex-wrap: wrap; justify-content: center; }} .hero .meta-item {{ text-align: center; }} .hero .meta-label {{ font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.1em; color: #666; margin-bottom: 0.5rem; }} .hero .meta-value {{ font-size: 1rem; color: #ccc; }} .section {{ padding: 6rem 2rem; max-width: 1400px; margin: 0 auto; }} .section-title {{ font-size: 2.5rem; font-weight: 600; margin-bottom: 1rem; color: #fff; }} .section-subtitle {{ font-size: 1.1rem; color: #888; margin-bottom: 4rem; max-width: 600px; }} .deliverable {{ display: grid; grid-template-columns: 1fr 1fr; gap: 4rem; margin-bottom: 8rem; align-items: center; }} .deliverable:nth-child(even) {{ direction: rtl; }} .deliverable:nth-child(even) > * {{ direction: ltr; }} .deliverable-image {{ position: relative; border-radius: 16px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); }} .deliverable-image img {{ width: 100%; height: auto; display: block; }} .deliverable-content {{ padding: 2rem 0; }} .deliverable-title {{ font-size: 2rem; font-weight: 600; margin-bottom: 1rem; color: #fff; }} .deliverable-concept {{ font-size: 1.1rem; color: #aaa; margin-bottom: 1.5rem; font-style: italic; }} .deliverable-purpose {{ font-size: 1rem; color: #888; margin-bottom: 1.5rem; line-height: 1.8; }} .deliverable-specs {{ display: inline-block; padding: 0.5rem 1rem; background: rgba(255, 255, 255, 0.05); border-radius: 8px; font-size: 0.85rem; color: #666; }} .color-palette {{ display: flex; gap: 1rem; margin-top: 2rem; }} .color-swatch {{ width: 60px; height: 60px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); }} .footer {{ text-align: center; padding: 4rem 2rem; border-top: 1px solid #222; color: #666; }} .footer p {{ margin-bottom: 0.5rem; }} @media (max-width: 900px) {{ .hero h1 {{ font-size: 2.5rem; }} .deliverable {{ grid-template-columns: 1fr; gap: 2rem; }} .deliverable:nth-child(even) {{ direction: ltr; }} }} </style> </head> <body> <section class="hero"> <h1>{brand_name}</h1> <p class="subtitle">Corporate Identity Program</p> <div class="meta"> <div class="meta-item"> <div class="meta-label">Industry</div> <div class="meta-value">{industry_info.get("Industry", industry.title())}</div> </div> <div class="meta-item"> <div class="meta-label">Style</div> <div class="meta-value">{style_info.get("Style Name", "Corporate")}</div> </div> <div class="meta-item"> <div class="meta-label">Mood</div> <div class="meta-value">{style_info.get("Mood", "Professional")}</div> </div> <div class="meta-item"> <div class="meta-label">Deliverables</div> <div class="meta-value">{len(images)} Items</div> </div> </div> </section> <section class="section"> <h2 class="section-title">Brand Applications</h2> <p class="section-subtitle"> Comprehensive identity system designed to maintain consistency across all brand touchpoints and communications. </p> '''] # Add each deliverable for i, image_path in enumerate(images): info = get_deliverable_info(image_path.stem) img_base64 = get_image_base64(image_path) if img_base64: img_src = f"data:image/png;base64,{img_base64}" else: img_src = str(image_path) html_parts.append(f''' <div class="deliverable"> <div class="deliverable-image"> <img src="{img_src}" alt="{info['title']}" loading="lazy"> </div> <div class="deliverable-content"> <h3 class="deliverable-title">{info['title']}</h3> <p class="deliverable-concept">{info['concept']}</p> <p class="deliverable-purpose">{info['purpose']}</p> <span class="deliverable-specs">{info['specs']}</span> </div> </div> ''') # Close HTML html_parts.append(f''' </section> <footer class="footer"> <p><strong>{brand_name}</strong> Corporate Identity Program</p> <p>Generated on {datetime.now().strftime("%B %d, %Y")}</p> <p style="margin-top: 1rem; font-size: 0.8rem;">Powered by CIP Design Skill</p> </footer> </body> </html> ''') html_content = "".join(html_parts) # Save HTML output_path = output_path or images_dir / f"{brand_name.lower().replace(' ', '-')}-cip-presentation.html" output_path = Path(output_path) with open(output_path, "w", encoding="utf-8") as f: f.write(html_content) print(f"✅ HTML presentation generated: {output_path}") return str(output_path) def main(): parser = argparse.ArgumentParser( description="Generate HTML presentation from CIP mockups", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Generate HTML from CIP images directory python render-html.py --brand "TopGroup" --industry "consulting" --images ./topgroup-cip # Specify output path python render-html.py --brand "TopGroup" --industry "consulting" --images ./cip --output presentation.html """ ) parser.add_argument("--brand", "-b", required=True, help="Brand name") parser.add_argument("--industry", "-i", default="technology", help="Industry type") parser.add_argument("--style", "-s", help="Design style") parser.add_argument("--images", required=True, help="Directory containing CIP mockup images") parser.add_argument("--output", "-o", help="Output HTML file path") args = parser.parse_args() generate_html( brand_name=args.brand, industry=args.industry, images_dir=args.images, output_path=args.output, style=args.style ) if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,11 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +CIP HTML Presentation Renderer + +Generates a professional HTML presentation from CIP mockup images +with detailed descriptions, concepts, and brand guidelines. +""" import argparse import json @@ -91,6 +97,7 @@ def get_image_base64(image_path): + """Convert image to base64 for embedding in HTML""" try: with open(image_path, "rb") as f: return base64.b64encode(f.read()).decode('utf-8') @@ -100,6 +107,7 @@ def get_deliverable_info(filename): + """Extract deliverable type from filename and get info""" filename_lower = filename.lower() for key, info in DELIVERABLE_INFO.items(): if key.replace(" ", "-") in filename_lower or key.replace(" ", "_") in filename_lower: @@ -114,6 +122,7 @@ def generate_html(brand_name, industry, images_dir, output_path=None, style=None): + """Generate HTML presentation from CIP images""" images_dir = Path(images_dir) if not images_dir.exists(): @@ -412,4 +421,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/render-html.py
Add docstrings for internal functions
#!/usr/bin/env python3 import sys import subprocess from pathlib import Path SCRIPT_DIR = Path(__file__).parent UNIFIED_VALIDATOR = SCRIPT_DIR / 'html-token-validator.py' def main(): args = sys.argv[1:] # If no files specified, default to slides type if not args or all(arg.startswith('-') for arg in args): cmd = [sys.executable, str(UNIFIED_VALIDATOR), '--type', 'slides'] + args else: cmd = [sys.executable, str(UNIFIED_VALIDATOR)] + args result = subprocess.run(cmd) sys.exit(result.returncode) if __name__ == '__main__': main()
--- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3 +""" +Slide Token Validator (Legacy Wrapper) +Now delegates to html-token-validator.py for unified HTML validation. + +For new usage, prefer: + python html-token-validator.py --type slides + python html-token-validator.py --type infographics + python html-token-validator.py # All HTML assets +""" import sys import subprocess @@ -9,6 +18,7 @@ def main(): + """Delegate to unified html-token-validator.py with --type slides.""" args = sys.argv[1:] # If no files specified, default to slides type @@ -22,4 +32,4 @@ if __name__ == '__main__': - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/slide-token-validator.py
Generate consistent docstrings
#!/usr/bin/env python3 import json import csv import re import sys from pathlib import Path # Project root relative to this script PROJECT_ROOT = Path(__file__).parent.parent.parent.parent.parent TOKENS_PATH = PROJECT_ROOT / 'assets' / 'design-tokens.json' BACKGROUNDS_CSV = Path(__file__).parent.parent / 'data' / 'slide-backgrounds.csv' def resolve_token_reference(ref: str, tokens: dict) -> str: if not ref or not ref.startswith('{') or not ref.endswith('}'): return ref # Already a value, not a reference # Parse reference: {primitive.color.ocean-blue.500} path = ref[1:-1].split('.') # ['primitive', 'color', 'ocean-blue', '500'] current = tokens for key in path: if isinstance(current, dict): current = current.get(key) else: return None # Invalid path # Return $value if it's a token object if isinstance(current, dict) and '$value' in current: return current['$value'] return current def load_brand_colors(): try: with open(TOKENS_PATH) as f: tokens = json.load(f) colors = tokens.get('primitive', {}).get('color', {}) semantic = tokens.get('semantic', {}).get('color', {}) # Try semantic tokens first (preferred) - resolve references if semantic: primary_ref = semantic.get('primary', {}).get('$value') secondary_ref = semantic.get('secondary', {}).get('$value') accent_ref = semantic.get('accent', {}).get('$value') background_ref = semantic.get('background', {}).get('$value') primary = resolve_token_reference(primary_ref, tokens) secondary = resolve_token_reference(secondary_ref, tokens) accent = resolve_token_reference(accent_ref, tokens) background = resolve_token_reference(background_ref, tokens) if primary and secondary: return { 'primary': primary, 'secondary': secondary, 'accent': accent or primary, 'background': background or '#0D0D0D', } # Fallback: find first color palette with 500 value (primary) primary_keys = ['ocean-blue', 'coral', 'blue', 'primary'] secondary_keys = ['golden-amber', 'purple', 'amber', 'secondary'] accent_keys = ['emerald', 'mint', 'green', 'accent'] primary_color = None secondary_color = None accent_color = None for key in primary_keys: if key in colors and isinstance(colors[key], dict): primary_color = colors[key].get('500', {}).get('$value') if primary_color: break for key in secondary_keys: if key in colors and isinstance(colors[key], dict): secondary_color = colors[key].get('500', {}).get('$value') if secondary_color: break for key in accent_keys: if key in colors and isinstance(colors[key], dict): accent_color = colors[key].get('500', {}).get('$value') if accent_color: break background = colors.get('dark', {}).get('800', {}).get('$value', '#0D0D0D') return { 'primary': primary_color or '#3B82F6', 'secondary': secondary_color or '#F59E0B', 'accent': accent_color or '#10B981', 'background': background, } except (FileNotFoundError, KeyError, TypeError): # Fallback defaults return { 'primary': '#3B82F6', 'secondary': '#F59E0B', 'accent': '#10B981', 'background': '#0D0D0D', } def load_backgrounds_config(): config = {} try: with open(BACKGROUNDS_CSV, newline='') as f: reader = csv.DictReader(f) for row in reader: config[row['slide_type']] = row except FileNotFoundError: print(f"Warning: {BACKGROUNDS_CSV} not found") return config def get_overlay_css(style: str, brand_colors: dict) -> str: overlays = { 'gradient-dark': f"linear-gradient(135deg, {brand_colors['background']}E6, {brand_colors['background']}B3)", 'gradient-brand': f"linear-gradient(135deg, {brand_colors['primary']}CC, {brand_colors['secondary']}99)", 'gradient-accent': f"linear-gradient(135deg, {brand_colors['accent']}99, transparent)", 'blur-dark': f"rgba(13,13,13,0.8)", 'desaturate-dark': f"rgba(13,13,13,0.7)", } return overlays.get(style, overlays['gradient-dark']) # Curated high-quality images from Pexels (free to use, pre-selected for brand aesthetic) CURATED_IMAGES = { 'hero': [ 'https://images.pexels.com/photos/3861969/pexels-photo-3861969.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/2582937/pexels-photo-2582937.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/1089438/pexels-photo-1089438.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'vision': [ 'https://images.pexels.com/photos/3183150/pexels-photo-3183150.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3182812/pexels-photo-3182812.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3184291/pexels-photo-3184291.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'team': [ 'https://images.pexels.com/photos/3184418/pexels-photo-3184418.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3184338/pexels-photo-3184338.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3182773/pexels-photo-3182773.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'testimonial': [ 'https://images.pexels.com/photos/3184465/pexels-photo-3184465.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/1181622/pexels-photo-1181622.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'cta': [ 'https://images.pexels.com/photos/3184339/pexels-photo-3184339.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3184298/pexels-photo-3184298.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'problem': [ 'https://images.pexels.com/photos/3760529/pexels-photo-3760529.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/897817/pexels-photo-897817.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'solution': [ 'https://images.pexels.com/photos/3184292/pexels-photo-3184292.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3184644/pexels-photo-3184644.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'hook': [ 'https://images.pexels.com/photos/2582937/pexels-photo-2582937.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/1089438/pexels-photo-1089438.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'social': [ 'https://images.pexels.com/photos/3184360/pexels-photo-3184360.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3184287/pexels-photo-3184287.jpeg?auto=compress&cs=tinysrgb&w=1920', ], 'demo': [ 'https://images.pexels.com/photos/1181675/pexels-photo-1181675.jpeg?auto=compress&cs=tinysrgb&w=1920', 'https://images.pexels.com/photos/3861958/pexels-photo-3861958.jpeg?auto=compress&cs=tinysrgb&w=1920', ], } def get_curated_images(slide_type: str) -> list: return CURATED_IMAGES.get(slide_type, CURATED_IMAGES.get('hero', [])) def get_pexels_search_url(keywords: str) -> str: import urllib.parse return f"https://www.pexels.com/search/{urllib.parse.quote(keywords)}/" def get_background_image(slide_type: str) -> dict: brand_colors = load_brand_colors() config = load_backgrounds_config() slide_config = config.get(slide_type) overlay_style = 'gradient-dark' keywords = slide_type if slide_config: keywords = slide_config.get('search_keywords', slide_config.get('image_category', slide_type)) overlay_style = slide_config.get('overlay_style', 'gradient-dark') # Get curated images urls = get_curated_images(slide_type) if urls: return { 'url': urls[0], 'all_urls': urls, 'overlay': get_overlay_css(overlay_style, brand_colors), 'attribution': 'Photo from Pexels (free to use)', 'source': 'pexels-curated', 'search_url': get_pexels_search_url(keywords), } # Fallback: provide search URL for manual selection return { 'url': None, 'overlay': get_overlay_css(overlay_style, brand_colors), 'keywords': keywords, 'search_url': get_pexels_search_url(keywords), 'available_types': list(CURATED_IMAGES.keys()), } def generate_css_for_background(result: dict, slide_class: str = '.slide-with-bg') -> str: if not result.get('url'): search_url = result.get('search_url', '') return f"""/* No image scraped. Search manually: {search_url} */ /* Overlay ready: {result.get('overlay', 'gradient-dark')} */ """ return f"""{slide_class} {{ background-image: url('{result['url']}'); background-size: cover; background-position: center; position: relative; }} {slide_class}::before {{ content: ''; position: absolute; inset: 0; background: {result['overlay']}; }} {slide_class} .content {{ position: relative; z-index: 1; }} /* {result.get('attribution', 'Pexels')} - {result.get('search_url', '')} */ """ def main(): import argparse parser = argparse.ArgumentParser(description='Get background images for slides') parser.add_argument('slide_type', nargs='?', help='Slide type (hero, vision, team, etc.)') parser.add_argument('--list', action='store_true', help='List available slide types') parser.add_argument('--css', action='store_true', help='Output CSS for the background') parser.add_argument('--json', action='store_true', help='Output JSON') parser.add_argument('--colors', action='store_true', help='Show brand colors') parser.add_argument('--all', action='store_true', help='Show all curated URLs') args = parser.parse_args() if args.colors: colors = load_brand_colors() print("\nBrand Colors (from design-tokens.json):") for name, value in colors.items(): print(f" {name}: {value}") return if args.list: print("\nAvailable slide types (curated images):") for slide_type, urls in CURATED_IMAGES.items(): print(f" {slide_type}: {len(urls)} images") return if not args.slide_type: parser.print_help() return result = get_background_image(args.slide_type) if args.json: print(json.dumps(result, indent=2)) elif args.css: print(generate_css_for_background(result)) elif args.all: print(f"\nAll images for '{args.slide_type}':") for i, url in enumerate(result.get('all_urls', []), 1): print(f" {i}. {url}") else: print(f"\nImage URL: {result['url']}") print(f"Alternatives: {len(result.get('all_urls', []))} available (use --all)") print(f"Overlay: {result['overlay']}") if __name__ == '__main__': main()
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Background Image Fetcher +Fetches real images from Pexels for slide backgrounds. +Uses web scraping (no API key required) or WebFetch tool integration. +""" import json import csv @@ -13,6 +18,7 @@ def resolve_token_reference(ref: str, tokens: dict) -> str: + """Resolve token reference like {primitive.color.ocean-blue.500} to hex value.""" if not ref or not ref.startswith('{') or not ref.endswith('}'): return ref # Already a value, not a reference @@ -31,6 +37,10 @@ def load_brand_colors(): + """Load colors from assets/design-tokens.json for overlay gradients. + + Resolves semantic token references to actual hex values. + """ try: with open(TOKENS_PATH) as f: tokens = json.load(f) @@ -104,6 +114,7 @@ def load_backgrounds_config(): + """Load background configuration from CSV.""" config = {} try: with open(BACKGROUNDS_CSV, newline='') as f: @@ -116,6 +127,7 @@ def get_overlay_css(style: str, brand_colors: dict) -> str: + """Generate overlay CSS using brand colors from design-tokens.json.""" overlays = { 'gradient-dark': f"linear-gradient(135deg, {brand_colors['background']}E6, {brand_colors['background']}B3)", 'gradient-brand': f"linear-gradient(135deg, {brand_colors['primary']}CC, {brand_colors['secondary']}99)", @@ -175,15 +187,21 @@ def get_curated_images(slide_type: str) -> list: + """Get curated images for slide type.""" return CURATED_IMAGES.get(slide_type, CURATED_IMAGES.get('hero', [])) def get_pexels_search_url(keywords: str) -> str: + """Generate Pexels search URL for manual lookup.""" import urllib.parse return f"https://www.pexels.com/search/{urllib.parse.quote(keywords)}/" def get_background_image(slide_type: str) -> dict: + """ + Get curated image matching slide type and brand aesthetic. + Uses pre-selected Pexels images (no API/scraping needed). + """ brand_colors = load_brand_colors() config = load_backgrounds_config() @@ -218,6 +236,7 @@ def generate_css_for_background(result: dict, slide_class: str = '.slide-with-bg') -> str: + """Generate CSS for a background slide.""" if not result.get('url'): search_url = result.get('search_url', '') return f"""/* No image scraped. Search manually: {search_url} */ @@ -248,6 +267,7 @@ def main(): + """CLI entry point.""" import argparse parser = argparse.ArgumentParser(description='Get background images for slides') @@ -294,4 +314,4 @@ if __name__ == '__main__': - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/fetch-background.py
Generate NumPy-style docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import re from pathlib import Path from math import log from collections import defaultdict # ============ CONFIGURATION ============ DATA_DIR = Path(__file__).parent.parent.parent / "data" / "cip" MAX_RESULTS = 3 CSV_CONFIG = { "deliverable": { "file": "deliverables.csv", "search_cols": ["Deliverable", "Category", "Keywords", "Description", "Mockup Context"], "output_cols": ["Deliverable", "Category", "Keywords", "Description", "Dimensions", "File Format", "Logo Placement", "Color Usage", "Typography Notes", "Mockup Context", "Best Practices", "Avoid"] }, "style": { "file": "styles.csv", "search_cols": ["Style Name", "Category", "Keywords", "Description", "Mood"], "output_cols": ["Style Name", "Category", "Keywords", "Description", "Primary Colors", "Secondary Colors", "Typography", "Materials", "Finishes", "Mood", "Best For", "Avoid For"] }, "industry": { "file": "industries.csv", "search_cols": ["Industry", "Keywords", "CIP Style", "Mood"], "output_cols": ["Industry", "Keywords", "CIP Style", "Primary Colors", "Secondary Colors", "Typography", "Key Deliverables", "Mood", "Best Practices", "Avoid"] }, "mockup": { "file": "mockup-contexts.csv", "search_cols": ["Context Name", "Category", "Keywords", "Scene Description"], "output_cols": ["Context Name", "Category", "Keywords", "Scene Description", "Lighting", "Environment", "Props", "Camera Angle", "Background", "Style Notes", "Best For", "Prompt Modifiers"] } } # ============ BM25 IMPLEMENTATION ============ class BM25: def __init__(self, k1=1.5, b=0.75): self.k1 = k1 self.b = b self.corpus = [] self.doc_lengths = [] self.avgdl = 0 self.idf = {} self.doc_freqs = defaultdict(int) self.N = 0 def tokenize(self, text): text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: return self.doc_lengths = [len(doc) for doc in self.corpus] self.avgdl = sum(self.doc_lengths) / self.N for doc in self.corpus: seen = set() for word in doc: if word not in seen: self.doc_freqs[word] += 1 seen.add(word) for word, freq in self.doc_freqs.items(): self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): query_tokens = self.tokenize(query) scores = [] for idx, doc in enumerate(self.corpus): score = 0 doc_len = self.doc_lengths[idx] term_freqs = defaultdict(int) for word in doc: term_freqs[word] += 1 for token in query_tokens: if token in self.idf: tf = term_freqs[token] idf = self.idf[token] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl) score += idf * numerator / denominator scores.append((idx, score)) return sorted(scores, key=lambda x: x[1], reverse=True) # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): if not filepath.exists(): return [] data = _load_csv(filepath) # Build documents from search columns documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data] # BM25 search bm25 = BM25() bm25.fit(documents) ranked = bm25.score(query) # Get top results with score > 0 results = [] for idx, score in ranked[:max_results]: if score > 0: row = data[idx] results.append({col: row.get(col, "") for col in output_cols if col in row}) return results def detect_domain(query): query_lower = query.lower() domain_keywords = { "deliverable": ["card", "letterhead", "envelope", "folder", "shirt", "cap", "badge", "signage", "vehicle", "car", "van", "stationery", "uniform", "merchandise", "packaging", "banner", "booth"], "style": ["style", "minimal", "modern", "luxury", "vintage", "industrial", "elegant", "bold", "corporate", "organic", "playful"], "industry": ["tech", "finance", "legal", "healthcare", "hospitality", "food", "fashion", "retail", "construction", "logistics"], "mockup": ["mockup", "scene", "context", "photo", "shot", "lighting", "background", "studio", "lifestyle"] } scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()} best = max(scores, key=scores.get) return best if scores[best] > 0 else "deliverable" def search(query, domain=None, max_results=MAX_RESULTS): if domain is None: domain = detect_domain(query) config = CSV_CONFIG.get(domain, CSV_CONFIG["deliverable"]) filepath = DATA_DIR / config["file"] if not filepath.exists(): return {"error": f"File not found: {filepath}", "domain": domain} results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results) return { "domain": domain, "query": query, "file": config["file"], "count": len(results), "results": results } def search_all(query, max_results=2): all_results = {} for domain in CSV_CONFIG.keys(): result = search(query, domain, max_results) if result.get("results"): all_results[domain] = result["results"] return all_results def get_cip_brief(brand_name, industry_query, style_query=None): # Search industry industry_results = search(industry_query, "industry", 1) industry = industry_results.get("results", [{}])[0] if industry_results.get("results") else {} # Search style (use industry style if not specified) style_query = style_query or industry.get("CIP Style", "corporate minimal") style_results = search(style_query, "style", 1) style = style_results.get("results", [{}])[0] if style_results.get("results") else {} # Get recommended deliverables for the industry key_deliverables = industry.get("Key Deliverables", "").split() deliverable_results = [] for d in key_deliverables[:5]: result = search(d, "deliverable", 1) if result.get("results"): deliverable_results.append(result["results"][0]) return { "brand_name": brand_name, "industry": industry, "style": style, "recommended_deliverables": deliverable_results, "color_system": { "primary": style.get("Primary Colors", industry.get("Primary Colors", "")), "secondary": style.get("Secondary Colors", industry.get("Secondary Colors", "")) }, "typography": style.get("Typography", industry.get("Typography", "")), "materials": style.get("Materials", ""), "finishes": style.get("Finishes", "") }
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +CIP Design Core - BM25 search engine for Corporate Identity Program design guidelines +""" import csv import re @@ -37,6 +40,7 @@ # ============ BM25 IMPLEMENTATION ============ class BM25: + """BM25 ranking algorithm for text search""" def __init__(self, k1=1.5, b=0.75): self.k1 = k1 @@ -49,10 +53,12 @@ self.N = 0 def tokenize(self, text): + """Lowercase, split, remove punctuation, filter short words""" text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): + """Build BM25 index from documents""" self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: @@ -71,6 +77,7 @@ self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): + """Score all documents against query""" query_tokens = self.tokenize(query) scores = [] @@ -96,11 +103,13 @@ # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): + """Load CSV and return list of dicts""" with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): + """Core search function using BM25""" if not filepath.exists(): return [] @@ -125,6 +134,7 @@ def detect_domain(query): + """Auto-detect the most relevant domain from query""" query_lower = query.lower() domain_keywords = { @@ -140,6 +150,7 @@ def search(query, domain=None, max_results=MAX_RESULTS): + """Main search function with auto-domain detection""" if domain is None: domain = detect_domain(query) @@ -161,6 +172,7 @@ def search_all(query, max_results=2): + """Search across all domains and combine results""" all_results = {} for domain in CSV_CONFIG.keys(): result = search(query, domain, max_results) @@ -170,6 +182,7 @@ def get_cip_brief(brand_name, industry_query, style_query=None): + """Generate a comprehensive CIP brief for a brand""" # Search industry industry_results = search(industry_query, "industry", 1) industry = industry_results.get("results", [{}])[0] if industry_results.get("results") else {} @@ -199,4 +212,4 @@ "typography": style.get("Typography", industry.get("Typography", "")), "materials": style.get("Materials", ""), "finishes": style.get("Finishes", "") - }+ }
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/core.py
Add docstrings for production code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import json import os import sys from pathlib import Path from datetime import datetime # Add parent directory for imports sys.path.insert(0, str(Path(__file__).parent)) from core import search, get_cip_brief # Model options MODELS = { "flash": "gemini-2.5-flash-image", # Nano Banana Flash - fast, default "pro": "gemini-3-pro-image-preview" # Nano Banana Pro - quality, 4K text } DEFAULT_MODEL = "flash" def load_logo_image(logo_path): try: from PIL import Image except ImportError: print("Error: pillow package not installed.") print("Install with: pip install pillow") return None logo_path = Path(logo_path) if not logo_path.exists(): print(f"Error: Logo file not found: {logo_path}") return None try: img = Image.open(logo_path) # Convert to RGB if necessary (Gemini works best with RGB) if img.mode in ('RGBA', 'P'): # Create white background for transparent images background = Image.new('RGB', img.size, (255, 255, 255)) if img.mode == 'RGBA': background.paste(img, mask=img.split()[3]) # Use alpha channel as mask else: background.paste(img) img = background elif img.mode != 'RGB': img = img.convert('RGB') return img except Exception as e: print(f"Error loading logo: {e}") return None # Load environment variables def load_env(): env_paths = [ Path(__file__).parent.parent.parent / ".env", Path.home() / ".claude" / "skills" / ".env", Path.home() / ".claude" / ".env" ] for env_path in env_paths: if env_path.exists(): with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: key, value = line.split("=", 1) if key not in os.environ: os.environ[key] = value.strip('"\'') load_env() def build_cip_prompt(deliverable, brand_name, style=None, industry=None, mockup=None, use_logo_image=False): # Get deliverable details deliverable_info = search(deliverable, "deliverable", 1) deliverable_data = deliverable_info.get("results", [{}])[0] if deliverable_info.get("results") else {} # Get style details style_info = search(style or "corporate minimal", "style", 1) if style else {} style_data = style_info.get("results", [{}])[0] if style_info.get("results") else {} # Get industry details industry_info = search(industry or "technology", "industry", 1) if industry else {} industry_data = industry_info.get("results", [{}])[0] if industry_info.get("results") else {} # Get mockup context mockup_context = deliverable_data.get("Mockup Context", "clean professional") if mockup: mockup_info = search(mockup, "mockup", 1) if mockup_info.get("results"): mockup_data = mockup_info["results"][0] mockup_context = mockup_data.get("Scene Description", mockup_context) # Build prompt components deliverable_name = deliverable_data.get("Deliverable", deliverable) description = deliverable_data.get("Description", "") dimensions = deliverable_data.get("Dimensions", "") logo_placement = deliverable_data.get("Logo Placement", "center") style_name = style_data.get("Style Name", style or "corporate") primary_colors = style_data.get("Primary Colors", industry_data.get("Primary Colors", "#0F172A #FFFFFF")) typography = style_data.get("Typography", industry_data.get("Typography", "clean sans-serif")) materials = style_data.get("Materials", "premium quality") finishes = style_data.get("Finishes", "professional") mood = style_data.get("Mood", industry_data.get("Mood", "professional")) # Construct the prompt - different for image editing vs pure generation if use_logo_image: # Image editing prompt: instructs to USE the provided logo image prompt_parts = [ f"Create a professional corporate identity mockup photograph of a {deliverable_name}", f"Use the EXACT logo from the provided image - do NOT modify or recreate the logo", f"The logo MUST appear exactly as shown in the input image", f"Place the logo on the {deliverable_name} at: {logo_placement}", f"Brand name: '{brand_name}'", f"{description}" if description else "", f"Design style: {style_name}", f"Color scheme matching the logo colors", f"Materials: {materials} with {finishes} finish", f"Setting: {mockup_context}", f"Mood: {mood}", "Photorealistic product photography", "Soft natural lighting, professional studio quality", "8K resolution, sharp details" ] else: # Pure text-to-image prompt prompt_parts = [ f"Professional corporate identity mockup photograph", f"showing {deliverable_name} for brand '{brand_name}'", f"{description}" if description else "", f"{style_name} design style", f"using colors {primary_colors}", f"{typography} typography", f"logo placement: {logo_placement}", f"{materials} materials with {finishes} finish", f"{mockup_context} setting", f"{mood} mood", "photorealistic product photography", "soft natural lighting", "high quality professional shot", "8k resolution detailed" ] prompt = ", ".join([p for p in prompt_parts if p]) return { "prompt": prompt, "deliverable": deliverable_name, "style": style_name, "brand": brand_name, "colors": primary_colors, "mockup_context": mockup_context, "logo_placement": logo_placement } def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", aspect_ratio="1:1", logo_image=None): try: from google import genai from google.genai import types except ImportError: print("Error: google-genai package not installed.") print("Install with: pip install google-genai") return None api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") if not api_key: print("Error: GEMINI_API_KEY or GOOGLE_API_KEY not set") return None client = genai.Client(api_key=api_key) prompt = prompt_data["prompt"] model_name = MODELS.get(model_key, MODELS[DEFAULT_MODEL]) # Determine mode mode = "image-editing" if logo_image else "text-to-image" print(f"\n🎨 Generating CIP mockup...") print(f" Mode: {mode}") print(f" Deliverable: {prompt_data['deliverable']}") print(f" Brand: {prompt_data['brand']}") print(f" Style: {prompt_data['style']}") print(f" Model: {model_name}") print(f" Context: {prompt_data['mockup_context']}") if logo_image: print(f" Logo: Using provided image ({logo_image.size[0]}x{logo_image.size[1]})") try: # Build contents: either just prompt or [prompt, image] for image editing if logo_image: # Image editing mode: pass both prompt and logo image contents = [prompt, logo_image] else: # Text-to-image mode: just the prompt contents = prompt # Use generate_content with response_modalities=['IMAGE'] for Nano Banana response = client.models.generate_content( model=model_name, contents=contents, config=types.GenerateContentConfig( response_modalities=['IMAGE'], # Uppercase required image_config=types.ImageConfig( aspect_ratio=aspect_ratio ) ) ) # Extract image from response if response.candidates and response.candidates[0].content.parts: for part in response.candidates[0].content.parts: if hasattr(part, 'inline_data') and part.inline_data: # Save image output_dir = output_dir or Path.cwd() output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") brand_slug = prompt_data["brand"].lower().replace(" ", "-") deliverable_slug = prompt_data["deliverable"].lower().replace(" ", "-") filename = f"{brand_slug}-{deliverable_slug}-{timestamp}.png" filepath = output_dir / filename image_data = part.inline_data.data with open(filepath, "wb") as f: f.write(image_data) print(f"\n✅ Generated: {filepath}") return str(filepath) print("No image generated in response") return None except Exception as e: print(f"Error generating image: {e}") return None def generate_cip_set(brand_name, industry, style=None, deliverables=None, output_dir=None, model_key="flash", logo_path=None, aspect_ratio="1:1"): # Load logo image if provided logo_image = None if logo_path: logo_image = load_logo_image(logo_path) if not logo_image: print("Warning: Could not load logo, falling back to text-to-image mode") # Get CIP brief for the brand brief = get_cip_brief(brand_name, industry, style) # Default deliverables if not specified if not deliverables: deliverables = ["business card", "letterhead", "office signage", "vehicle", "polo shirt"] results = [] for deliverable in deliverables: prompt_data = build_cip_prompt( deliverable=deliverable, brand_name=brand_name, style=brief.get("style", {}).get("Style Name"), industry=industry, use_logo_image=(logo_image is not None) ) filepath = generate_with_nano_banana( prompt_data, output_dir, model_key=model_key, aspect_ratio=aspect_ratio, logo_image=logo_image ) if filepath: results.append({ "deliverable": deliverable, "filepath": filepath, "prompt": prompt_data["prompt"] }) return results def check_logo_required(brand_name, skip_prompt=False): if skip_prompt: return 'continue' print(f"\n⚠️ No logo image provided for '{brand_name}'") print(" Without a logo, AI will generate its own interpretation of the brand logo.") print("") print(" Options:") print(" 1. Continue without logo (AI-generated logo interpretation)") print(" 2. Generate a logo first using 'logo-design' skill") print(" 3. Exit and provide a logo path with --logo") print("") try: choice = input(" Enter choice [1/2/3] (default: 1): ").strip() if choice == '2': return 'generate' elif choice == '3': return 'exit' return 'continue' except (EOFError, KeyboardInterrupt): return 'continue' def main(): parser = argparse.ArgumentParser( description="Generate CIP mockups using Gemini Nano Banana", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Generate with brand logo (RECOMMENDED) python generate.py --brand "TopGroup" --logo /path/to/logo.png --deliverable "business card" # Generate CIP set with logo python generate.py --brand "TopGroup" --logo /path/to/logo.png --industry "consulting" --set # Generate without logo (AI interprets brand) python generate.py --brand "TechFlow" --deliverable "business card" --no-logo-prompt # Generate with Pro model (higher quality, 4K text) python generate.py --brand "TechFlow" --logo logo.png --deliverable "business card" --model pro # Specify output directory and aspect ratio python generate.py --brand "MyBrand" --logo logo.png --deliverable "vehicle" --output ./mockups --ratio 16:9 Models: flash (default): gemini-2.5-flash-image - Fast, cost-effective pro: gemini-3-pro-image-preview - Quality, 4K text rendering Image Editing Mode: When --logo is provided, uses Gemini's text-and-image-to-image capability to incorporate your ACTUAL logo into the CIP mockups. """ ) parser.add_argument("--brand", "-b", required=True, help="Brand name") parser.add_argument("--logo", "-l", help="Path to brand logo image (enables image editing mode)") parser.add_argument("--deliverable", "-d", help="Single deliverable to generate") parser.add_argument("--deliverables", help="Comma-separated list of deliverables") parser.add_argument("--industry", "-i", default="technology", help="Industry type") parser.add_argument("--style", "-s", help="Design style") parser.add_argument("--mockup", "-m", help="Mockup context") parser.add_argument("--set", action="store_true", help="Generate full CIP set") parser.add_argument("--output", "-o", help="Output directory") parser.add_argument("--model", default="flash", choices=["flash", "pro"], help="Model: flash (fast) or pro (quality)") parser.add_argument("--ratio", default="1:1", help="Aspect ratio (1:1, 16:9, 4:3, etc.)") parser.add_argument("--prompt-only", action="store_true", help="Only show prompt, don't generate") parser.add_argument("--json", "-j", action="store_true", help="Output as JSON") parser.add_argument("--no-logo-prompt", action="store_true", help="Skip logo prompt, proceed without logo") args = parser.parse_args() # Check if logo is provided, prompt user if not logo_image = None if args.logo: logo_image = load_logo_image(args.logo) if not logo_image: print("Error: Could not load logo image") sys.exit(1) elif not args.prompt_only: # No logo provided - ask user what to do action = check_logo_required(args.brand, skip_prompt=args.no_logo_prompt) if action == 'generate': print("\n💡 To generate a logo, use the logo-design skill:") print(f" python ~/.claude/skills/design/scripts/logo/generate.py --brand \"{args.brand}\" --industry \"{args.industry}\"") print("\n Then re-run this command with --logo <generated_logo.png>") sys.exit(0) elif action == 'exit': print("\n Provide logo with: --logo /path/to/your/logo.png") sys.exit(0) # else: continue without logo use_logo = logo_image is not None if args.set or args.deliverables: # Generate multiple deliverables deliverables = args.deliverables.split(",") if args.deliverables else None if args.prompt_only: results = [] deliverables = deliverables or ["business card", "letterhead", "office signage", "vehicle", "polo shirt"] for d in deliverables: prompt_data = build_cip_prompt(d, args.brand, args.style, args.industry, args.mockup, use_logo_image=use_logo) results.append(prompt_data) if args.json: print(json.dumps(results, indent=2)) else: for r in results: print(f"\n{r['deliverable']}:\n{r['prompt']}\n") else: results = generate_cip_set( args.brand, args.industry, args.style, deliverables, args.output, model_key=args.model, logo_path=args.logo, aspect_ratio=args.ratio ) if args.json: print(json.dumps(results, indent=2)) else: print(f"\n✅ Generated {len(results)} CIP mockups") else: # Generate single deliverable deliverable = args.deliverable or "business card" prompt_data = build_cip_prompt(deliverable, args.brand, args.style, args.industry, args.mockup, use_logo_image=use_logo) if args.prompt_only: if args.json: print(json.dumps(prompt_data, indent=2)) else: print(f"\nPrompt:\n{prompt_data['prompt']}") else: filepath = generate_with_nano_banana( prompt_data, args.output, model_key=args.model, aspect_ratio=args.ratio, logo_image=logo_image ) if args.json: print(json.dumps({"filepath": filepath, **prompt_data}, indent=2)) if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,18 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +CIP Design Generator - Generate corporate identity mockups using Gemini Nano Banana + +Uses Gemini's native image generation (Nano Banana Flash/Pro) for high-quality mockups. +Supports text-and-image-to-image generation for using actual brand logos. + +- gemini-2.5-flash-image: Fast generation, cost-effective (default) +- gemini-3-pro-image-preview: Pro quality, 4K text rendering + +Image Editing (text-and-image-to-image): + When --logo is provided, the script uses Gemini's image editing capability + to incorporate the actual logo into CIP mockups instead of generating one. +""" import argparse import json @@ -21,6 +34,7 @@ def load_logo_image(logo_path): + """Load logo image using PIL for Gemini image editing""" try: from PIL import Image except ImportError: @@ -53,6 +67,7 @@ # Load environment variables def load_env(): + """Load environment variables from .env files""" env_paths = [ Path(__file__).parent.parent.parent / ".env", Path.home() / ".claude" / "skills" / ".env", @@ -72,6 +87,16 @@ def build_cip_prompt(deliverable, brand_name, style=None, industry=None, mockup=None, use_logo_image=False): + """Build an optimized prompt for CIP mockup generation + + Args: + deliverable: Type of deliverable (business card, letterhead, etc.) + brand_name: Name of the brand + style: Design style preference + industry: Industry for style recommendations + mockup: Mockup context override + use_logo_image: If True, prompt is optimized for image editing with logo + """ # Get deliverable details deliverable_info = search(deliverable, "deliverable", 1) @@ -159,6 +184,23 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", aspect_ratio="1:1", logo_image=None): + """Generate image using Gemini Nano Banana (native image generation) + + Supports two modes: + 1. Text-to-image: Pure prompt-based generation (logo_image=None) + 2. Image editing: Text-and-image-to-image using provided logo (logo_image=PIL.Image) + + Models: + - flash: gemini-2.5-flash-image (fast, cost-effective) - DEFAULT + - pro: gemini-3-pro-image-preview (quality, 4K text rendering) + + Args: + prompt_data: Dict with prompt, deliverable, brand, etc. + output_dir: Output directory for generated images + model_key: 'flash' or 'pro' + aspect_ratio: Output aspect ratio (1:1, 16:9, etc.) + logo_image: PIL.Image object of the brand logo for image editing mode + """ try: from google import genai from google.genai import types @@ -242,6 +284,18 @@ def generate_cip_set(brand_name, industry, style=None, deliverables=None, output_dir=None, model_key="flash", logo_path=None, aspect_ratio="1:1"): + """Generate a complete CIP set for a brand + + Args: + brand_name: Brand name to generate for + industry: Industry type for style recommendations + style: Optional specific style override + deliverables: List of deliverables to generate (default: core set) + output_dir: Output directory for images + model_key: 'flash' (fast) or 'pro' (quality) + logo_path: Path to brand logo image for image editing mode + aspect_ratio: Output aspect ratio + """ # Load logo image if provided logo_image = None @@ -285,6 +339,11 @@ def check_logo_required(brand_name, skip_prompt=False): + """Check if logo is required and suggest logo-design skill if not provided + + Returns: + str: 'continue' to proceed without logo, 'generate' to use logo-design skill, 'exit' to abort + """ if skip_prompt: return 'continue' @@ -422,4 +481,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/generate.py
Add inline docstrings for readability
#!/usr/bin/env python3 import argparse import json import subprocess import sys from pathlib import Path from typing import List, Optional class ShadcnInstaller: def __init__(self, project_root: Optional[Path] = None, dry_run: bool = False): self.project_root = project_root or Path.cwd() self.dry_run = dry_run self.components_json = self.project_root / "components.json" def check_shadcn_config(self) -> bool: return self.components_json.exists() def get_installed_components(self) -> List[str]: if not self.check_shadcn_config(): return [] try: with open(self.components_json) as f: config = json.load(f) components_dir = self.project_root / config.get("aliases", {}).get( "components", "components" ).replace("@/", "") ui_dir = components_dir / "ui" if not ui_dir.exists(): return [] return [f.stem for f in ui_dir.glob("*.tsx") if f.is_file()] except (json.JSONDecodeError, KeyError, OSError): return [] def add_components( self, components: List[str], overwrite: bool = False ) -> tuple[bool, str]: if not components: return False, "No components specified" if not self.check_shadcn_config(): return ( False, "shadcn not initialized. Run 'npx shadcn@latest init' first", ) # Check which components already exist installed = self.get_installed_components() already_installed = [c for c in components if c in installed] if already_installed and not overwrite: return ( False, f"Components already installed: {', '.join(already_installed)}. " "Use --overwrite to reinstall", ) # Build command cmd = ["npx", "shadcn@latest", "add"] + components if overwrite: cmd.append("--overwrite") if self.dry_run: return True, f"Would run: {' '.join(cmd)}" # Execute command try: result = subprocess.run( cmd, cwd=self.project_root, capture_output=True, text=True, check=True, ) success_msg = f"Successfully added components: {', '.join(components)}" if result.stdout: success_msg += f"\n\nOutput:\n{result.stdout}" return True, success_msg except subprocess.CalledProcessError as e: error_msg = f"Failed to add components: {e.stderr or e.stdout or str(e)}" return False, error_msg except FileNotFoundError: return False, "npx not found. Ensure Node.js is installed" def add_all_components(self, overwrite: bool = False) -> tuple[bool, str]: if not self.check_shadcn_config(): return ( False, "shadcn not initialized. Run 'npx shadcn@latest init' first", ) cmd = ["npx", "shadcn@latest", "add", "--all"] if overwrite: cmd.append("--overwrite") if self.dry_run: return True, f"Would run: {' '.join(cmd)}" try: result = subprocess.run( cmd, cwd=self.project_root, capture_output=True, text=True, check=True, ) success_msg = "Successfully added all components" if result.stdout: success_msg += f"\n\nOutput:\n{result.stdout}" return True, success_msg except subprocess.CalledProcessError as e: error_msg = f"Failed to add all components: {e.stderr or e.stdout or str(e)}" return False, error_msg except FileNotFoundError: return False, "npx not found. Ensure Node.js is installed" def list_installed(self) -> tuple[bool, str]: if not self.check_shadcn_config(): return False, "shadcn not initialized" installed = self.get_installed_components() if not installed: return True, "No components installed" return True, f"Installed components:\n" + "\n".join(f" - {c}" for c in sorted(installed)) def main(): parser = argparse.ArgumentParser( description="Add shadcn/ui components to your project", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Add single component python shadcn_add.py button # Add multiple components python shadcn_add.py button card dialog # Add all components python shadcn_add.py --all # Overwrite existing components python shadcn_add.py button --overwrite # Dry run (show what would be done) python shadcn_add.py button card --dry-run # List installed components python shadcn_add.py --list """, ) parser.add_argument( "components", nargs="*", help="Component names to add (e.g., button, card, dialog)", ) parser.add_argument( "--all", action="store_true", help="Add all available components", ) parser.add_argument( "--overwrite", action="store_true", help="Overwrite existing components", ) parser.add_argument( "--dry-run", action="store_true", help="Show what would be done without executing", ) parser.add_argument( "--list", action="store_true", help="List installed components", ) parser.add_argument( "--project-root", type=Path, help="Project root directory (default: current directory)", ) args = parser.parse_args() # Initialize installer installer = ShadcnInstaller( project_root=args.project_root, dry_run=args.dry_run, ) # Handle list command if args.list: success, message = installer.list_installed() print(message) sys.exit(0 if success else 1) # Handle add all command if args.all: success, message = installer.add_all_components(overwrite=args.overwrite) print(message) sys.exit(0 if success else 1) # Handle add specific components if not args.components: parser.print_help() sys.exit(1) success, message = installer.add_components( args.components, overwrite=args.overwrite, ) print(message) sys.exit(0 if success else 1) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +shadcn/ui Component Installer + +Add shadcn/ui components to project with automatic dependency handling. +Wraps shadcn CLI for programmatic component installation. +""" import argparse import json @@ -9,16 +15,36 @@ class ShadcnInstaller: + """Handle shadcn/ui component installation.""" def __init__(self, project_root: Optional[Path] = None, dry_run: bool = False): + """ + Initialize installer. + + Args: + project_root: Project root directory (default: current directory) + dry_run: If True, show actions without executing + """ self.project_root = project_root or Path.cwd() self.dry_run = dry_run self.components_json = self.project_root / "components.json" def check_shadcn_config(self) -> bool: + """ + Check if shadcn is initialized in project. + + Returns: + True if components.json exists + """ return self.components_json.exists() def get_installed_components(self) -> List[str]: + """ + Get list of already installed components. + + Returns: + List of installed component names + """ if not self.check_shadcn_config(): return [] @@ -41,6 +67,16 @@ def add_components( self, components: List[str], overwrite: bool = False ) -> tuple[bool, str]: + """ + Add shadcn/ui components. + + Args: + components: List of component names to add + overwrite: If True, overwrite existing components + + Returns: + Tuple of (success, message) + """ if not components: return False, "No components specified" @@ -93,6 +129,15 @@ return False, "npx not found. Ensure Node.js is installed" def add_all_components(self, overwrite: bool = False) -> tuple[bool, str]: + """ + Add all available shadcn/ui components. + + Args: + overwrite: If True, overwrite existing components + + Returns: + Tuple of (success, message) + """ if not self.check_shadcn_config(): return ( False, @@ -129,6 +174,12 @@ return False, "npx not found. Ensure Node.js is installed" def list_installed(self) -> tuple[bool, str]: + """ + List installed components. + + Returns: + Tuple of (success, message with component list) + """ if not self.check_shadcn_config(): return False, "shadcn not initialized" @@ -141,6 +192,7 @@ def main(): + """CLI entry point.""" parser = argparse.ArgumentParser( description="Add shadcn/ui components to your project", formatter_class=argparse.RawDescriptionHelpFormatter, @@ -237,4 +289,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/ui-styling/scripts/shadcn_add.py
Generate descriptive docstrings automatically
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import json from pathlib import Path from datetime import datetime # Paths SCRIPT_DIR = Path(__file__).parent DATA_DIR = SCRIPT_DIR.parent / "data" TOKENS_CSS = Path(__file__).resolve().parents[4] / "assets" / "design-tokens.css" TOKENS_JSON = Path(__file__).resolve().parents[4] / "assets" / "design-tokens.json" OUTPUT_DIR = Path(__file__).resolve().parents[4] / "assets" / "designs" / "slides" # ============ BRAND-COMPLIANT SLIDE TEMPLATE ============ # ALL values reference CSS variables from design-tokens.css SLIDE_TEMPLATE = '''<!DOCTYPE html> <html lang="en" data-theme="dark"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{title}</title> <!-- Brand Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet"> <!-- Design Tokens - SINGLE SOURCE OF TRUTH --> <link rel="stylesheet" href="{tokens_css_path}"> <style> /* ============================================ STRICT TOKEN USAGE - NO HARDCODED VALUES All styles MUST use var(--token-name) ============================================ */ * {{ margin: 0; padding: 0; box-sizing: border-box; }} html, body {{ width: 100%; height: 100%; }} body {{ font-family: var(--typography-font-body); background: var(--color-background); color: var(--color-foreground); line-height: var(--primitive-lineHeight-relaxed); }} /* Slide Container - 16:9 aspect ratio */ .slide-deck {{ width: 100%; max-width: 1920px; margin: 0 auto; }} .slide {{ width: 100%; aspect-ratio: 16 / 9; padding: var(--slide-padding); background: var(--slide-bg); display: flex; flex-direction: column; position: relative; overflow: hidden; }} .slide + .slide {{ margin-top: var(--primitive-spacing-8); }} /* Background Variants */ .slide--surface {{ background: var(--slide-bg-surface); }} .slide--gradient {{ background: var(--slide-bg-gradient); }} .slide--glow::before {{ content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 150%; height: 150%; background: var(--primitive-gradient-glow); pointer-events: none; }} /* Typography - MUST use token fonts and sizes */ h1, h2, h3, h4, h5, h6 {{ font-family: var(--typography-font-heading); font-weight: var(--primitive-fontWeight-bold); line-height: var(--primitive-lineHeight-tight); }} .slide-title {{ font-size: var(--slide-title-size); background: var(--primitive-gradient-primary); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }} .slide-heading {{ font-size: var(--slide-heading-size); color: var(--color-foreground); }} .slide-subheading {{ font-size: var(--primitive-fontSize-3xl); color: var(--color-foreground-secondary); font-weight: var(--primitive-fontWeight-medium); }} .slide-body {{ font-size: var(--slide-body-size); color: var(--color-foreground-secondary); max-width: 80ch; }} /* Brand Colors - Primary/Secondary/Accent */ .text-primary {{ color: var(--color-primary); }} .text-secondary {{ color: var(--color-secondary); }} .text-accent {{ color: var(--color-accent); }} .text-muted {{ color: var(--color-foreground-muted); }} .bg-primary {{ background: var(--color-primary); }} .bg-secondary {{ background: var(--color-secondary); }} .bg-accent {{ background: var(--color-accent); }} .bg-surface {{ background: var(--color-surface); }} /* Cards - Using component tokens */ .card {{ background: var(--card-bg); border: 1px solid var(--card-border); border-radius: var(--card-radius); padding: var(--card-padding); box-shadow: var(--card-shadow); transition: border-color var(--primitive-duration-base) var(--primitive-easing-out); }} .card:hover {{ border-color: var(--card-border-hover); }} /* Buttons - Using component tokens */ .btn {{ display: inline-flex; align-items: center; justify-content: center; padding: var(--button-primary-padding-y) var(--button-primary-padding-x); border-radius: var(--button-primary-radius); font-size: var(--button-primary-font-size); font-weight: var(--button-primary-font-weight); font-family: var(--typography-font-body); text-decoration: none; cursor: pointer; border: none; transition: all var(--primitive-duration-base) var(--primitive-easing-out); }} .btn-primary {{ background: var(--button-primary-bg); color: var(--button-primary-fg); box-shadow: var(--button-primary-shadow); }} .btn-primary:hover {{ background: var(--button-primary-bg-hover); }} .btn-secondary {{ background: transparent; color: var(--color-primary); border: 2px solid var(--color-primary); }} /* Layout Utilities */ .flex {{ display: flex; }} .flex-col {{ flex-direction: column; }} .items-center {{ align-items: center; }} .justify-center {{ justify-content: center; }} .justify-between {{ justify-content: space-between; }} .gap-4 {{ gap: var(--primitive-spacing-4); }} .gap-6 {{ gap: var(--primitive-spacing-6); }} .gap-8 {{ gap: var(--primitive-spacing-8); }} .grid {{ display: grid; }} .grid-2 {{ grid-template-columns: repeat(2, 1fr); }} .grid-3 {{ grid-template-columns: repeat(3, 1fr); }} .grid-4 {{ grid-template-columns: repeat(4, 1fr); }} .text-center {{ text-align: center; }} .mt-auto {{ margin-top: auto; }} .mb-4 {{ margin-bottom: var(--primitive-spacing-4); }} .mb-6 {{ margin-bottom: var(--primitive-spacing-6); }} .mb-8 {{ margin-bottom: var(--primitive-spacing-8); }} /* Metric Cards */ .metric {{ text-align: center; padding: var(--primitive-spacing-6); }} .metric-value {{ font-family: var(--typography-font-heading); font-size: var(--primitive-fontSize-6xl); font-weight: var(--primitive-fontWeight-bold); background: var(--primitive-gradient-primary); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }} .metric-label {{ font-size: var(--primitive-fontSize-lg); color: var(--color-foreground-secondary); margin-top: var(--primitive-spacing-2); }} /* Feature List */ .feature-item {{ display: flex; align-items: flex-start; gap: var(--primitive-spacing-4); padding: var(--primitive-spacing-4) 0; }} .feature-icon {{ width: 48px; height: 48px; border-radius: var(--primitive-radius-lg); background: var(--color-surface-elevated); display: flex; align-items: center; justify-content: center; color: var(--color-primary); font-size: var(--primitive-fontSize-xl); flex-shrink: 0; }} .feature-content h4 {{ font-size: var(--primitive-fontSize-xl); color: var(--color-foreground); margin-bottom: var(--primitive-spacing-2); }} .feature-content p {{ color: var(--color-foreground-secondary); font-size: var(--primitive-fontSize-base); }} /* Testimonial */ .testimonial {{ background: var(--color-surface); border-radius: var(--primitive-radius-xl); padding: var(--primitive-spacing-8); border-left: 4px solid var(--color-primary); }} .testimonial-quote {{ font-size: var(--primitive-fontSize-2xl); color: var(--color-foreground); font-style: italic; margin-bottom: var(--primitive-spacing-6); }} .testimonial-author {{ font-size: var(--primitive-fontSize-lg); color: var(--color-primary); font-weight: var(--primitive-fontWeight-semibold); }} .testimonial-role {{ font-size: var(--primitive-fontSize-base); color: var(--color-foreground-muted); }} /* Badge/Tag */ .badge {{ display: inline-block; padding: var(--primitive-spacing-2) var(--primitive-spacing-4); background: var(--color-surface-elevated); border-radius: var(--primitive-radius-full); font-size: var(--primitive-fontSize-sm); color: var(--color-accent); font-weight: var(--primitive-fontWeight-medium); }} /* Chart Container */ .chart-container {{ background: var(--color-surface); border-radius: var(--primitive-radius-xl); padding: var(--primitive-spacing-6); height: 100%; display: flex; flex-direction: column; }} .chart-title {{ font-family: var(--typography-font-heading); font-size: var(--primitive-fontSize-xl); color: var(--color-foreground); margin-bottom: var(--primitive-spacing-4); }} /* CSS-only Bar Chart */ .bar-chart {{ display: flex; align-items: flex-end; gap: var(--primitive-spacing-4); height: 200px; padding-top: var(--primitive-spacing-4); }} .bar {{ flex: 1; background: var(--primitive-gradient-primary); border-radius: var(--primitive-radius-md) var(--primitive-radius-md) 0 0; position: relative; min-width: 40px; }} .bar-label {{ position: absolute; bottom: -30px; left: 50%; transform: translateX(-50%); font-size: var(--primitive-fontSize-sm); color: var(--color-foreground-muted); white-space: nowrap; }} .bar-value {{ position: absolute; top: -25px; left: 50%; transform: translateX(-50%); font-size: var(--primitive-fontSize-sm); color: var(--color-foreground); font-weight: var(--primitive-fontWeight-semibold); }} /* Progress Bar */ .progress {{ height: 12px; background: var(--color-surface-elevated); border-radius: var(--primitive-radius-full); overflow: hidden; }} .progress-fill {{ height: 100%; background: var(--primitive-gradient-primary); border-radius: var(--primitive-radius-full); }} /* Footer */ .slide-footer {{ margin-top: auto; display: flex; justify-content: space-between; align-items: center; padding-top: var(--primitive-spacing-6); border-top: 1px solid var(--color-border); color: var(--color-foreground-muted); font-size: var(--primitive-fontSize-sm); }} /* Glow Effects */ .glow-coral {{ box-shadow: var(--primitive-shadow-glow-coral); }} .glow-purple {{ box-shadow: var(--primitive-shadow-glow-purple); }} .glow-mint {{ box-shadow: var(--primitive-shadow-glow-mint); }} </style> </head> <body> <div class="slide-deck"> {slides_content} </div> </body> </html> ''' # ============ SLIDE GENERATORS ============ def generate_title_slide(data): return f''' <section class="slide slide--glow flex flex-col items-center justify-center text-center"> <div class="badge mb-6">{data.get('badge', 'Pitch Deck')}</div> <h1 class="slide-title mb-6">{data.get('title', 'Your Title Here')}</h1> <p class="slide-subheading mb-8">{data.get('subtitle', 'Your compelling subtitle')}</p> <div class="flex gap-4"> <a href="#" class="btn btn-primary">{data.get('cta', 'Get Started')}</a> <a href="#" class="btn btn-secondary">{data.get('secondary_cta', 'Learn More')}</a> </div> <div class="slide-footer"> <span>{data.get('company', 'Company Name')}</span> <span>{data.get('date', datetime.now().strftime('%B %Y'))}</span> </div> </section> ''' def generate_problem_slide(data): return f''' <section class="slide slide--surface"> <div class="badge mb-6">The Problem</div> <h2 class="slide-heading mb-8">{data.get('headline', 'The problem your audience faces')}</h2> <div class="grid grid-3 gap-8"> <div class="card"> <div class="text-primary" style="font-size: var(--primitive-fontSize-4xl); margin-bottom: var(--primitive-spacing-4);">01</div> <h4 style="margin-bottom: var(--primitive-spacing-2); font-size: var(--primitive-fontSize-xl);">{data.get('pain_1_title', 'Pain Point 1')}</h4> <p class="text-muted">{data.get('pain_1_desc', 'Description of the first pain point')}</p> </div> <div class="card"> <div class="text-secondary" style="font-size: var(--primitive-fontSize-4xl); margin-bottom: var(--primitive-spacing-4);">02</div> <h4 style="margin-bottom: var(--primitive-spacing-2); font-size: var(--primitive-fontSize-xl);">{data.get('pain_2_title', 'Pain Point 2')}</h4> <p class="text-muted">{data.get('pain_2_desc', 'Description of the second pain point')}</p> </div> <div class="card"> <div class="text-accent" style="font-size: var(--primitive-fontSize-4xl); margin-bottom: var(--primitive-spacing-4);">03</div> <h4 style="margin-bottom: var(--primitive-spacing-2); font-size: var(--primitive-fontSize-xl);">{data.get('pain_3_title', 'Pain Point 3')}</h4> <p class="text-muted">{data.get('pain_3_desc', 'Description of the third pain point')}</p> </div> </div> <div class="slide-footer"> <span>{data.get('company', 'Company Name')}</span> <span>{data.get('page', '2')}</span> </div> </section> ''' def generate_solution_slide(data): return f''' <section class="slide"> <div class="badge mb-6">The Solution</div> <h2 class="slide-heading mb-8">{data.get('headline', 'How we solve this')}</h2> <div class="flex gap-8" style="flex: 1;"> <div style="flex: 1;"> <div class="feature-item"> <div class="feature-icon">&#10003;</div> <div class="feature-content"> <h4>{data.get('feature_1_title', 'Feature 1')}</h4> <p>{data.get('feature_1_desc', 'Description of feature 1')}</p> </div> </div> <div class="feature-item"> <div class="feature-icon">&#10003;</div> <div class="feature-content"> <h4>{data.get('feature_2_title', 'Feature 2')}</h4> <p>{data.get('feature_2_desc', 'Description of feature 2')}</p> </div> </div> <div class="feature-item"> <div class="feature-icon">&#10003;</div> <div class="feature-content"> <h4>{data.get('feature_3_title', 'Feature 3')}</h4> <p>{data.get('feature_3_desc', 'Description of feature 3')}</p> </div> </div> </div> <div style="flex: 1;" class="card flex items-center justify-center"> <div class="text-center"> <div class="text-accent" style="font-size: 80px; margin-bottom: var(--primitive-spacing-4);">&#9670;</div> <p class="text-muted">Product screenshot or demo</p> </div> </div> </div> <div class="slide-footer"> <span>{data.get('company', 'Company Name')}</span> <span>{data.get('page', '3')}</span> </div> </section> ''' def generate_metrics_slide(data): metrics = data.get('metrics', [ {'value': '10K+', 'label': 'Active Users'}, {'value': '95%', 'label': 'Retention Rate'}, {'value': '3x', 'label': 'Revenue Growth'}, {'value': '$2M', 'label': 'ARR'} ]) metrics_html = ''.join([f''' <div class="card metric"> <div class="metric-value">{m['value']}</div> <div class="metric-label">{m['label']}</div> </div> ''' for m in metrics[:4]]) return f''' <section class="slide slide--surface slide--glow"> <div class="badge mb-6">Traction</div> <h2 class="slide-heading mb-8 text-center">{data.get('headline', 'Our Growth')}</h2> <div class="grid grid-4 gap-6" style="flex: 1; align-items: center;"> {metrics_html} </div> <div class="slide-footer"> <span>{data.get('company', 'Company Name')}</span> <span>{data.get('page', '4')}</span> </div> </section> ''' def generate_chart_slide(data): bars = data.get('bars', [ {'label': 'Q1', 'value': 40}, {'label': 'Q2', 'value': 60}, {'label': 'Q3', 'value': 80}, {'label': 'Q4', 'value': 100} ]) bars_html = ''.join([f''' <div class="bar" style="height: {b['value']}%;"> <span class="bar-value">{b.get('display', str(b['value']) + '%')}</span> <span class="bar-label">{b['label']}</span> </div> ''' for b in bars]) return f''' <section class="slide"> <div class="badge mb-6">{data.get('badge', 'Growth')}</div> <h2 class="slide-heading mb-8">{data.get('headline', 'Revenue Growth')}</h2> <div class="chart-container" style="flex: 1;"> <div class="chart-title">{data.get('chart_title', 'Quarterly Revenue')}</div> <div class="bar-chart" style="flex: 1; padding-bottom: 40px;"> {bars_html} </div> </div> <div class="slide-footer"> <span>{data.get('company', 'Company Name')}</span> <span>{data.get('page', '5')}</span> </div> </section> ''' def generate_testimonial_slide(data): return f''' <section class="slide slide--surface flex flex-col justify-center"> <div class="badge mb-6">What They Say</div> <div class="testimonial" style="max-width: 900px;"> <p class="testimonial-quote">"{data.get('quote', 'This product changed how we work. Incredible results.')}"</p> <p class="testimonial-author">{data.get('author', 'Jane Doe')}</p> <p class="testimonial-role">{data.get('role', 'CEO, Example Company')}</p> </div> <div class="slide-footer"> <span>{data.get('company', 'Company Name')}</span> <span>{data.get('page', '6')}</span> </div> </section> ''' def generate_cta_slide(data): return f''' <section class="slide slide--gradient flex flex-col items-center justify-center text-center"> <h2 class="slide-heading mb-6" style="color: var(--color-foreground);">{data.get('headline', 'Ready to get started?')}</h2> <p class="slide-body mb-8" style="color: rgba(255,255,255,0.8);">{data.get('subheadline', 'Join thousands of teams already using our solution.')}</p> <div class="flex gap-4"> <a href="{data.get('cta_url', '#')}" class="btn" style="background: var(--color-foreground); color: var(--color-primary);">{data.get('cta', 'Start Free Trial')}</a> </div> <div class="slide-footer" style="border-color: rgba(255,255,255,0.2); color: rgba(255,255,255,0.6);"> <span>{data.get('contact', 'contact@example.com')}</span> <span>{data.get('website', 'www.example.com')}</span> </div> </section> ''' # Slide type mapping SLIDE_GENERATORS = { 'title': generate_title_slide, 'problem': generate_problem_slide, 'solution': generate_solution_slide, 'metrics': generate_metrics_slide, 'traction': generate_metrics_slide, 'chart': generate_chart_slide, 'testimonial': generate_testimonial_slide, 'cta': generate_cta_slide, 'closing': generate_cta_slide } def generate_deck(slides_data, title="Pitch Deck"): slides_html = "" for slide in slides_data: slide_type = slide.get('type', 'title') generator = SLIDE_GENERATORS.get(slide_type) if generator: slides_html += generator(slide) else: print(f"Warning: Unknown slide type '{slide_type}'") # Calculate relative path to tokens CSS tokens_rel_path = "../../../assets/design-tokens.css" return SLIDE_TEMPLATE.format( title=title, tokens_css_path=tokens_rel_path, slides_content=slides_html ) def main(): parser = argparse.ArgumentParser(description="Generate brand-compliant slides") parser.add_argument("--json", "-j", help="JSON file with slide data") parser.add_argument("--output", "-o", help="Output HTML file path") parser.add_argument("--demo", action="store_true", help="Generate demo deck") args = parser.parse_args() if args.demo: # Demo deck showcasing all slide types demo_slides = [ { 'type': 'title', 'badge': 'Investor Deck 2024', 'title': 'ClaudeKit Marketing', 'subtitle': 'Your AI marketing team. Always on.', 'cta': 'Join Waitlist', 'secondary_cta': 'See Demo', 'company': 'ClaudeKit', 'date': 'December 2024' }, { 'type': 'problem', 'headline': 'Marketing teams are drowning', 'pain_1_title': 'Content Overload', 'pain_1_desc': 'Need to produce 10x content with same headcount', 'pain_2_title': 'Tool Fatigue', 'pain_2_desc': '15+ tools that don\'t talk to each other', 'pain_3_title': 'No Time to Think', 'pain_3_desc': 'Strategy suffers when execution consumes all hours', 'company': 'ClaudeKit', 'page': '2' }, { 'type': 'solution', 'headline': 'AI agents that actually get marketing', 'feature_1_title': 'Content Creation', 'feature_1_desc': 'Blog posts, social, email - all on brand, all on time', 'feature_2_title': 'Campaign Management', 'feature_2_desc': 'Multi-channel orchestration with one command', 'feature_3_title': 'Analytics & Insights', 'feature_3_desc': 'Real-time optimization without the spreadsheets', 'company': 'ClaudeKit', 'page': '3' }, { 'type': 'metrics', 'headline': 'Early traction speaks volumes', 'metrics': [ {'value': '500+', 'label': 'Beta Users'}, {'value': '85%', 'label': 'Weekly Active'}, {'value': '4.9', 'label': 'NPS Score'}, {'value': '50hrs', 'label': 'Saved/Week'} ], 'company': 'ClaudeKit', 'page': '4' }, { 'type': 'chart', 'badge': 'Revenue', 'headline': 'Growing month over month', 'chart_title': 'MRR Growth ($K)', 'bars': [ {'label': 'Sep', 'value': 20, 'display': '$5K'}, {'label': 'Oct', 'value': 40, 'display': '$12K'}, {'label': 'Nov', 'value': 70, 'display': '$28K'}, {'label': 'Dec', 'value': 100, 'display': '$45K'} ], 'company': 'ClaudeKit', 'page': '5' }, { 'type': 'testimonial', 'quote': 'ClaudeKit replaced 3 tools and 2 contractors. Our content output tripled while costs dropped 60%.', 'author': 'Sarah Chen', 'role': 'Head of Marketing, TechStartup', 'company': 'ClaudeKit', 'page': '6' }, { 'type': 'cta', 'headline': 'Ship campaigns while you sleep', 'subheadline': 'Early access available. Limited spots.', 'cta': 'Join the Waitlist', 'contact': 'hello@claudekit.ai', 'website': 'claudekit.ai' } ] html = generate_deck(demo_slides, "ClaudeKit Marketing - Pitch Deck") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) output_path = OUTPUT_DIR / f"demo-pitch-{datetime.now().strftime('%y%m%d')}.html" output_path.write_text(html, encoding='utf-8') print(f"Demo deck generated: {output_path}") elif args.json: with open(args.json, 'r') as f: data = json.load(f) html = generate_deck(data.get('slides', []), data.get('title', 'Presentation')) output_path = Path(args.output) if args.output else OUTPUT_DIR / f"deck-{datetime.now().strftime('%y%m%d-%H%M')}.html" output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(html, encoding='utf-8') print(f"Deck generated: {output_path}") else: parser.print_help() if __name__ == "__main__": main()
--- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Slide Generator - Generates HTML slides using design tokens +ALL styles MUST use CSS variables from design-tokens.css +NO hardcoded colors, fonts, or spacing allowed +""" import argparse import json @@ -404,6 +409,7 @@ # ============ SLIDE GENERATORS ============ def generate_title_slide(data): + """Title slide with gradient headline""" return f''' <section class="slide slide--glow flex flex-col items-center justify-center text-center"> <div class="badge mb-6">{data.get('badge', 'Pitch Deck')}</div> @@ -422,6 +428,7 @@ def generate_problem_slide(data): + """Problem statement slide using PAS formula""" return f''' <section class="slide slide--surface"> <div class="badge mb-6">The Problem</div> @@ -452,6 +459,7 @@ def generate_solution_slide(data): + """Solution slide with feature highlights""" return f''' <section class="slide"> <div class="badge mb-6">The Solution</div> @@ -496,6 +504,7 @@ def generate_metrics_slide(data): + """Traction/metrics slide with large numbers""" metrics = data.get('metrics', [ {'value': '10K+', 'label': 'Active Users'}, {'value': '95%', 'label': 'Retention Rate'}, @@ -526,6 +535,7 @@ def generate_chart_slide(data): + """Chart slide with CSS bar chart""" bars = data.get('bars', [ {'label': 'Q1', 'value': 40}, {'label': 'Q2', 'value': 60}, @@ -559,6 +569,7 @@ def generate_testimonial_slide(data): + """Social proof slide""" return f''' <section class="slide slide--surface flex flex-col justify-center"> <div class="badge mb-6">What They Say</div> @@ -576,6 +587,7 @@ def generate_cta_slide(data): + """Closing CTA slide""" return f''' <section class="slide slide--gradient flex flex-col items-center justify-center text-center"> <h2 class="slide-heading mb-6" style="color: var(--color-foreground);">{data.get('headline', 'Ready to get started?')}</h2> @@ -606,6 +618,7 @@ def generate_deck(slides_data, title="Pitch Deck"): + """Generate complete deck from slide data list""" slides_html = "" for slide in slides_data: slide_type = slide.get('type', 'title') @@ -737,4 +750,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/generate-slide.py
Add docstrings for internal functions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import re from pathlib import Path from math import log from collections import defaultdict # ============ CONFIGURATION ============ DATA_DIR = Path(__file__).parent.parent.parent / "data" / "logo" MAX_RESULTS = 3 CSV_CONFIG = { "style": { "file": "styles.csv", "search_cols": ["Style Name", "Category", "Keywords", "Best For"], "output_cols": ["Style Name", "Category", "Keywords", "Primary Colors", "Secondary Colors", "Typography", "Effects", "Best For", "Avoid For", "Complexity", "Era"] }, "color": { "file": "colors.csv", "search_cols": ["Palette Name", "Category", "Keywords", "Psychology", "Best For"], "output_cols": ["Palette Name", "Category", "Keywords", "Primary Hex", "Secondary Hex", "Accent Hex", "Background Hex", "Text Hex", "Psychology", "Best For", "Avoid For"] }, "industry": { "file": "industries.csv", "search_cols": ["Industry", "Keywords", "Recommended Styles", "Mood"], "output_cols": ["Industry", "Keywords", "Recommended Styles", "Primary Colors", "Typography", "Common Symbols", "Mood", "Best Practices", "Avoid"] } } # ============ BM25 IMPLEMENTATION ============ class BM25: def __init__(self, k1=1.5, b=0.75): self.k1 = k1 self.b = b self.corpus = [] self.doc_lengths = [] self.avgdl = 0 self.idf = {} self.doc_freqs = defaultdict(int) self.N = 0 def tokenize(self, text): text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: return self.doc_lengths = [len(doc) for doc in self.corpus] self.avgdl = sum(self.doc_lengths) / self.N for doc in self.corpus: seen = set() for word in doc: if word not in seen: self.doc_freqs[word] += 1 seen.add(word) for word, freq in self.doc_freqs.items(): self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): query_tokens = self.tokenize(query) scores = [] for idx, doc in enumerate(self.corpus): score = 0 doc_len = self.doc_lengths[idx] term_freqs = defaultdict(int) for word in doc: term_freqs[word] += 1 for token in query_tokens: if token in self.idf: tf = term_freqs[token] idf = self.idf[token] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl) score += idf * numerator / denominator scores.append((idx, score)) return sorted(scores, key=lambda x: x[1], reverse=True) # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): if not filepath.exists(): return [] data = _load_csv(filepath) # Build documents from search columns documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data] # BM25 search bm25 = BM25() bm25.fit(documents) ranked = bm25.score(query) # Get top results with score > 0 results = [] for idx, score in ranked[:max_results]: if score > 0: row = data[idx] results.append({col: row.get(col, "") for col in output_cols if col in row}) return results def detect_domain(query): query_lower = query.lower() domain_keywords = { "style": ["style", "minimalist", "vintage", "modern", "retro", "geometric", "abstract", "emblem", "badge", "wordmark", "mascot", "luxury", "playful", "corporate"], "color": ["color", "palette", "hex", "#", "rgb", "blue", "red", "green", "gold", "warm", "cool", "vibrant", "pastel"], "industry": ["tech", "healthcare", "finance", "legal", "restaurant", "food", "fashion", "beauty", "education", "sports", "fitness", "real estate", "crypto", "gaming"] } scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()} best = max(scores, key=scores.get) return best if scores[best] > 0 else "style" def search(query, domain=None, max_results=MAX_RESULTS): if domain is None: domain = detect_domain(query) config = CSV_CONFIG.get(domain, CSV_CONFIG["style"]) filepath = DATA_DIR / config["file"] if not filepath.exists(): return {"error": f"File not found: {filepath}", "domain": domain} results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results) return { "domain": domain, "query": query, "file": config["file"], "count": len(results), "results": results } def search_all(query, max_results=2): all_results = {} for domain in CSV_CONFIG.keys(): result = search(query, domain, max_results) if result.get("results"): all_results[domain] = result["results"] return all_results
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Logo Design Core - BM25 search engine for logo design guidelines +""" import csv import re @@ -32,6 +35,7 @@ # ============ BM25 IMPLEMENTATION ============ class BM25: + """BM25 ranking algorithm for text search""" def __init__(self, k1=1.5, b=0.75): self.k1 = k1 @@ -44,10 +48,12 @@ self.N = 0 def tokenize(self, text): + """Lowercase, split, remove punctuation, filter short words""" text = re.sub(r'[^\w\s]', ' ', str(text).lower()) return [w for w in text.split() if len(w) > 2] def fit(self, documents): + """Build BM25 index from documents""" self.corpus = [self.tokenize(doc) for doc in documents] self.N = len(self.corpus) if self.N == 0: @@ -66,6 +72,7 @@ self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1) def score(self, query): + """Score all documents against query""" query_tokens = self.tokenize(query) scores = [] @@ -91,11 +98,13 @@ # ============ SEARCH FUNCTIONS ============ def _load_csv(filepath): + """Load CSV and return list of dicts""" with open(filepath, 'r', encoding='utf-8') as f: return list(csv.DictReader(f)) def _search_csv(filepath, search_cols, output_cols, query, max_results): + """Core search function using BM25""" if not filepath.exists(): return [] @@ -120,6 +129,7 @@ def detect_domain(query): + """Auto-detect the most relevant domain from query""" query_lower = query.lower() domain_keywords = { @@ -134,6 +144,7 @@ def search(query, domain=None, max_results=MAX_RESULTS): + """Main search function with auto-domain detection""" if domain is None: domain = detect_domain(query) @@ -155,9 +166,10 @@ def search_all(query, max_results=2): + """Search across all domains and combine results""" all_results = {} for domain in CSV_CONFIG.keys(): result = search(query, domain, max_results) if result.get("results"): all_results[domain] = result["results"] - return all_results+ return all_results
https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/logo/core.py
Provide clean and structured docstrings
# if someone hits a 404, redirect them to another location def send_http_302_temporary_redirect(cli, new_path): cli.reply(b"redirecting...", 302, headers={"Location": new_path}) def send_http_301_permanent_redirect(cli, new_path): cli.reply(b"redirecting...", 301, headers={"Location": new_path}) def send_errorpage_with_redirect_link(cli, new_path): cli.redirect(new_path, click=False, msg="this page has moved") def main(cli, vn, rem): print(f"this client just hit a 404: {cli.ip}") print(f"they were accessing this volume: /{vn.vpath}") print(f"and the original request-path (straight from the URL) was /{cli.vpath}") print(f"...which resolves to the following filesystem path: {vn.canonical(rem)}") new_path = "/foo/bar/" print(f"will now redirect the client to {new_path}") # uncomment one of these: send_http_302_temporary_redirect(cli, new_path) # send_http_301_permanent_redirect(cli, new_path) # send_errorpage_with_redirect_link(cli, new_path) return "true"
--- +++ @@ -2,18 +2,40 @@ def send_http_302_temporary_redirect(cli, new_path): + """ + replies with an HTTP 302, which is a temporary redirect; + "new_path" can be any of the following: + - "http://a.com/" would redirect to another website, + - "/foo/bar" would redirect to /foo/bar on the same server; + note the leading '/' in the location which is important + """ cli.reply(b"redirecting...", 302, headers={"Location": new_path}) def send_http_301_permanent_redirect(cli, new_path): + """ + replies with an HTTP 301, which is a permanent redirect; + otherwise identical to send_http_302_temporary_redirect + """ cli.reply(b"redirecting...", 301, headers={"Location": new_path}) def send_errorpage_with_redirect_link(cli, new_path): + """ + replies with a website explaining that the page has moved; + "new_path" must be an absolute location on the same server + but without a leading '/', so for example "foo/bar" + would redirect to "/foo/bar" + """ cli.redirect(new_path, click=False, msg="this page has moved") def main(cli, vn, rem): + """ + this is the function that gets called by copyparty; + note that vn.vpath and cli.vpath does not have a leading '/' + so we're adding the slash in the debug messages below + """ print(f"this client just hit a 404: {cli.ip}") print(f"they were accessing this volume: /{vn.vpath}") print(f"and the original request-path (straight from the URL) was /{cli.vpath}") @@ -27,4 +49,4 @@ # send_http_301_permanent_redirect(cli, new_path) # send_errorpage_with_redirect_link(cli, new_path) - return "true"+ return "true"
https://raw.githubusercontent.com/9001/copyparty/HEAD/bin/handlers/redirect.py
Generate descriptive docstrings automatically
# coding: utf-8 from __future__ import print_function, unicode_literals import socket import time import ipaddress from ipaddress import ( IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_address, ip_network, ) from .__init__ import MACOS, TYPE_CHECKING from .util import IP6_LL, IP64_LL, Daemon, Netdev, find_prefix, min_ex, spack if TYPE_CHECKING: from .svchub import SvcHub if True: # pylint: disable=using-constant-test from typing import Optional, Union if not hasattr(socket, "IPPROTO_IPV6"): setattr(socket, "IPPROTO_IPV6", 41) class NoIPs(Exception): pass class MC_Sck(object): def __init__( self, sck: socket.socket, nd: Netdev, grp: str, ip: str, net: Union[IPv4Network, IPv6Network], ): self.sck = sck self.idx = nd.idx self.name = nd.name self.grp = grp self.mreq = b"" self.ip = ip self.net = net self.ips = {ip: net} self.v6 = ":" in ip self.have4 = ":" not in ip self.have6 = ":" in ip class MCast(object): def __init__( self, hub: "SvcHub", Srv: type[MC_Sck], on: list[str], off: list[str], mc_grp_4: str, mc_grp_6: str, port: int, vinit: bool, ) -> None: self.hub = hub self.Srv = Srv self.args = hub.args self.asrv = hub.asrv self.log_func = hub.log self.on = on self.off = off self.grp4 = mc_grp_4 self.grp6 = mc_grp_6 self.port = port self.vinit = vinit self.srv: dict[socket.socket, MC_Sck] = {} # listening sockets self.sips: set[str] = set() # all listening ips (including failed attempts) self.ll_ok: set[str] = set() # fallback linklocal IPv4 and IPv6 addresses self.b2srv: dict[bytes, MC_Sck] = {} # binary-ip -> server socket self.b4: list[bytes] = [] # sorted list of binary-ips self.b6: list[bytes] = [] # sorted list of binary-ips self.cscache: dict[str, Optional[MC_Sck]] = {} # client ip -> server cache self.running = True def log(self, msg: str, c: Union[int, str] = 0) -> None: self.log_func("multicast", msg, c) def create_servers(self) -> list[str]: bound: list[str] = [] netdevs = self.hub.tcpsrv.netdevs blist = self.hub.tcpsrv.bound if self.args.http_no_tcp: blist = self.hub.tcpsrv.seen_eps ips = [x[0] for x in blist] if "::" in ips: ips = [x for x in ips if x != "::"] + list( [x.split("/")[0] for x in netdevs if ":" in x] ) ips.append("0.0.0.0") if "0.0.0.0" in ips: ips = [x for x in ips if x != "0.0.0.0"] + list( [x.split("/")[0] for x in netdevs if ":" not in x] ) ips = [x for x in ips if x not in ("::1", "127.0.0.1")] ips = find_prefix(ips, list(netdevs)) on = self.on[:] off = self.off[:] for lst in (on, off): for av in list(lst): try: arg_net = ip_network(av, False) except: arg_net = None for sk, sv in netdevs.items(): if arg_net: net_ip = ip_address(sk.split("/")[0]) if net_ip in arg_net and sk not in lst: lst.append(sk) if (av == str(sv.idx) or av == sv.name) and sk not in lst: lst.append(sk) if on: ips = [x for x in ips if x in on] elif off: ips = [x for x in ips if x not in off] if not self.grp4: ips = [x for x in ips if ":" in x] if not self.grp6: ips = [x for x in ips if ":" not in x] ips = list(set(ips)) all_selected = ips[:] # discard non-linklocal ipv6 ips = [x for x in ips if ":" not in x or x.startswith(IP6_LL)] if not ips: raise NoIPs() for ip in ips: v6 = ":" in ip netdev = netdevs[ip] if not netdev.idx: t = "using INADDR_ANY for ip [{}], netdev [{}]" if not self.srv and ip not in ["::", "0.0.0.0"]: self.log(t.format(ip, netdev), 3) ipv = socket.AF_INET6 if v6 else socket.AF_INET sck = socket.socket(ipv, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sck.settimeout(None) sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: # safe for this purpose; https://lwn.net/Articles/853637/ sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except: pass # most ipv6 clients expect multicast on linklocal ip only; # add a/aaaa records for the other nic IPs other_ips: set[str] = set() if v6: for nd in netdevs.values(): if nd.idx == netdev.idx and nd.ip in all_selected and ":" in nd.ip: other_ips.add(nd.ip) net = ipaddress.ip_network(ip, False) ip = ip.split("/")[0] srv = self.Srv(sck, netdev, self.grp6 if ":" in ip else self.grp4, ip, net) for oth_ip in other_ips: srv.ips[oth_ip.split("/")[0]] = ipaddress.ip_network(oth_ip, False) # gvfs breaks if a linklocal ip appears in a dns reply ll = {k: v for k, v in srv.ips.items() if k.startswith(IP64_LL)} rt = {k: v for k, v in srv.ips.items() if k not in ll} if self.args.ll or not rt: self.ll_ok.update(list(ll)) if not self.args.ll: srv.ips = rt or ll if not srv.ips: self.log("no IPs on {}; skipping [{}]".format(netdev, ip), 3) continue try: self.setup_socket(srv) self.srv[sck] = srv bound.append(ip) except: t = "announce failed on {} [{}]:\n{}" self.log(t.format(netdev, ip, min_ex()), 3) sck.close() if self.args.zm_msub: for s1 in self.srv.values(): for s2 in self.srv.values(): if s1.idx != s2.idx: continue if s1.ip not in s2.ips: s2.ips[s1.ip] = s1.net if self.args.zm_mnic: for s1 in self.srv.values(): for s2 in self.srv.values(): for ip1, net1 in list(s1.ips.items()): for ip2, net2 in list(s2.ips.items()): if net1 == net2 and ip1 != ip2: s1.ips[ip2] = net2 self.sips = set([x.split("/")[0] for x in all_selected]) for srv in self.srv.values(): assert srv.ip in self.sips Daemon(self.hopper, "mc-hop") return bound def setup_socket(self, srv: MC_Sck) -> None: sck = srv.sck if srv.v6: if self.vinit: zsl = list(srv.ips.keys()) self.log("v6({}) idx({}) {}".format(srv.ip, srv.idx, zsl), 6) for ip in srv.ips: bip = socket.inet_pton(socket.AF_INET6, ip) self.b2srv[bip] = srv self.b6.append(bip) grp = self.grp6 if srv.idx else "" try: if MACOS: raise Exception() sck.bind((grp, self.port, 0, srv.idx)) except: sck.bind(("", self.port, 0, srv.idx)) bgrp = socket.inet_pton(socket.AF_INET6, self.grp6) dev = spack(b"@I", srv.idx) srv.mreq = bgrp + dev if srv.idx != socket.INADDR_ANY: sck.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, dev) try: sck.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 255) sck.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1) except: # macos t = "failed to set IPv6 TTL/LOOP; announcements may not survive multiple switches/routers" self.log(t, 3) else: if self.vinit: self.log("v4({}) idx({})".format(srv.ip, srv.idx), 6) bip = socket.inet_aton(srv.ip) self.b2srv[bip] = srv self.b4.append(bip) grp = self.grp4 if srv.idx else "" try: if MACOS: raise Exception() sck.bind((grp, self.port)) except: sck.bind(("", self.port)) bgrp = socket.inet_aton(self.grp4) dev = ( spack(b"=I", socket.INADDR_ANY) if srv.idx == socket.INADDR_ANY else socket.inet_aton(srv.ip) ) srv.mreq = bgrp + dev if srv.idx != socket.INADDR_ANY: sck.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, dev) try: sck.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255) sck.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) except: # probably can't happen but dontcare if it does t = "failed to set IPv4 TTL/LOOP; announcements may not survive multiple switches/routers" self.log(t, 3) if self.hop(srv, False): self.log("igmp was already joined?? chilling for a sec", 3) time.sleep(1.2) self.hop(srv, True) self.b4.sort(reverse=True) self.b6.sort(reverse=True) def hop(self, srv: MC_Sck, on: bool) -> bool: sck = srv.sck req = srv.mreq if ":" in srv.ip: if not on: try: sck.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_LEAVE_GROUP, req) return True except: return False else: sck.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req) else: if not on: try: sck.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, req) return True except: return False else: # t = "joining {} from ip {} idx {} with mreq {}" # self.log(t.format(srv.grp, srv.ip, srv.idx, repr(srv.mreq)), 6) sck.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req) return True def hopper(self): while self.args.mc_hop and self.running: time.sleep(self.args.mc_hop) if not self.running: return for srv in self.srv.values(): self.hop(srv, False) # linux does leaves/joins twice with 0.2~1.05s spacing time.sleep(1.2) if not self.running: return for srv in self.srv.values(): self.hop(srv, True) def map_client(self, cip: str) -> Optional[MC_Sck]: try: return self.cscache[cip] except: pass ret: Optional[MC_Sck] = None v6 = ":" in cip ci = IPv6Address(cip) if v6 else IPv4Address(cip) for x in self.b6 if v6 else self.b4: srv = self.b2srv[x] if any([x for x in srv.ips.values() if ci in x]): ret = srv break if not ret and cip in ("127.0.0.1", "::1"): # just give it something ret = list(self.srv.values())[0] if not ret and cip.startswith("169.254"): # idk how to map LL IPv4 msgs to nics; # just pick one and hope for the best lls = ( x for x in self.srv.values() if next((y for y in x.ips if y in self.ll_ok), None) ) ret = next(lls, None) if ret: t = "new client on {} ({}): {}" self.log(t.format(ret.name, ret.net, cip), 6) else: t = "could not map client {} to known subnet; maybe forwarded from another network?" self.log(t.format(cip), 3) if len(self.cscache) > 9000: self.cscache = {} self.cscache[cip] = ret return ret
--- +++ @@ -32,6 +32,7 @@ class MC_Sck(object): + """there is one socket for each server ip""" def __init__( self, @@ -66,6 +67,7 @@ port: int, vinit: bool, ) -> None: + """disable ipv%d by setting mc_grp_%d empty""" self.hub = hub self.Srv = Srv self.args = hub.args @@ -308,6 +310,7 @@ self.b6.sort(reverse=True) def hop(self, srv: MC_Sck, on: bool) -> bool: + """rejoin to keepalive on routers/switches without igmp-snooping""" sck = srv.sck req = srv.mreq if ":" in srv.ip: @@ -390,4 +393,4 @@ self.cscache = {} self.cscache[cip] = ret - return ret+ return ret
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/multicast.py
Document functions with clear intent
# coding: utf-8 from __future__ import print_function, unicode_literals import ctypes import platform import socket import sys import ipaddress if True: # pylint: disable=using-constant-test from typing import Callable, List, Optional, Union PY2 = sys.version_info < (3,) if not PY2: U: Callable[[str], str] = str else: U = unicode # noqa: F821 # pylint: disable=undefined-variable,self-assigning-variable range = xrange # noqa: F821 # pylint: disable=undefined-variable,self-assigning-variable class Adapter(object): def __init__( self, name: str, nice_name: str, ips: List["IP"], index: Optional[int] = None ) -> None: #: Unique name that identifies the adapter in the system. #: On Linux this is of the form of `eth0` or `eth0:1`, on #: Windows it is a UUID in string representation, such as #: `{846EE342-7039-11DE-9D20-806E6F6E6963}`. self.name = name #: Human readable name of the adpater. On Linux this #: is currently the same as :attr:`name`. On Windows #: this is the name of the device. self.nice_name = nice_name #: List of :class:`ifaddr.IP` instances in the order they were #: reported by the system. self.ips = ips #: Adapter index as used by some API (e.g. IPv6 multicast group join). self.index = index def __repr__(self) -> str: return "Adapter(name={name}, nice_name={nice_name}, ips={ips}, index={index})".format( name=repr(self.name), nice_name=repr(self.nice_name), ips=repr(self.ips), index=repr(self.index), ) if True: # pylint: disable=using-constant-test # Type of an IPv4 address (a string in "xxx.xxx.xxx.xxx" format) _IPv4Address = str # Type of an IPv6 address (a three-tuple `(ip, flowinfo, scope_id)`) _IPv6Address = tuple[str, int, int] class IP(object): def __init__( self, ip: Union[_IPv4Address, _IPv6Address], network_prefix: int, nice_name: str ) -> None: #: IP address. For IPv4 addresses this is a string in #: "xxx.xxx.xxx.xxx" format. For IPv6 addresses this #: is a three-tuple `(ip, flowinfo, scope_id)`, where #: `ip` is a string in the usual collon separated #: hex format. self.ip = ip #: Number of bits of the IP that represent the #: network. For a `255.255.255.0` netmask, this #: number would be `24`. self.network_prefix = network_prefix #: Human readable name for this IP. #: On Linux is this currently the same as the adapter name. #: On Windows this is the name of the network connection #: as configured in the system control panel. self.nice_name = nice_name @property def is_IPv4(self) -> bool: return not isinstance(self.ip, tuple) @property def is_IPv6(self) -> bool: return isinstance(self.ip, tuple) def __repr__(self) -> str: return "IP(ip={ip}, network_prefix={network_prefix}, nice_name={nice_name})".format( ip=repr(self.ip), network_prefix=repr(self.network_prefix), nice_name=repr(self.nice_name), ) if platform.system() == "Darwin" or "BSD" in platform.system(): # BSD derived systems use marginally different structures # than either Linux or Windows. # I still keep it in `shared` since we can use # both structures equally. class sockaddr(ctypes.Structure): _fields_ = [ ("sa_len", ctypes.c_uint8), ("sa_familiy", ctypes.c_uint8), ("sa_data", ctypes.c_uint8 * 14), ] class sockaddr_in(ctypes.Structure): _fields_ = [ ("sa_len", ctypes.c_uint8), ("sa_familiy", ctypes.c_uint8), ("sin_port", ctypes.c_uint16), ("sin_addr", ctypes.c_uint8 * 4), ("sin_zero", ctypes.c_uint8 * 8), ] class sockaddr_in6(ctypes.Structure): _fields_ = [ ("sa_len", ctypes.c_uint8), ("sa_familiy", ctypes.c_uint8), ("sin6_port", ctypes.c_uint16), ("sin6_flowinfo", ctypes.c_uint32), ("sin6_addr", ctypes.c_uint8 * 16), ("sin6_scope_id", ctypes.c_uint32), ] else: class sockaddr(ctypes.Structure): # type: ignore _fields_ = [("sa_familiy", ctypes.c_uint16), ("sa_data", ctypes.c_uint8 * 14)] class sockaddr_in(ctypes.Structure): # type: ignore _fields_ = [ ("sin_familiy", ctypes.c_uint16), ("sin_port", ctypes.c_uint16), ("sin_addr", ctypes.c_uint8 * 4), ("sin_zero", ctypes.c_uint8 * 8), ] class sockaddr_in6(ctypes.Structure): # type: ignore _fields_ = [ ("sin6_familiy", ctypes.c_uint16), ("sin6_port", ctypes.c_uint16), ("sin6_flowinfo", ctypes.c_uint32), ("sin6_addr", ctypes.c_uint8 * 16), ("sin6_scope_id", ctypes.c_uint32), ] def sockaddr_to_ip( sockaddr_ptr: "ctypes.pointer[sockaddr]", ) -> Optional[Union[_IPv4Address, _IPv6Address]]: if sockaddr_ptr: if sockaddr_ptr[0].sa_familiy == socket.AF_INET: ipv4 = ctypes.cast(sockaddr_ptr, ctypes.POINTER(sockaddr_in)) ippacked = bytes(bytearray(ipv4[0].sin_addr)) ip = U(ipaddress.ip_address(ippacked)) return ip elif sockaddr_ptr[0].sa_familiy == socket.AF_INET6: ipv6 = ctypes.cast(sockaddr_ptr, ctypes.POINTER(sockaddr_in6)) flowinfo = ipv6[0].sin6_flowinfo ippacked = bytes(bytearray(ipv6[0].sin6_addr)) ip = U(ipaddress.ip_address(ippacked)) scope_id = ipv6[0].sin6_scope_id return (ip, flowinfo, scope_id) return None def ipv6_prefixlength(address: ipaddress.IPv6Address) -> int: prefix_length = 0 for i in range(address.max_prefixlen): if int(address) >> i & 1: prefix_length = prefix_length + 1 return prefix_length
--- +++ @@ -21,6 +21,15 @@ class Adapter(object): + """ + Represents a network interface device controller (NIC), such as a + network card. An adapter can have multiple IPs. + + On Linux aliasing (multiple IPs per physical NIC) is implemented + by creating 'virtual' adapters, each represented by an instance + of this class. Each of those 'virtual' adapters can have both + a IPv4 and an IPv6 IP address. + """ def __init__( self, name: str, nice_name: str, ips: List["IP"], index: Optional[int] = None @@ -62,6 +71,9 @@ class IP(object): + """ + Represents an IP address of an adapter. + """ def __init__( self, ip: Union[_IPv4Address, _IPv6Address], network_prefix: int, nice_name: str @@ -87,10 +99,18 @@ @property def is_IPv4(self) -> bool: + """ + Returns `True` if this IP is an IPv4 address and `False` + if it is an IPv6 address. + """ return not isinstance(self.ip, tuple) @property def is_IPv6(self) -> bool: + """ + Returns `True` if this IP is an IPv6 address and `False` + if it is an IPv4 address. + """ return isinstance(self.ip, tuple) def __repr__(self) -> str: @@ -181,4 +201,4 @@ for i in range(address.max_prefixlen): if int(address) >> i & 1: prefix_length = prefix_length + 1 - return prefix_length+ return prefix_length
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/stolen/ifaddr/_shared.py
Help me comply with documentation standards
# coding: utf-8 from __future__ import print_function, unicode_literals import hashlib import math import os import re import socket import sys import threading import time import queue from .__init__ import ANYWIN, CORES, EXE, MACOS, PY2, TYPE_CHECKING, EnvParams, unicode try: MNFE = ModuleNotFoundError except: MNFE = ImportError try: import jinja2 except MNFE: if EXE: raise print( """\033[1;31m you do not have jinja2 installed,\033[33m choose one of these:\033[0m * apt install python-jinja2 * {} -m pip install --user jinja2 * (try another python version, if you have one) * (try copyparty.sfx instead) """.format( sys.executable ) ) sys.exit(1) except SyntaxError: if EXE: raise print( """\033[1;31m your jinja2 version is incompatible with your python version;\033[33m please try to replace it with an older version:\033[0m * {} -m pip install --user jinja2==2.11.3 * (try another python version, if you have one) * (try copyparty.sfx instead) """.format( sys.executable ) ) sys.exit(1) from .httpconn import HttpConn from .metrics import Metrics from .u2idx import U2idx from .util import ( E_SCK, FHC, CachedDict, Daemon, Garda, Magician, Netdev, NetMap, build_netmap, has_resource, ipnorm, load_ipr, load_ipu, load_resource, min_ex, shut_socket, spack, start_log_thrs, start_stackmon, ub64enc, ) if TYPE_CHECKING: from .authsrv import VFS from .broker_util import BrokerCli from .ssdp import SSDPr if True: # pylint: disable=using-constant-test from typing import Any, Optional if PY2: range = xrange # type: ignore if not hasattr(socket, "AF_UNIX"): setattr(socket, "AF_UNIX", -9001) def load_jinja2_resource(E: EnvParams, name: str): with load_resource(E, "web/" + name, "r") as f: return f.read() class HttpSrv(object): def __init__(self, broker: "BrokerCli", nid: Optional[int]) -> None: self.broker = broker self.nid = nid self.args = broker.args self.E: EnvParams = self.args.E self.log = broker.log self.asrv = broker.asrv # redefine in case of multiprocessing socket.setdefaulttimeout(120) self.t0 = time.time() nsuf = "-n{}-i{:x}".format(nid, os.getpid()) if nid else "" self.magician = Magician() self.nm = NetMap([], []) self.ssdp: Optional["SSDPr"] = None self.gpwd = Garda(self.args.ban_pw) self.gpwc = Garda(self.args.ban_pwc) self.g404 = Garda(self.args.ban_404) self.g403 = Garda(self.args.ban_403) self.g422 = Garda(self.args.ban_422, False) self.gmal = Garda(self.args.ban_422) self.gurl = Garda(self.args.ban_url) self.bans: dict[str, int] = {} self.aclose: dict[str, int] = {} dli: dict[str, tuple[float, int, "VFS", str, str]] = {} # info dls: dict[str, tuple[float, int]] = {} # state self.dli = self.tdli = dli self.dls = self.tdls = dls self.iiam = '<img src="%s.cpr/w/iiam.gif?cache=i" />' % (self.args.SRS,) self.bound: set[tuple[str, int]] = set() self.name = "hsrv" + nsuf self.mutex = threading.Lock() self.u2mutex = threading.Lock() self.bad_ver = False self.stopping = False self.tp_nthr = 0 # actual self.tp_ncli = 0 # fading self.tp_time = 0.0 # latest worker collect self.tp_q: Optional[queue.LifoQueue[Any]] = ( None if self.args.no_htp else queue.LifoQueue() ) self.t_periodic: Optional[threading.Thread] = None self.u2fh = FHC() self.u2sc: dict[str, tuple[int, "hashlib._Hash"]] = {} self.pipes = CachedDict(0.2) self.metrics = Metrics(self) self.nreq = 0 self.nsus = 0 self.nban = 0 self.srvs: list[socket.socket] = [] self.ncli = 0 # exact self.clients: set[HttpConn] = set() # laggy self.nclimax = 0 self.cb_ts = 0.0 self.cb_v = "" self.u2idx_free: dict[str, U2idx] = {} self.u2idx_n = 0 assert jinja2 # type: ignore # !rm env = jinja2.Environment() env.loader = jinja2.FunctionLoader(lambda f: load_jinja2_resource(self.E, f)) jn = [ "browser", "browser2", "cf", "idp", "md", "mde", "msg", "rups", "shares", "splash", "svcs", ] self.j2 = {x: env.get_template(x + ".html") for x in jn} self.j2["opds"] = env.get_template("opds.xml") self.j2["opds_osd"] = env.get_template("opds_osd.xml") self.prism = has_resource(self.E, "web/deps/prism.js.gz") if self.args.ipu: self.ipu_iu, self.ipu_nm = load_ipu(self.log, self.args.ipu) else: self.ipu_iu = self.ipu_nm = None if self.args.ipr: self.ipr = load_ipr(self.log, self.args.ipr) else: self.ipr = None self.ipa_nm = build_netmap(self.args.ipa) self.ipar_nm = build_netmap(self.args.ipar) self.xff_nm = build_netmap(self.args.xff_src) self.xff_lan = build_netmap("lan") self.mallow = "GET HEAD POST PUT DELETE OPTIONS".split() if not self.args.no_dav: zs = "PROPFIND PROPPATCH LOCK UNLOCK MKCOL COPY MOVE" self.mallow += zs.split() if self.args.zs: from .ssdp import SSDPr self.ssdp = SSDPr(broker) if self.tp_q: self.start_threads(4) if nid: self.tdli = {} self.tdls = {} if self.args.stackmon: start_stackmon(self.args.stackmon, nid) if self.args.log_thrs: start_log_thrs(self.log, self.args.log_thrs, nid) self.th_cfg: dict[str, set[str]] = {} Daemon(self.post_init, "hsrv-init2") def post_init(self) -> None: try: x = self.broker.ask("thumbsrv.getcfg") self.th_cfg = x.get() except: pass def set_bad_ver(self) -> None: self.bad_ver = True def set_netdevs(self, netdevs: dict[str, Netdev]) -> None: ips = set() for ip, _ in self.bound: ips.add(ip) self.nm = NetMap(list(ips), list(netdevs)) def start_threads(self, n: int) -> None: self.tp_nthr += n if self.args.log_htp: self.log(self.name, "workers += {} = {}".format(n, self.tp_nthr), 6) for _ in range(n): Daemon(self.thr_poolw, self.name + "-poolw") def stop_threads(self, n: int) -> None: self.tp_nthr -= n if self.args.log_htp: self.log(self.name, "workers -= {} = {}".format(n, self.tp_nthr), 6) assert self.tp_q # !rm for _ in range(n): self.tp_q.put(None) def periodic(self) -> None: while True: time.sleep(2 if self.tp_ncli or self.ncli else 10) with self.u2mutex, self.mutex: self.u2fh.clean() if self.tp_q: self.tp_ncli = max(self.ncli, self.tp_ncli - 2) if self.tp_nthr > self.tp_ncli + 8: self.stop_threads(4) if not self.ncli and not self.u2fh.cache and self.tp_nthr <= 8: self.t_periodic = None return def listen(self, sck: socket.socket, nlisteners: int) -> None: tcp = sck.family != socket.AF_UNIX if self.args.j != 1: # lost in the pickle; redefine if not ANYWIN or self.args.reuseaddr: sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if tcp: sck.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sck.settimeout(None) # < does not inherit, ^ opts above do if tcp: ip, port = sck.getsockname()[:2] else: ip = re.sub(r"\.[0-9]+$", "", sck.getsockname().split("/")[-1]) port = 0 self.srvs.append(sck) self.bound.add((ip, port)) self.nclimax = math.ceil(self.args.nc * 1.0 / nlisteners) Daemon( self.thr_listen, "httpsrv-n{}-listen-{}-{}".format(self.nid or "0", ip, port), (sck,), ) def thr_listen(self, srv_sck: socket.socket) -> None: fno = srv_sck.fileno() if srv_sck.family == socket.AF_UNIX: ip = re.sub(r"\.[0-9]+$", "", srv_sck.getsockname()) msg = "subscribed @ %s f%d p%d" % (ip, fno, os.getpid()) ip = ip.split("/")[-1] port = 0 tcp = False else: tcp = True ip, port = srv_sck.getsockname()[:2] hip = "[%s]" % (ip,) if ":" in ip else ip msg = "subscribed @ %s:%d f%d p%d" % (hip, port, fno, os.getpid()) self.log(self.name, msg) Daemon(self.broker.say, "sig-hsrv-up1", ("cb_httpsrv_up",)) saddr = ("", 0) # fwd-decl for `except TypeError as ex:` while not self.stopping: if self.args.log_conn: self.log(self.name, "|%sC-ncli" % ("-" * 1,), c="90") spins = 0 while self.ncli >= self.nclimax: if not spins: t = "at connection limit (global-option 'nc'); waiting" self.log(self.name, t, 3) spins += 1 time.sleep(0.1) if spins != 50 or not self.args.aclose: continue ipfreq: dict[str, int] = {} with self.mutex: for c in self.clients: ip = ipnorm(c.ip) try: ipfreq[ip] += 1 except: ipfreq[ip] = 1 ip, n = sorted(ipfreq.items(), key=lambda x: x[1], reverse=True)[0] if n < self.nclimax / 2: continue self.aclose[ip] = int(time.time() + self.args.aclose * 60) nclose = 0 nloris = 0 nconn = 0 with self.mutex: for c in self.clients: cip = ipnorm(c.ip) if ip != cip: continue nconn += 1 try: if ( c.nreq >= 1 or not c.cli or c.cli.in_hdr_recv or c.cli.keepalive ): Daemon(c.shutdown) nclose += 1 if c.nreq <= 0 and (not c.cli or c.cli.in_hdr_recv): nloris += 1 except: pass t = "{} downgraded to connection:close for {} min; dropped {}/{} connections" self.log(self.name, t.format(ip, self.args.aclose, nclose, nconn), 1) if nloris < nconn / 2: continue t = "slow%s (idle-conn): %s banned for %d min" # slowloris self.log(self.name, t % ("loris", ip, self.args.loris), 1) self.bans[ip] = int(time.time() + self.args.loris * 60) if self.args.log_conn: self.log(self.name, "|%sC-acc1" % ("-" * 2,), c="90") try: sck, saddr = srv_sck.accept() if tcp: cip = unicode(saddr[0]) if cip.startswith("::ffff:"): cip = cip[7:] addr = (cip, saddr[1]) else: addr = ("127.8.3.7", sck.fileno()) except (OSError, socket.error) as ex: if self.stopping: break self.log(self.name, "accept({}): {}".format(fno, ex), c=6) time.sleep(0.02) continue except TypeError as ex: # on macOS, accept() may return a None saddr if blocked by LittleSnitch; # unicode(saddr[0]) ==> TypeError: 'NoneType' object is not subscriptable if tcp and not saddr: t = "accept(%s): failed to accept connection from client due to firewall or network issue" self.log(self.name, t % (fno,), c=3) try: sck.close() # type: ignore except: pass time.sleep(0.02) continue raise if self.args.log_conn: t = "|{}C-acc2 \033[0;36m{} \033[3{}m{}".format( "-" * 3, ip, port % 8, port ) self.log("%s %s" % addr, t, c="90") self.accept(sck, addr) def accept(self, sck: socket.socket, addr: tuple[str, int]) -> None: now = time.time() if now - (self.tp_time or now) > 300: t = "httpserver threadpool died: tpt {:.2f}, now {:.2f}, nthr {}, ncli {}" self.log(self.name, t.format(self.tp_time, now, self.tp_nthr, self.ncli), 1) self.tp_time = 0 self.tp_q = None with self.mutex: self.ncli += 1 if not self.t_periodic: name = "hsrv-pt" if self.nid: name += "-%d" % (self.nid,) self.t_periodic = Daemon(self.periodic, name) if self.tp_q: self.tp_time = self.tp_time or now self.tp_ncli = max(self.tp_ncli, self.ncli) if self.tp_nthr < self.ncli + 4: self.start_threads(8) self.tp_q.put((sck, addr)) return if not self.args.no_htp: t = "looks like the httpserver threadpool died; please make an issue on github and tell me the story of how you pulled that off, thanks and dog bless\n" self.log(self.name, t, 1) Daemon( self.thr_client, "httpconn-%s-%d" % (addr[0].split(".", 2)[-1][-6:], addr[1]), (sck, addr), ) def thr_poolw(self) -> None: assert self.tp_q # !rm while True: task = self.tp_q.get() if not task: break with self.mutex: self.tp_time = 0 try: sck, addr = task me = threading.current_thread() me.name = "httpconn-%s-%d" % (addr[0].split(".", 2)[-1][-6:], addr[1]) self.thr_client(sck, addr) me.name = self.name + "-poolw" except Exception as ex: if str(ex).startswith("client d/c "): self.log(self.name, "thr_client: " + str(ex), 6) else: self.log(self.name, "thr_client: " + min_ex(), 3) def shutdown(self) -> None: self.stopping = True for srv in self.srvs: try: srv.close() except: pass thrs = [] clients = list(self.clients) for cli in clients: t = threading.Thread(target=cli.shutdown) thrs.append(t) t.start() if self.tp_q: self.stop_threads(self.tp_nthr) for _ in range(10): time.sleep(0.05) if self.tp_q.empty(): break for t in thrs: t.join() self.log(self.name, "ok bye") def thr_client(self, sck: socket.socket, addr: tuple[str, int]) -> None: cli = HttpConn(sck, addr, self) with self.mutex: self.clients.add(cli) # print("{}\n".format(len(self.clients)), end="") fno = sck.fileno() try: if self.args.log_conn: self.log("%s %s" % addr, "|%sC-crun" % ("-" * 4,), c="90") cli.run() except (OSError, socket.error) as ex: if ex.errno not in E_SCK: self.log( "%s %s" % addr, "run({}): {}".format(fno, ex), c=6, ) finally: sck = cli.s if self.args.log_conn: self.log("%s %s" % addr, "|%sC-cdone" % ("-" * 5,), c="90") try: fno = sck.fileno() shut_socket(cli.log, sck) except (OSError, socket.error) as ex: if not MACOS: self.log( "%s %s" % addr, "shut({}): {}".format(fno, ex), c="90", ) if ex.errno not in E_SCK: raise finally: with self.mutex: self.clients.remove(cli) self.ncli -= 1 if cli.u2idx: self.put_u2idx(str(addr), cli.u2idx) def cachebuster(self) -> str: if time.time() - self.cb_ts < 1: return self.cb_v with self.mutex: if time.time() - self.cb_ts < 1: return self.cb_v v = self.E.t0 try: with os.scandir(self.E.mod_ + "web") as dh: for fh in dh: inf = fh.stat() v = max(v, inf.st_mtime) except: pass # spack gives 4 lsb, take 3 lsb, get 4 ch self.cb_v = ub64enc(spack(b">L", int(v))[1:]).decode("ascii") self.cb_ts = time.time() return self.cb_v def get_u2idx(self, ident: str) -> Optional[U2idx]: utab = self.u2idx_free for _ in range(100): # 5/0.05 = 5sec with self.mutex: if utab: if ident in utab: return utab.pop(ident) return utab.pop(list(utab.keys())[0]) if self.u2idx_n < CORES: self.u2idx_n += 1 return U2idx(self) time.sleep(0.05) # not using conditional waits, on a hunch that # average performance will be faster like this # since most servers won't be fully saturated return None def put_u2idx(self, ident: str, u2idx: U2idx) -> None: with self.mutex: while ident in self.u2idx_free: ident += "a" self.u2idx_free[ident] = u2idx def read_dls( self, ) -> tuple[ dict[str, tuple[float, int, str, str, str]], dict[str, tuple[float, int]] ]: dli = {k: (a, b, c.vpath, d, e) for k, (a, b, c, d, e) in self.dli.items()} return (dli, self.dls) def write_dls( self, sdli: dict[str, tuple[float, int, str, str, str]], dls: dict[str, tuple[float, int]], ) -> None: dli: dict[str, tuple[float, int, "VFS", str, str]] = {} for k, (a, b, c, d, e) in sdli.items(): vn = self.asrv.vfs.all_nodes[c] dli[k] = (a, b, vn, d, e) self.tdli = dli self.tdls = dls
--- +++ @@ -102,6 +102,10 @@ class HttpSrv(object): + """ + handles incoming connections using HttpConn to process http, + relying on MpSrv for performance (HttpSrv is just plain threads) + """ def __init__(self, broker: "BrokerCli", nid: Optional[int]) -> None: self.broker = broker @@ -306,6 +310,7 @@ ) def thr_listen(self, srv_sck: socket.socket) -> None: + """listens on a shared tcp server""" fno = srv_sck.fileno() if srv_sck.family == socket.AF_UNIX: ip = re.sub(r"\.[0-9]+$", "", srv_sck.getsockname()) @@ -430,6 +435,7 @@ self.accept(sck, addr) def accept(self, sck: socket.socket, addr: tuple[str, int]) -> None: + """takes an incoming tcp connection and creates a thread to handle it""" now = time.time() if now - (self.tp_time or now) > 300: @@ -516,6 +522,7 @@ self.log(self.name, "ok bye") def thr_client(self, sck: socket.socket, addr: tuple[str, int]) -> None: + """thread managing one tcp client""" cli = HttpConn(sck, addr, self) with self.mutex: self.clients.add(cli) @@ -616,6 +623,10 @@ ) -> tuple[ dict[str, tuple[float, int, str, str, str]], dict[str, tuple[float, int]] ]: + """ + mp-broker asking for local dl-info + dl-state; + reduce overhead by sending just the vfs vpath + """ dli = {k: (a, b, c.vpath, d, e) for k, (a, b, c, d, e) in self.dli.items()} return (dli, self.dls) @@ -624,10 +635,14 @@ sdli: dict[str, tuple[float, int, str, str, str]], dls: dict[str, tuple[float, int]], ) -> None: + """ + mp-broker pushing total dl-info + dl-state; + swap out the vfs vpath with the vfs node + """ dli: dict[str, tuple[float, int, "VFS", str, str]] = {} for k, (a, b, c, d, e) in sdli.items(): vn = self.asrv.vfs.all_nodes[c] dli[k] = (a, b, vn, d, e) self.tdli = dli - self.tdls = dls+ self.tdls = dls
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/httpsrv.py
Document functions with detailed explanations
# coding: utf-8 from __future__ import print_function, unicode_literals import errno import re import select import socket import time from .__init__ import TYPE_CHECKING from .multicast import MC_Sck, MCast from .util import CachedSet, formatdate, html_escape, min_ex if TYPE_CHECKING: from .broker_util import BrokerCli from .httpcli import HttpCli from .svchub import SvcHub if True: # pylint: disable=using-constant-test from typing import Optional, Union GRP = "239.255.255.250" class SSDP_Sck(MC_Sck): def __init__(self, *a): super(SSDP_Sck, self).__init__(*a) self.hport = 0 class SSDPr(object): def __init__(self, broker: "BrokerCli") -> None: self.broker = broker self.args = broker.args def reply(self, hc: "HttpCli") -> bool: if hc.vpath.endswith("device.xml"): return self.tx_device(hc) hc.reply(b"unknown request", 400) return False def tx_device(self, hc: "HttpCli") -> bool: zs = """ <?xml version="1.0"?> <root xmlns="urn:schemas-upnp-org:device-1-0"> <specVersion> <major>1</major> <minor>0</minor> </specVersion> <URLBase>{}</URLBase> <device> <presentationURL>{}</presentationURL> <deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType> <friendlyName>{}</friendlyName> <modelDescription>file server</modelDescription> <manufacturer>ed</manufacturer> <manufacturerURL>https://ocv.me/</manufacturerURL> <modelName>copyparty</modelName> <modelURL>https://github.com/9001/copyparty/</modelURL> <UDN>{}</UDN> <serviceList> <service> <serviceType>urn:schemas-upnp-org:device:Basic:1</serviceType> <serviceId>urn:schemas-upnp-org:device:Basic</serviceId> <controlURL>/.cpr/ssdp/services.xml</controlURL> <eventSubURL>/.cpr/ssdp/services.xml</eventSubURL> <SCPDURL>/.cpr/ssdp/services.xml</SCPDURL> </service> </serviceList> </device> </root>""" c = html_escape sip, sport = hc.s.getsockname()[:2] sip = sip.replace("::ffff:", "") proto = "https" if self.args.https_only else "http" ubase = "{}://{}:{}".format(proto, sip, sport) zsl = self.args.zsl url = zsl if "://" in zsl else ubase + "/" + zsl.lstrip("/") name = self.args.doctitle zs = zs.strip().format(c(ubase), c(url), c(name), c(self.args.zsid)) hc.reply(zs.encode("utf-8", "replace")) return False # close connection class SSDPd(MCast): def __init__(self, hub: "SvcHub", ngen: int) -> None: al = hub.args vinit = al.zsv and not al.zmv super(SSDPd, self).__init__( hub, SSDP_Sck, al.zs_on, al.zs_off, GRP, "", 1900, vinit ) self.srv: dict[socket.socket, SSDP_Sck] = {} self.logsrc = "SSDP-{}".format(ngen) self.ngen = ngen self.rxc = CachedSet(0.7) self.txc = CachedSet(5) # win10: every 3 sec self.ptn_st = re.compile(b"\nst: *upnp:rootdevice", re.I) def log(self, msg: str, c: Union[int, str] = 0) -> None: self.log_func(self.logsrc, msg, c) def run(self) -> None: try: bound = self.create_servers() except: t = "no server IP matches the ssdp config\n{}" self.log(t.format(min_ex()), 1) bound = [] if not bound: self.log("failed to announce copyparty services on the network", 3) return # find http port for this listening ip for srv in self.srv.values(): tcps = self.hub.tcpsrv.bound hp = next((x[1] for x in tcps if x[0] in ("0.0.0.0", srv.ip)), 0) hp = hp or next((x[1] for x in tcps if x[0] == "::"), 0) if not hp: hp = tcps[0][1] self.log("assuming port {} for {}".format(hp, srv.ip), 3) srv.hport = hp self.log("listening") try: self.run2() except OSError as ex: if ex.errno != errno.EBADF: raise self.log("stopping due to {}".format(ex), "90") self.log("stopped", 2) def run2(self) -> None: try: if self.args.no_poll: raise Exception() fd2sck = {} srvpoll = select.poll() for sck in self.srv: fd = sck.fileno() fd2sck[fd] = sck srvpoll.register(fd, select.POLLIN) except Exception as ex: srvpoll = None if not self.args.no_poll: t = "WARNING: failed to poll(), will use select() instead: %r" self.log(t % (ex,), 3) while self.running: if srvpoll: pr = srvpoll.poll((self.args.z_chk or 180) * 1000) rx = [fd2sck[x[0]] for x in pr if x[1] & select.POLLIN] else: rdy = select.select(self.srv, [], [], self.args.z_chk or 180) rx: list[socket.socket] = rdy[0] # type: ignore self.rxc.cln() buf = b"" addr = ("0", 0) for sck in rx: try: buf, addr = sck.recvfrom(4096) self.eat(buf, addr) except: if not self.running: break t = "{} {} \033[33m|{}| {}\n{}".format( self.srv[sck].name, addr, len(buf), repr(buf)[2:-1], min_ex() ) self.log(t, 6) def stop(self) -> None: self.running = False for srv in self.srv.values(): try: srv.sck.close() except: pass self.srv.clear() def eat(self, buf: bytes, addr: tuple[str, int]) -> None: cip = addr[0] if cip.startswith("169.254") and not self.ll_ok: return if buf in self.rxc.c: return srv: Optional[SSDP_Sck] = self.map_client(cip) # type: ignore if not srv: return self.rxc.add(buf) if not buf.startswith(b"M-SEARCH * HTTP/1."): return if not self.ptn_st.search(buf): return if self.args.zsv: t = "{} [{}] \033[36m{} \033[0m|{}|" self.log(t.format(srv.name, srv.ip, cip, len(buf)), "90") zs = """ HTTP/1.1 200 OK CACHE-CONTROL: max-age=1800 DATE: {0} EXT: LOCATION: http://{1}:{2}/.cpr/ssdp/device.xml OPT: "http://schemas.upnp.org/upnp/1/0/"; ns=01 01-NLS: {3} SERVER: UPnP/1.0 ST: upnp:rootdevice USN: {3}::upnp:rootdevice BOOTID.UPNP.ORG: 0 CONFIGID.UPNP.ORG: 1 """ v4 = srv.ip.replace("::ffff:", "") zs = zs.format(formatdate(), v4, srv.hport, self.args.zsid) zb = zs[1:].replace("\n", "\r\n").encode("utf-8", "replace") srv.sck.sendto(zb, addr[:2]) if cip not in self.txc.c: self.log("{} [{}] --> {}".format(srv.name, srv.ip, cip), 6) self.txc.add(cip) self.txc.cln()
--- +++ @@ -30,6 +30,7 @@ class SSDPr(object): + """generates http responses for httpcli""" def __init__(self, broker: "BrokerCli") -> None: self.broker = broker @@ -87,6 +88,7 @@ class SSDPd(MCast): + """communicates with ssdp clients over multicast""" def __init__(self, hub: "SvcHub", ngen: int) -> None: al = hub.args @@ -235,4 +237,4 @@ self.log("{} [{}] --> {}".format(srv.name, srv.ip, cip), 6) self.txc.add(cip) - self.txc.cln()+ self.txc.cln()
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/ssdp.py
Generate NumPy-style docstrings
# coding: utf-8 from __future__ import print_function, unicode_literals import re import stat import tarfile from queue import Queue from .authsrv import AuthSrv from .bos import bos from .sutil import StreamArc, errdesc from .util import Daemon, fsenc, min_ex if True: # pylint: disable=using-constant-test from typing import Any, Generator, Optional from .util import NamedLogger class QFile(object): # inherit io.StringIO for painful typing def __init__(self) -> None: self.q: Queue[Optional[bytes]] = Queue(64) self.bq: list[bytes] = [] self.nq = 0 def write(self, buf: Optional[bytes]) -> None: if buf is None or self.nq >= 240 * 1024: self.q.put(b"".join(self.bq)) self.bq = [] self.nq = 0 if buf is None: self.q.put(None) else: self.bq.append(buf) self.nq += len(buf) class StreamTar(StreamArc): def __init__( self, log: "NamedLogger", asrv: AuthSrv, fgen: Generator[dict[str, Any], None, None], cmp: str = "", **kwargs: Any ): super(StreamTar, self).__init__(log, asrv, fgen) self.ci = 0 self.co = 0 self.qfile = QFile() self.errf: dict[str, Any] = {} # python 3.8 changed to PAX_FORMAT as default; # slower, bigger, and no particular advantage fmt = tarfile.GNU_FORMAT if "pax" in cmp: # unless a client asks for it (currently # gnu-tar has wider support than pax-tar) fmt = tarfile.PAX_FORMAT cmp = re.sub(r"[^a-z0-9]*pax[^a-z0-9]*", "", cmp) try: cmp, zs = cmp.replace(":", ",").split(",") lv = int(zs) except: lv = -1 arg = {"name": None, "fileobj": self.qfile, "mode": "w", "format": fmt} if cmp == "gz": fun = tarfile.TarFile.gzopen arg["compresslevel"] = lv if lv >= 0 else 3 elif cmp == "bz2": fun = tarfile.TarFile.bz2open arg["compresslevel"] = lv if lv >= 0 else 2 elif cmp == "xz": fun = tarfile.TarFile.xzopen arg["preset"] = lv if lv >= 0 else 1 else: fun = tarfile.open arg["mode"] = "w|" self.tar = fun(**arg) Daemon(self._gen, "star-gen") def gen(self) -> Generator[Optional[bytes], None, None]: buf = b"" try: while True: buf = self.qfile.q.get() if not buf: break self.co += len(buf) yield buf yield None finally: while buf: try: buf = self.qfile.q.get() except: pass if self.errf: bos.unlink(self.errf["ap"]) def ser(self, f: dict[str, Any]) -> None: name = f["vp"] src = f["ap"] fsi = f["st"] if stat.S_ISDIR(fsi.st_mode): return inf = tarfile.TarInfo(name=name) inf.mode = fsi.st_mode inf.size = fsi.st_size inf.mtime = fsi.st_mtime inf.uid = 0 inf.gid = 0 self.ci += inf.size with open(fsenc(src), "rb", self.args.iobuf) as fo: self.tar.addfile(inf, fo) def _gen(self) -> None: errors = [] for f in self.fgen: if "err" in f: errors.append((f["vp"], f["err"])) continue if self.stopped: break try: self.ser(f) except: ex = min_ex(5, True).replace("\n", "\n-- ") errors.append((f["vp"], ex)) if errors: self.errf, txt = errdesc(self.asrv.vfs, errors) self.log("\n".join(([repr(self.errf)] + txt[1:]))) self.ser(self.errf) self.tar.close() self.qfile.write(None)
--- +++ @@ -19,6 +19,7 @@ class QFile(object): # inherit io.StringIO for painful typing + """file-like object which buffers writes into a queue""" def __init__(self) -> None: self.q: Queue[Optional[bytes]] = Queue(64) @@ -39,6 +40,7 @@ class StreamTar(StreamArc): + """construct in-memory tar file from the given path""" def __init__( self, @@ -151,4 +153,4 @@ self.ser(self.errf) self.tar.close() - self.qfile.write(None)+ self.qfile.write(None)
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/star.py
Add docstrings with type hints explained
#!/usr/bin/env python3 # coding: utf-8 from __future__ import print_function, unicode_literals """copyparty: http file sharing hub (py2/py3)""" __author__ = "ed <copyparty@ocv.me>" __copyright__ = 2019 __license__ = "MIT" __url__ = "https://github.com/9001/copyparty/" import argparse import base64 import locale import os import re import select import socket import sys import threading import time import traceback import uuid from .__init__ import ( ANYWIN, CORES, EXE, MACOS, PY2, PY36, VT100, WINDOWS, E, EnvParams, unicode, ) from .__version__ import CODENAME, S_BUILD_DT, S_VERSION from .authsrv import expand_config_file, split_cfg_ln, upgrade_cfg_fmt from .bos import bos from .cfg import flagcats, onedash from .svchub import SvcHub from .util import ( APPLESAN_TXT, BAD_BOTS, DEF_EXP, DEF_MTE, DEF_MTH, HAVE_IPV6, IMPLICATIONS, JINJA_VER, MIKO_VER, MIMES, PARTFTPY_VER, PY_DESC, PYFTPD_VER, RAM_AVAIL, RAM_TOTAL, RE_ANSI, SQLITE_VER, UNPLICATIONS, URL_BUG, URL_PRJ, Daemon, align_tab, b64enc, ctypes, dedent, has_resource, load_resource, min_ex, pybin, read_utf8, termsize, wk32, wrap, ) if True: # pylint: disable=using-constant-test from collections.abc import Callable from types import FrameType from typing import Any, Optional if PY2: range = xrange # type: ignore try: if os.environ.get("PRTY_NO_TLS"): raise Exception() HAVE_SSL = True import ssl except: HAVE_SSL = False u = unicode printed: list[str] = [] zsid = uuid.uuid4().urn[4:] CFG_DEF = [os.environ.get("PRTY_CONFIG", "")] if not CFG_DEF[0]: CFG_DEF.pop() class RiceFormatter(argparse.HelpFormatter): def __init__(self, *args: Any, **kwargs: Any) -> None: if PY2: kwargs["width"] = termsize()[0] super(RiceFormatter, self).__init__(*args, **kwargs) def _get_help_string(self, action: argparse.Action) -> str: fmt = "\033[36m (default: \033[35m%(default)s\033[36m)\033[0m" if not VT100: fmt = " (default: %(default)s)" ret = unicode(action.help) if "%(default)" not in ret: if action.default is not argparse.SUPPRESS: defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE] if action.option_strings or action.nargs in defaulting_nargs: ret += fmt if not VT100: ret = re.sub("\033\\[[0-9;]+m", "", ret) return ret # type: ignore def _fill_text(self, text: str, width: int, indent: str) -> str: return "".join(indent + line + "\n" for line in text.splitlines()) def __add_whitespace(self, idx: int, iWSpace: int, text: str) -> str: return (" " * iWSpace) + text if idx else text def _split_lines(self, text: str, width: int) -> list[str]: # https://stackoverflow.com/a/35925919 textRows = text.splitlines() ptn = re.compile(r"\s*[0-9\-]{0,}\.?\s*") for idx, line in enumerate(textRows): search = ptn.search(line) if not line.strip(): textRows[idx] = " " elif search: lWSpace = search.end() lines = [ self.__add_whitespace(i, lWSpace, x) for i, x in enumerate(wrap(line, width, width - 1)) ] textRows[idx] = lines # type: ignore return [item for sublist in textRows for item in sublist] class Dodge11874(RiceFormatter): def __init__(self, *args: Any, **kwargs: Any) -> None: kwargs["width"] = 9003 super(Dodge11874, self).__init__(*args, **kwargs) class BasicDodge11874( argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter ): def __init__(self, *args: Any, **kwargs: Any) -> None: kwargs["width"] = 9003 super(BasicDodge11874, self).__init__(*args, **kwargs) def lprint(*a: Any, **ka: Any) -> None: eol = ka.pop("end", "\n") txt: str = " ".join(unicode(x) for x in a) + eol printed.append(txt) if not VT100: txt = RE_ANSI.sub("", txt) print(txt, end="", **ka) def warn(msg: str) -> None: lprint("\033[1mwarning:\033[0;33m {}\033[0m\n".format(msg)) def init_E(EE: EnvParams) -> None: # some cpython alternatives (such as pyoxidizer) can # __init__ several times, so do expensive stuff here E = EE # pylint: disable=redefined-outer-name def get_unixdir() -> tuple[str, bool]: paths: list[tuple[Callable[..., Any], str]] = [ (os.environ.get, "XDG_CONFIG_HOME"), (os.path.expanduser, "~/.config"), (os.environ.get, "TMPDIR"), (os.environ.get, "TEMP"), (os.environ.get, "TMP"), (unicode, "/tmp"), ] errs = [] for npath, (pf, pa) in enumerate(paths): priv = npath < 2 # private/trusted location ram = npath > 1 # "nonvolatile"; not semantically same as `not priv` p = "" try: p = pf(pa) if not p or p.startswith("~"): continue p = os.path.normpath(p) mkdir = not os.path.isdir(p) if mkdir: os.mkdir(p, 0o700) p = os.path.join(p, "copyparty") if not priv and os.path.isdir(p): uid = os.geteuid() if os.stat(p).st_uid != uid: p += ".%s" % (uid,) if os.path.isdir(p) and os.stat(p).st_uid != uid: raise Exception("filesystem has broken unix permissions") try: os.listdir(p) except: os.mkdir(p, 0o700) if ram: t = "Using %s/copyparty [%s] for config; filekeys/dirkeys will change on every restart. Consider setting XDG_CONFIG_HOME or giving the unix-user a ~/.config/" errs.append(t % (pa, p)) elif mkdir: t = "Using %s/copyparty [%s] for config%s (Warning: %s did not exist and was created just now)" errs.append(t % (pa, p, " instead" if npath else "", pa)) elif errs: errs.append("Using %s/copyparty [%s] instead" % (pa, p)) if errs: warn(". ".join(errs)) return p, priv except Exception as ex: if p: t = "Unable to store config in %s [%s] due to %r" errs.append(t % (pa, p, ex)) t = "could not find a writable path for runtime state:\n> %s" raise Exception(t % ("\n> ".join(errs))) E.mod = os.path.dirname(os.path.realpath(__file__)) if E.mod.endswith("__init__"): E.mod = os.path.dirname(E.mod) E.mod_ = os.path.join(E.mod, "") try: p = os.environ.get("XDG_CONFIG_HOME") if not p: raise Exception() if p.startswith("~"): p = os.path.expanduser(p) p = os.path.abspath(os.path.realpath(p)) p = os.path.join(p, "copyparty") if not os.path.isdir(p): os.mkdir(p, 0o700) os.listdir(p) except: p = "" if p: E.cfg = p elif sys.platform == "win32": bdir = os.environ.get("APPDATA") or os.environ.get("TEMP") or "." E.cfg = os.path.normpath(bdir + "/copyparty") elif sys.platform == "darwin": E.cfg = os.path.expanduser("~/Library/Preferences/copyparty") else: E.cfg, E.scfg = get_unixdir() E.cfg = E.cfg.replace("\\", "/") try: bos.makedirs(E.cfg, bos.MKD_700) except: if not os.path.isdir(E.cfg): raise def get_srvname(verbose) -> str: try: ret: str = unicode(socket.gethostname()).split(".")[0] except: ret = "" if ret not in ["", "localhost"]: return ret fp = os.path.join(E.cfg, "name.txt") if verbose: lprint("using hostname from {}\n".format(fp)) try: return read_utf8(None, fp, True).strip() except: ret = "" namelen = 5 while len(ret) < namelen: ret += base64.b32encode(os.urandom(4))[:7].decode("utf-8").lower() ret = re.sub("[234567=]", "", ret)[:namelen] with open(fp, "wb") as f: f.write(ret.encode("utf-8") + b"\n") return ret def get_salt(name: str, nbytes: int) -> str: fp = os.path.join(E.cfg, "%s-salt.txt" % (name,)) try: return read_utf8(None, fp, True).strip() except: ret = b64enc(os.urandom(nbytes)) with open(fp, "wb") as f: f.write(ret + b"\n") return ret.decode("utf-8") def ensure_locale() -> None: if ANYWIN and PY2: return # maybe XP, so busted 65001 safe = "en_US.UTF-8" for x in [ safe, "English_United States.UTF8", "English_United States.1252", ]: try: locale.setlocale(locale.LC_ALL, x) if x != safe: lprint("Locale: {}\n".format(x)) return except: continue t = "setlocale {} failed,\n sorting and dates might get funky\n" warn(t.format(safe)) def ensure_webdeps() -> None: if has_resource(E, "web/deps/mini-fa.woff"): return t = """could not find webdeps; if you are running the sfx, or exe, or pypi package, or docker image, then this is a bug! Please let me know so I can fix it, thanks :-) %s however, if you are a dev, or running copyparty from source, and you want full client functionality, you will need to build or obtain the webdeps: %s/blob/hovudstraum/docs/devnotes.md#building """ warn(t % (URL_BUG, URL_PRJ)) def configure_ssl_ver(al: argparse.Namespace) -> None: def terse_sslver(txt: str) -> str: txt = txt.lower() for c in ["_", "v", "."]: txt = txt.replace(c, "") return txt.replace("tls10", "tls1") # oh man i love openssl # check this out # hold my beer assert ssl # type: ignore # !rm ptn = re.compile(r"^OP_NO_(TLS|SSL)v") sslver = terse_sslver(al.ssl_ver).split(",") flags = [k for k in ssl.__dict__ if ptn.match(k)] # SSLv2 SSLv3 TLSv1 TLSv1_1 TLSv1_2 TLSv1_3 if "help" in sslver: avail1 = [terse_sslver(x[6:]) for x in flags] avail = " ".join(sorted(avail1) + ["all"]) lprint("\navailable ssl/tls versions:\n " + avail) sys.exit(0) al.ssl_flags_en = 0 al.ssl_flags_de = 0 for flag in sorted(flags): ver = terse_sslver(flag[6:]) num = getattr(ssl, flag) if ver in sslver: al.ssl_flags_en |= num else: al.ssl_flags_de |= num if sslver == ["all"]: x = al.ssl_flags_en al.ssl_flags_en = al.ssl_flags_de al.ssl_flags_de = x for k in ["ssl_flags_en", "ssl_flags_de"]: num = getattr(al, k) lprint("{0}: {1:8x} ({1})".format(k, num)) # think i need that beer now def configure_ssl_ciphers(al: argparse.Namespace) -> None: assert ssl # type: ignore # !rm ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) if al.ssl_ver: ctx.options &= ~al.ssl_flags_en ctx.options |= al.ssl_flags_de is_help = al.ciphers == "help" if al.ciphers and not is_help: try: ctx.set_ciphers(al.ciphers) except: lprint("\n\033[1;31mfailed to set ciphers\033[0m\n") if not hasattr(ctx, "get_ciphers"): lprint("cannot read cipher list: openssl or python too old") else: ciphers = [x["description"] for x in ctx.get_ciphers()] lprint("\n ".join(["\nenabled ciphers:"] + align_tab(ciphers) + [""])) if is_help: sys.exit(0) def args_from_cfg(cfg_path: str) -> list[str]: lines: list[str] = [] expand_config_file(None, lines, cfg_path, "") lines = upgrade_cfg_fmt(None, argparse.Namespace(vc=False), lines, "") ret: list[str] = [] skip = True for ln in lines: sn = ln.split(" #")[0].strip() if sn.startswith("["): skip = True if sn.startswith("[global]"): skip = False continue if skip or not sn.split("#")[0].strip(): continue for k, v in split_cfg_ln(sn).items(): k = k.lstrip("-") if not k: continue prefix = "-" if k in onedash else "--" if v is True: ret.append(prefix + k) else: ret.append(prefix + k + "=" + v) return ret def expand_cfg(argv) -> list[str]: if CFG_DEF: supp = args_from_cfg(CFG_DEF[0]) argv = argv[:1] + supp + argv[1:] n = 0 while n < len(argv): v1 = argv[n] v1v = v1[2:].lstrip("=") try: v2 = argv[n + 1] except: v2 = "" n += 1 if v1 == "-c" and v2 and os.path.isfile(v2): n += 1 argv = argv[:n] + args_from_cfg(v2) + argv[n:] elif v1.startswith("-c") and v1v and os.path.isfile(v1v): argv = argv[:n] + args_from_cfg(v1v) + argv[n:] return argv def quotecheck(al): for zs1, zco in vars(al).items(): zsl = [u(x) for x in zco] if isinstance(zco, list) else [u(zco)] for zs2 in zsl: zs2 = zs2.strip() zs3 = zs2.strip("\"'") if zs2 == zs3 or len(zs2) - len(zs3) < 2: continue if al.c: t = "found the following global-config: %s: %s\n values should not be quoted; did you mean: %s: %s" else: t = 'found the following config-option: "--%s=%s"\n values should not be quoted; did you mean: "--%s=%s"' warn(t % (zs1, zs2, zs1, zs3)) def sighandler(sig: Optional[int] = None, frame: Optional[FrameType] = None) -> None: msg = [""] * 5 for th in threading.enumerate(): stk = sys._current_frames()[th.ident] # type: ignore msg.append(str(th)) msg.extend(traceback.format_stack(stk)) msg.append("\n") print("\n".join(msg)) def disable_quickedit() -> None: if not ctypes: raise Exception("no ctypes") import atexit from ctypes import wintypes def ecb(ok: bool, fun: Any, args: list[Any]) -> list[Any]: if not ok: err: int = ctypes.get_last_error() # type: ignore if err: raise ctypes.WinError(err) # type: ignore return args if PY2: wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD) k32 = wk32 k32.GetStdHandle.errcheck = ecb # type: ignore k32.GetConsoleMode.errcheck = ecb # type: ignore k32.SetConsoleMode.errcheck = ecb # type: ignore k32.GetConsoleMode.argtypes = (wintypes.HANDLE, wintypes.LPDWORD) k32.SetConsoleMode.argtypes = (wintypes.HANDLE, wintypes.DWORD) def cmode(out: bool, mode: Optional[int] = None) -> int: h = k32.GetStdHandle(-11 if out else -10) if mode: return k32.SetConsoleMode(h, mode) # type: ignore cmode = wintypes.DWORD() k32.GetConsoleMode(h, ctypes.byref(cmode)) return cmode.value # disable quickedit mode = orig_in = cmode(False) quickedit = 0x40 extended = 0x80 mask = quickedit + extended if mode & mask != extended: atexit.register(cmode, False, orig_in) cmode(False, mode & ~mask | extended) # enable colors in case the os.system("rem") trick ever stops working if VT100: mode = orig_out = cmode(True) if mode & 4 != 4: atexit.register(cmode, True, orig_out) cmode(True, mode | 4) def sfx_tpoke(top: str): if os.environ.get("PRTY_NO_TPOKE"): return files = [top] + [ os.path.join(dp, p) for dp, dd, df in os.walk(top) for p in dd + df ] while True: t = int(time.time()) for f in list(files): try: os.utime(f, (t, t)) except Exception as ex: lprint("<TPOKE> [%s] %r" % (f, ex)) files.remove(f) time.sleep(78123) def showlic() -> None: try: with load_resource(E, "res/COPYING.txt") as f: buf = f.read() except: buf = b"" if buf: print(buf.decode("utf-8", "replace")) else: print("no relevant license info to display") return def get_sects(): return [ [ "bind", "configure listening", dedent( """ \033[33m-i\033[0m takes a comma-separated list of interfaces to listen on; IP-addresses, unix-sockets, and/or open file descriptors the default (\033[32m-i ::\033[0m) means all IPv4 and IPv6 addresses \033[32m-i 0.0.0.0\033[0m listens on all IPv4 NICs/subnets \033[32m-i 127.0.0.1\033[0m listens on IPv4 localhost only \033[32m-i 127.1\033[0m listens on IPv4 localhost only \033[32m-i 127.1,192.168.123.1\033[0m = IPv4 localhost and 192.168.123.1 \033[33m-p\033[0m takes a comma-separated list of tcp ports to listen on; the default is \033[32m-p 3923\033[0m but as root you can \033[32m-p 80,443,3923\033[0m when running behind a reverse-proxy, it's recommended to use unix-sockets for improved performance and security; \033[32m-i unix:770:www:\033[33m/dev/shm/party.sock\033[0m listens on \033[33m/dev/shm/party.sock\033[0m with permissions \033[33m0770\033[0m; only accessible to members of the \033[33mwww\033[0m group. This is the best approach. Alternatively, \033[32m-i unix:777:\033[33m/dev/shm/party.sock\033[0m sets perms \033[33m0777\033[0m so anyone can access it; bad unless it's inside a restricted folder \033[32m-i unix:\033[33m/dev/shm/party.sock\033[0m keeps umask-defined permission (usually \033[33m0600\033[0m) and the same user/group as copyparty \033[32m-i fd:\033[33m3\033[0m uses the socket passed to copyparty on file descriptor 3 \033[33m-p\033[0m (tcp ports) is ignored for unix-sockets and FDs """ ), ], [ "accounts", "accounts and volumes", dedent( """ -a takes username:password, -v takes src:dst:\033[33mperm\033[0m1:\033[33mperm\033[0m2:\033[33mperm\033[0mN:\033[32mvolflag\033[0m1:\033[32mvolflag\033[0m2:\033[32mvolflag\033[0mN:... * "\033[33mperm\033[0m" is "permissions,username1,username2,..." * "\033[32mvolflag\033[0m" is config flags to set on this volume --grp takes groupname:username1,username2,... and groupnames can be used instead of usernames in -v by prefixing the groupname with @ list of permissions: "r" (read): list folder contents, download files "w" (write): upload files; need "r" to see the uploads "m" (move): move files and folders; need "w" at destination "d" (delete): permanently delete files and folders "g" (get): download files, but cannot see folder contents "G" (upget): "get", but can see filekeys of their own uploads "h" (html): "get", but folders return their index.html "." (dots): user can ask to show dotfiles in listings "a" (admin): can see uploader IPs, config-reload "A" ("all"): same as "rwmda." (read/write/move/delete/admin/dotfiles) too many volflags to list here, see --help-flags example:\033[35m -a ed:hunter2 -v .::r:rw,ed -v ../inc:dump:w:rw,ed:c,nodupe \033[36m mount current directory at "/" with * r (read-only) for everyone * rw (read+write) for ed mount ../inc at "/dump" with * w (write-only) for everyone * rw (read+write) for ed * reject duplicate files \033[0m if no accounts or volumes are configured, current folder will be read/write for everyone the group \033[33m@acct\033[0m will always have every user with an account (the name of that group can be changed with \033[32m--grp-all\033[0m) to hide a volume from authenticated users, specify \033[33m*,-@acct\033[0m to subtract \033[33m@acct\033[0m from \033[33m*\033[0m (can subtract users from groups too) consider the config file for more flexible account/volume management, including dynamic reload at runtime (and being more readable w) see \033[32m--help-auth\033[0m for ways to provide the password in requests; see \033[32m--help-idp\033[0m for replacing it with SSO and auth-middlewares """ ), ], [ "auth", "how to login from a client", dedent( """ different ways to provide the password so you become authenticated: login with the ui: go to \033[36mhttp://127.0.0.1:3923/?h\033[0m and login there send the password in the '\033[36mPW\033[0m' http-header: \033[36mPW: \033[35mhunter2\033[0m or if you have \033[33m--usernames\033[0m enabled, \033[36mPW: \033[35med:hunter2\033[0m send the password in the URL itself: \033[36mhttp://127.0.0.1:3923/\033[35m?pw=hunter2\033[0m or if you have \033[33m--usernames\033[0m enabled, \033[36mhttp://127.0.0.1:3923/\033[35m?pw=ed:hunter2\033[0m use basic-authentication: \033[36mhttp://\033[35med:hunter2\033[36m@127.0.0.1:3923/\033[0m which should be the same as this header: \033[36mAuthorization: Basic \033[35mZWQ6aHVudGVyMg==\033[0m """ ), ], [ "auth-ord", "authentication precedence", dedent( """ \033[33m--auth-ord\033[0m is a comma-separated list of auth options (one or more of the [\033[35moptions\033[0m] below); first one wins [\033[35mpw\033[0m] is conventional login, for example the "\033[36mPW\033[0m" header, or the \033[36m?pw=\033[0m[...] URL-suffix, or a valid session cookie (see \033[33m--help-auth\033[0m) [\033[35midp\033[0m] is a username provided in the http-request-header defined by \033[33m--idp-h-usr\033[0m and/or \033[33m--idp-hm-usr\033[0m, which is provided by an authentication middleware such as authentik, authelia, tailscale, ... (see \033[33m--help-idp\033[0m) [\033[35midp-h\033[0m] is specifically an \033[33m--idp-h-usr\033[0m header, [\033[35midp-hm\033[0m] is specifically an \033[33m--idp-hm-usr\033[0m header; [\033[35midp\033[0m] is the same as [\033[35midp-hm,idp-h\033[0m] [\033[35mipu\033[0m] is a mapping from an IP-address to a username, auto-authing that client-IP to that account (see the description of \033[36m--ipu\033[0m in \033[33m--help\033[0m) NOTE: even if an option (\033[35mpw\033[0m/\033[35mipu\033[0m/...) is not in the list, it may still be enabled and can still take effect if none of the other alternatives identify the user NOTE: if [\033[35mipu\033[0m] is in the list, it must be FIRST or LAST NOTE: if [\033[35mpw\033[0m] is not in the list, the logout-button will be hidden when any idp feature is enabled """ ), ], [ "flags", "list of volflags", dedent( """ volflags are appended to volume definitions, for example, to create a write-only volume with the \033[33mnodupe\033[0m and \033[32mnosub\033[0m flags: \033[35m-v /mnt/inc:/inc:w\033[33m:c,nodupe\033[32m:c,nosub\033[0m if global config defines a volflag for all volumes, you can unset it for a specific volume with -flag """ ).rstrip() + build_flags_desc(), ], [ "handlers", "use plugins to handle certain events", dedent( """ usually copyparty returns a \033[33m404\033[0m if a file does not exist, and \033[33m403\033[0m if a user tries to access a file they don't have access to you can load a plugin which will be invoked right before this happens, and the plugin can choose to override this behavior load the plugin using --args or volflags; for example \033[36m --on404 ~/partyhandlers/not404.py -v .::r:c,on404=~/partyhandlers/not404.py \033[0m the file must define the function \033[35mmain(cli,vn,rem)\033[0m: \033[35mcli\033[0m: the copyparty HttpCli instance \033[35mvn\033[0m: the VFS which overlaps with the requested URL \033[35mrem\033[0m: the remainder of the URL below the VFS mountpoint `main` must return a string; one of the following: > \033[32m"true"\033[0m: the plugin has responded to the request, and the TCP connection should be kept open > \033[32m"false"\033[0m: the plugin has responded to the request, and the TCP connection should be terminated > \033[32m"retry"\033[0m: the plugin has done something to resolve the 404 situation, and copyparty should reattempt reading the file. if it still fails, a regular 404 will be returned > \033[32m"allow"\033[0m: should ignore the insufficient permissions and let the client continue anyways > \033[32m""\033[0m: the plugin has not handled the request; try the next plugin or return the usual 404 or 403 \033[1;35mPS!\033[0m the folder that contains the python file should ideally not contain many other python files, and especially nothing with filenames that overlap with modules used by copyparty """ ), ], [ "hooks", "execute commands before/after various events", dedent( """ execute a command (a program or script) before or after various events; \033[36mxbu\033[35m executes CMD before a file upload starts \033[36mxau\033[35m executes CMD after a file upload finishes \033[36mxiu\033[35m executes CMD after all uploads finish and volume is idle \033[36mxbc\033[35m executes CMD before a file copy \033[36mxac\033[35m executes CMD after a file copy \033[36mxbr\033[35m executes CMD before a file rename/move \033[36mxar\033[35m executes CMD after a file rename/move \033[36mxbd\033[35m executes CMD before a file delete \033[36mxad\033[35m executes CMD after a file delete \033[36mxm\033[35m executes CMD on message \033[36mxban\033[35m executes CMD if someone gets banned \033[0m can be defined as --args or volflags; for example \033[36m --xau foo.py -v .::r:c,xau=bar.py \033[0m hooks specified as commandline --args are appended to volflags; each commandline --arg and volflag can be specified multiple times, each hook will execute in order unless one returns non-zero, or "100" which means "stop daisychaining and return 0 (success/OK)" optionally prefix the command with comma-sep. flags similar to -mtp: \033[36mf\033[35m forks the process, doesn't wait for completion \033[36mc\033[35m checks return code, blocks the action if non-zero \033[36mj\033[35m provides json with info as 1st arg instead of filepath \033[36ms\033[35m provides input data on stdin (instead of 1st arg) \033[36mwN\033[35m waits N sec after command has been started before continuing \033[36mtN\033[35m sets an N sec timeout before the command is abandoned \033[36miN\033[35m xiu only: volume must be idle for N sec (default = 5) \033[36mI\033[35m import and run as module, not as subprocess \033[36mar\033[35m only run hook if user has read-access \033[36marw\033[35m only run hook if user has read-write-access \033[36marwmd\033[35m ...and so on... (doesn't work for xiu or xban) \033[36mkt\033[35m kills the entire process tree on timeout (default), \033[36mkm\033[35m kills just the main process \033[36mkn\033[35m lets it continue running until copyparty is terminated \033[36mc0\033[35m show all process output (default) \033[36mc1\033[35m show only stderr \033[36mc2\033[35m show only stdout \033[36mc3\033[35m mute all process output \033[0m examples: \033[36m--xm some.py\033[35m runs \033[33msome.py msgtxt\033[35m on each 📟 message; \033[33mmsgtxt\033[35m is the message that was written into the web-ui \033[36m--xm j,some.py\033[35m runs \033[33msome.py jsontext\033[35m on each 📟 message; \033[33mjsontext\033[35m is the message info (ip, user, ..., msg-text) \033[36m--xm aw,j,some.py\033[35m requires user to have write-access \033[36m--xm aw,,notify-send,hey,--\033[35m shows an OS alert on linux; the \033[33m,,\033[35m stops copyparty from reading the rest as flags and the \033[33m--\033[35m stops notify-send from reading the message as args and the alert will be "hey" followed by the messagetext \033[36m--xm s,,tee,-a,log.txt\033[35m appends each msg to log.txt; \033[36m--xm s,j,,tee,-a,log.txt\033[35m writes it as json instead \033[36m--xau zmq:pub:tcp://*:5556\033[35m announces uploads on zeromq; \033[36m--xau t3,zmq:push:tcp://*:5557\033[35m also works, and you can \033[36m--xau t3,j,zmq:req:tcp://localhost:5555\033[35m too for example \033[0m each hook is executed once for each event, except for \033[36mxiu\033[0m which builds up a backlog of uploads, running the hook just once as soon as the volume has been idle for iN seconds (5 by default) \033[36mxiu\033[0m is also unique in that it will pass the metadata to the executed program on STDIN instead of as argv arguments (so just like the \033[36ms\033[0m option does for the other hook types), and it also includes the wark (file-id/hash) as a json property \033[36mxban\033[0m can be used to overrule / cancel a user ban event; if the program returns 0 (true/OK) then the ban will NOT happen effects can be used to redirect uploads into other locations, and to delete or index other files based on new uploads, but with certain limitations. See bin/hooks/reloc* and docs/devnotes.md#hook-effects the \033[36mI\033[0m option will override most other options, because it entirely hands over control to the hook, which is then able to tamper with copyparty's internal memory and wreck havoc if it wants to -- but this is worh it because it makes the hook 140x faster except for \033[36mxm\033[0m, only one hook / one action can run at a time, so it's recommended to use the \033[36mf\033[0m flag unless you really need to wait for the hook to finish before continuing (without \033[36mf\033[0m the upload speed can easily drop to 10% for small files)""" ), ], [ "idp", "replacing the login system with fancy middleware", dedent( """ if you already have a centralized service which handles user-authentication for other services already, you can integrate copyparty with that for automatic login if the middleware is providing the username in an http-header named '\033[35mtheUsername\033[0m' then do this: \033[36m--idp-h-usr theUsername\033[0m if the middleware is providing a list of groups in the header named '\033[35mtheGroups\033[0m' then do this: \033[36m--idp-h-grp theGroup\033[0m if the list of groups is separated by '\033[35m%\033[0m' then \033[36m--idp-gsep %\033[0m if the middleware is providing a header named '\033[35mAccount\033[0m' and the value is '\033[35malice@forest.net\033[0m' but the username is actually '\033[35mmarisa\033[0m' then do this for each user: \033[36m--idp-hm-usr ^Account^alice@forest.net^marisa\033[0m (the separator '\033[35m^\033[0m' can be any character) make ABSOLUTELY SURE that the header can only be set by your middleware and not by clients! and, as an extra precaution, send a header named '\033[36mfinalmasterspark\033[0m' (a secret keyword) and then \033[36m--idp-h-key finalmasterspark\033[0m to require that the login/logout links/buttons can be replaced with links going to your IdP's UI; \033[36m--idp-login /login/?redir={dst}\033[0m will expand \033[36m{dst}\033[0m to the URL of the current page, so the IdP can redirect the user back to where they were """ ), ], [ "urlform", "how to handle url-form POSTs", dedent( """ values for --urlform: \033[36mstash\033[35m dumps the data to file and returns length + checksum \033[36msave,get\033[35m dumps to file and returns the page like a GET \033[36mprint \033[35m prints the data to log and returns an error \033[36mprint,xm \033[35m prints the data to log and returns --xm output \033[36mprint,get\033[35m prints the data to log and returns GET\033[0m note that the \033[35m--xm\033[0m hook will only run if \033[35m--urlform\033[0m is either \033[36mprint\033[0m or \033[36mprint,get\033[0m or the default \033[36mprint,xm\033[0m if an \033[35m--xm\033[0m hook returns text, then the response code will be HTTP 202; http/get responses will be HTTP 200 if there are multiple \033[35m--xm\033[0m hooks defined, then the first hook that produced output is returned if there are no \033[35m--xm\033[0m hooks defined, then the default \033[36mprint,xm\033[0m behaves like \033[36mprint,get\033[0m (returning html) """ ), ], [ "exp", "text expansion", dedent( """ specify --exp or the "exp" volflag to enable placeholder expansions in README.md / PREADME.md / .prologue.html / .epilogue.html --exp-md (volflag exp_md) holds the list of placeholders which can be expanded in READMEs, and --exp-lg (volflag exp_lg) likewise for logues; any placeholder not given in those lists will be ignored and shown as-is the default list will expand the following placeholders: \033[36m{{self.ip}} \033[35mclient ip \033[36m{{self.ua}} \033[35mclient user-agent \033[36m{{self.uname}} \033[35mclient username \033[36m{{self.host}} \033[35mthe "Host" header, or the server's external IP otherwise \033[36m{{cfg.name}} \033[35mthe --name global-config \033[36m{{cfg.logout}} \033[35mthe --logout global-config \033[36m{{vf.scan}} \033[35mthe "scan" volflag \033[36m{{vf.thsize}} \033[35mthumbnail size \033[36m{{srv.itime}} \033[35mserver time in seconds \033[36m{{srv.htime}} \033[35mserver time as YY-mm-dd, HH:MM:SS (UTC) \033[36m{{hdr.cf-ipcountry}} \033[35mthe "CF-IPCountry" client header (probably blank) \033[0m so the following types of placeholders can be added to the lists: * any client header can be accessed through {{hdr.*}} * any variable in httpcli.py can be accessed through {{self.*}} * any global server setting can be accessed through {{cfg.*}} * any volflag can be accessed through {{vf.*}} remove vf.scan from default list using --exp-md /vf.scan add "accept" header to def. list using --exp-md +hdr.accept for performance reasons, expansion only happens while embedding documents into directory listings, and when accessing a ?doc=... link, but never otherwise, so if you click a -txt- link you'll have to refresh the page to apply expansion """ ), ], [ "ls", "volume inspection", dedent( """ \033[35m--ls USR,VOL,FLAGS \033[36mUSR\033[0m is a user to browse as; * is anonymous, ** is all users \033[36mVOL\033[0m is a single volume to scan, default is * (all vols) \033[36mFLAG\033[0m is flags; \033[36mv\033[0m in addition to realpaths, print usernames and vpaths \033[36mln\033[0m only prints symlinks leaving the volume mountpoint \033[36mp\033[0m exits 1 if any such symlinks are found \033[36mr\033[0m resumes startup after the listing examples: --ls '**' # list all files which are possible to read --ls '**,*,ln' # check for dangerous symlinks --ls '**,*,ln,p,r' # check, then start normally if safe """ ), ], [ "dbd", "database durability profiles", dedent( """ mainly affects uploads of many small files on slow HDDs; speeds measured uploading 520 files on a WD20SPZX (SMR 2.5" 5400rpm 4kb) \033[32macid\033[0m = extremely safe but slow; the old default. Should never lose any data no matter what \033[32mswal\033[0m = 2.4x faster uploads yet 99.9% as safe -- theoretical chance of losing metadata for the ~200 most recently uploaded files if there's a power-loss or your OS crashes \033[32mwal\033[0m = another 21x faster on HDDs yet 90% as safe; same pitfall as \033[33mswal\033[0m except more likely \033[32myolo\033[0m = another 1.5x faster, and removes the occasional sudden upload-pause while the disk syncs, but now you're at risk of losing the entire database in a powerloss / OS-crash profiles can be set globally (--dbd=yolo), or per-volume with volflags: -v ~/Music:music:r:c,dbd=acid """ ), ], [ "chmod", "file/folder permissions", dedent( """ global-option \033[33m--chmod-f\033[0m and volflag \033[33mchmod_f\033[0m specifies the unix-permission to use when creating a new file similarly, \033[33m--chmod-d\033[0m and \033[33mchmod_d\033[0m sets the directory/folder perm the value is a three- or four-digit octal number such as \033[32m755\033[0m, \033[32m0644\033[0m, \033[32m2750\033[0m, etc. if 3 digits: User, Group, Other if 4 digits: Special, User, Group, Other "Special" digit (sum of the following): \033[32m1\033[0m = sticky (files: n/a; dirs: files in directory can be deleted only by their owners) \033[32m2\033[0m = setgid (files: run executable as file group; dirs: files inherit group from directory) \033[32m4\033[0m = setuid (files: run executable as file owner; dirs: n/a) "User", "Group", "Other" digits for files: \033[32m0\033[0m = \033[35m---\033[0m = no access \033[32m1\033[0m = \033[35m--x\033[0m = can execute the file as a program \033[32m2\033[0m = \033[35m-w-\033[0m = can write \033[32m3\033[0m = \033[35m-wx\033[0m = can write and execute \033[32m4\033[0m = \033[35mr--\033[0m = can read \033[32m5\033[0m = \033[35mr-x\033[0m = can read and execute \033[32m6\033[0m = \033[35mrw-\033[0m = can read and write \033[32m7\033[0m = \033[35mrwx\033[0m = can read, write, execute "User", "Group", "Other" digits for directories/folders: \033[32m0\033[0m = \033[35m---\033[0m = no access \033[32m1\033[0m = \033[35m--x\033[0m = can read files in folder but not list contents \033[32m2\033[0m = \033[35m-w-\033[0m = n/a \033[32m3\033[0m = \033[35m-wx\033[0m = can create files but not list \033[32m4\033[0m = \033[35mr--\033[0m = can list, but not read/write \033[32m5\033[0m = \033[35mr-x\033[0m = can list and read files \033[32m6\033[0m = \033[35mrw-\033[0m = n/a \033[32m7\033[0m = \033[35mrwx\033[0m = can read, write, list """ ), ], [ "pwhash", "password hashing", dedent( """ when \033[36m--ah-alg\033[0m is not the default [\033[32mnone\033[0m], all account passwords must be hashed passwords can be hashed on the commandline with \033[36m--ah-gen\033[0m, but copyparty will also hash and print any passwords that are non-hashed (password which do not start with '+') and then terminate afterwards if you have enabled --usernames then the password must be provided as username:password for hashing \033[36m--ah-alg\033[0m specifies the hashing algorithm and a list of optional comma-separated arguments: \033[36m--ah-alg argon2\033[0m # which is the same as: \033[36m--ah-alg argon2,3,256,4,19\033[0m use argon2id with timecost 3, 256 MiB, 4 threads, version 19 (0x13/v1.3) \033[36m--ah-alg scrypt\033[0m # which is the same as: \033[36m--ah-alg scrypt,13,2,8,4,32\033[0m use scrypt with cost 2**13, 2 iterations, blocksize 8, 4 threads, and allow using up to 32 MiB RAM (ram=cost*blksz roughly) \033[36m--ah-alg sha2\033[0m # which is the same as: \033[36m--ah-alg sha2,424242\033[0m use sha2-512 with 424242 iterations recommended: \033[32m--ah-alg argon2\033[0m (takes about 0.4 sec and 256M RAM to process a new password) argon2 needs python-package argon2-cffi, scrypt needs openssl, sha2 is always available """ ), ], [ "zm", "mDNS debugging", dedent( """ the mDNS protocol is multicast-based, which means there are thousands of fun and interesting ways for it to break unexpectedly things to check if it does not work at all: * is there a firewall blocking port 5353 on either the server or client? (for example, clients may be able to send queries to copyparty, but the replies could get lost) * is multicast accidentally disabled on either the server or client? (look for mDNS log messages saying "new client on [...]") * the router/switch must be multicast and igmp capable things to check if it works for a while but then it doesn't: * is there a firewall blocking port 5353 on either the server or client? (copyparty may be unable to see the queries from the clients, but the clients may still be able to see the initial unsolicited announce, so it works for about 2 minutes after startup until TTL expires) * does the client have multiple IPs on its interface, and some of the IPs are in subnets which the copyparty server is not a member of? for both of the above intermittent issues, try --zm-spam 30 (not spec-compliant but nothing will mind) """ ), ], ] def build_flags_desc(): ret = "" for grp, flags in flagcats.items(): ret += "\n\n\033[0m" + grp for k, v in flags.items(): v = v.replace("\n", "\n ") ret += "\n \033[36m{}\033[35m {}".format(k, v) return ret # fmt: off def add_general(ap, nc, srvname): ap2 = ap.add_argument_group("general options") ap2.add_argument("-c", metavar="PATH", type=u, default=CFG_DEF, action="append", help="\033[34mREPEATABLE:\033[0m add config file") ap2.add_argument("-nc", metavar="NUM", type=int, default=nc, help="max num clients") ap2.add_argument("-a", metavar="ACCT", type=u, action="append", help="\033[34mREPEATABLE:\033[0m add account, \033[33mUSER\033[0m:\033[33mPASS\033[0m; example [\033[32med:wark\033[0m]") ap2.add_argument("-v", metavar="VOL", type=u, action="append", help="\033[34mREPEATABLE:\033[0m add volume, \033[33mSRC\033[0m:\033[33mDST\033[0m:\033[33mFLAG\033[0m; examples [\033[32m.::r\033[0m], [\033[32m/mnt/nas/music:/music:r:aed\033[0m], see --help-accounts") ap2.add_argument("--grp", metavar="G:N,N", type=u, action="append", help="\033[34mREPEATABLE:\033[0m add group, \033[33mNAME\033[0m:\033[33mUSER1\033[0m,\033[33mUSER2\033[0m,\033[33m...\033[0m; example [\033[32madmins:ed,foo,bar\033[0m]") ap2.add_argument("--usernames", action="store_true", help="require username and password for login; default is just password") ap2.add_argument("--chdir", metavar="PATH", type=u, help="change working-directory to \033[33mPATH\033[0m before mapping volumes") ap2.add_argument("-ed", action="store_true", help="enable the ?dots url parameter / client option which allows clients to see dotfiles / hidden files (volflag=dots)") ap2.add_argument("--urlform", metavar="MODE", type=u, default="print,xm", help="how to handle url-form POSTs; see \033[33m--help-urlform\033[0m") ap2.add_argument("--wintitle", metavar="TXT", type=u, default="cpp @ $pub", help="server terminal title, for example [\033[32m$ip-10.1.2.\033[0m] or [\033[32m$ip-]") ap2.add_argument("--name", metavar="TXT", type=u, default=srvname, help="server name (displayed topleft in browser and in mDNS)") ap2.add_argument("--name-url", metavar="TXT", type=u, help="URL for server name hyperlink (displayed topleft in browser)") ap2.add_argument("--name-html", type=u, help=argparse.SUPPRESS) ap2.add_argument("--site", metavar="URL", type=u, default="", help="public URL to assume when creating links; example: [\033[32mhttps://example.com/\033[0m]") ap2.add_argument("--mime", metavar="EXT=MIME", type=u, action="append", help="\033[34mREPEATABLE:\033[0m map file \033[33mEXT\033[0mension to \033[33mMIME\033[0mtype, for example [\033[32mjpg=image/jpeg\033[0m]") ap2.add_argument("--mimes", action="store_true", help="list default mimetype mapping and exit") ap2.add_argument("--rmagic", action="store_true", help="do expensive analysis to improve accuracy of returned mimetypes; will make file-downloads, rss, and webdav slower (volflag=rmagic)") ap2.add_argument("-j", metavar="CORES", type=int, default=1, help="num cpu-cores for uploads/downloads (0=all); keeping the default is almost always best") ap2.add_argument("--vc-url", metavar="URL", type=u, default="", help="URL to check for vulnerable versions (default-disabled)") ap2.add_argument("--vc-age", metavar="HOURS", type=int, default=3, help="how many hours to wait between vulnerability checks") ap2.add_argument("--vc-exit", action="store_true", help="panic and exit if current version is vulnerable") ap2.add_argument("--license", action="store_true", help="show licenses and exit") ap2.add_argument("--version", action="store_true", help="show versions and exit") ap2.add_argument("--versionb", action="store_true", help="show version and exit") def add_qr(ap, tty): ap2 = ap.add_argument_group("qr options") ap2.add_argument("--qr", action="store_true", help="show QR-code on startup") ap2.add_argument("--qrs", action="store_true", help="change the QR-code URL to https://") ap2.add_argument("--qrl", metavar="PATH", type=u, default="", help="location to include in the url, for example [\033[32mpriv/?pw=hunter2\033[0m]") ap2.add_argument("--qri", metavar="PREFIX", type=u, default="", help="select IP which starts with \033[33mPREFIX\033[0m; [\033[32m.\033[0m] to force default IP when mDNS URL would have been used instead") ap2.add_argument("--qr-fg", metavar="COLOR", type=int, default=0 if tty else 16, help="foreground; try [\033[32m0\033[0m] or [\033[32m-1\033[0m] if the qr-code is unreadable") ap2.add_argument("--qr-bg", metavar="COLOR", type=int, default=229, help="background (white=255)") ap2.add_argument("--qrp", metavar="CELLS", type=int, default=4, help="padding (spec says 4 or more, but 1 is usually fine)") ap2.add_argument("--qrz", metavar="N", type=int, default=0, help="[\033[32m1\033[0m]=1x, [\033[32m2\033[0m]=2x, [\033[32m0\033[0m]=auto (try [\033[32m2\033[0m] on broken fonts)") ap2.add_argument("--qr-pin", metavar="N", type=int, default=0, help="sticky/pin the qr-code to always stay on-screen; [\033[32m0\033[0m]=disabled, [\033[32m1\033[0m]=with-url, [\033[32m2\033[0m]=just-qr") ap2.add_argument("--qr-wait", metavar="SEC", type=float, default=0, help="wait \033[33mSEC\033[0m before printing the qr-code to the log") ap2.add_argument("--qr-every", metavar="SEC", type=float, default=0, help="print the qr-code every \033[33mSEC\033[0m (try this with/without --qr-pin in case of issues)") ap2.add_argument("--qr-winch", metavar="SEC", type=float, default=0, help="when --qr-pin is enabled, check for terminal size change every \033[33mSEC\033[0m") ap2.add_argument("--qr-file", metavar="TXT", type=u, action="append", help="\033[34mREPEATABLE:\033[0m write qr-code to file.\n └─To create txt or svg, \033[33mTXT\033[0m is Filepath:Zoom:Pad, for example [\033[32mqr.txt:1:2\033[0m]\n └─To create png or gif, \033[33mTXT\033[0m is Filepath:Zoom:Pad:Foreground:Background, for example [\033[32mqr.png:8:2:333333:ffcc55\033[0m], or [\033[32mqr.png:8:2::ffcc55\033[0m] for transparent") ap2.add_argument("--qr-stdout", action="store_true", help="always display the QR-code on STDOUT in the terminal, even if \033[33m-q\033[0m") ap2.add_argument("--qr-stderr", action="store_true", help="always display the QR-code on STDERR in the terminal, even if \033[33m-q\033[0m") def add_fs(ap): ap2 = ap.add_argument_group("filesystem options") rm_re_def = "15/0.1" if ANYWIN else "0/0" ap2.add_argument("--casechk", metavar="N", type=u, default="auto", help="detect and prevent CI (case-insensitive) behavior if the underlying filesystem is CI? [\033[32my\033[0m] = detect and prevent, [\033[32mn\033[0m] = ignore and allow, [\033[32mauto\033[0m] = \033[32my\033[0m if CI fs detected. NOTE: \033[32my\033[0m is very slow but necessary for correct WebDAV behavior on Windows/Macos (volflag=casechk)") ap2.add_argument("--fsnt", metavar="OS", type=u, default="auto", help="which characters to allow in file/folder names; [\033[32mwin\033[0m] = windows (not <>:|?*\"\\/), [\033[32mmac\033[0m] = macos (not :), [\033[32mlin\033[0m] = linux (anything goes) (volflag=fsnt)") ap2.add_argument("--rm-retry", metavar="T/R", type=u, default=rm_re_def, help="if a file cannot be deleted because it is busy, continue trying for \033[33mT\033[0m seconds, retry every \033[33mR\033[0m seconds; disable with 0/0 (volflag=rm_retry)") ap2.add_argument("--mv-retry", metavar="T/R", type=u, default=rm_re_def, help="if a file cannot be renamed because it is busy, continue trying for \033[33mT\033[0m seconds, retry every \033[33mR\033[0m seconds; disable with 0/0 (volflag=mv_retry)") ap2.add_argument("--iobuf", metavar="BYTES", type=int, default=256*1024, help="file I/O buffer-size; if your volumes are on a network drive, try increasing to \033[32m524288\033[0m or even \033[32m4194304\033[0m (and let me know if that improves your performance)") ap2.add_argument("--mtab-age", metavar="SEC", type=int, default=60, help="rebuild mountpoint cache every \033[33mSEC\033[0m to keep track of sparse-files support; keep low on servers with removable media") def add_share(ap): db_path = os.path.join(E.cfg, "shares.db") ap2 = ap.add_argument_group("share-url options") ap2.add_argument("--shr", metavar="DIR", type=u, default="", help="toplevel virtual folder for shared files/folders, for example [\033[32m/share\033[0m]") ap2.add_argument("--shr-db", metavar="FILE", type=u, default=db_path, help="database to store shares in") ap2.add_argument("--shr-who", metavar="TXT", type=u, default="auth", help="who can create a share? [\033[32mno\033[0m]=nobody, [\033[32ma\033[0m]=admin-permission, [\033[32mauth\033[0m]=authenticated (volflag=shr_who)") ap2.add_argument("--shr-adm", metavar="U,U", type=u, default="", help="comma-separated list of users allowed to view/delete any share") ap2.add_argument("--shr-rt", metavar="MIN", type=int, default=1440, help="shares can be revived by their owner if they expired less than MIN minutes ago; [\033[32m60\033[0m]=hour, [\033[32m1440\033[0m]=day, [\033[32m10080\033[0m]=week") ap2.add_argument("--shr-site", metavar="URL", type=u, default="--site", help="public URL to assume when creating share-links; example: [\033[32mhttps://example.com/\033[0m]") ap2.add_argument("--shr-v", action="store_true", help="debug") def add_upload(ap): ap2 = ap.add_argument_group("upload options") ap2.add_argument("--dotpart", action="store_true", help="dotfile incomplete uploads, hiding them from clients unless \033[33m-ed\033[0m") ap2.add_argument("--plain-ip", action="store_true", help="when avoiding filename collisions by appending the uploader's ip to the filename: append the plaintext ip instead of salting and hashing the ip") ap2.add_argument("--up-site", metavar="URL", type=u, default="--site", help="public URL to assume when creating links to uploaded files; example: [\033[32mhttps://example.com/\033[0m]") ap2.add_argument("--put-name", metavar="TXT", type=u, default="put-{now.6f}-{cip}.bin", help="filename for nameless uploads (when uploader doesn't provide a name); default is [\033[32mput-UNIXTIME-IP.bin\033[0m] (the \033[32m.6f\033[0m means six decimal places) (volflag=put_name)") ap2.add_argument("--put-ck", metavar="ALG", type=u, default="sha512", help="default checksum-hasher for PUT/WebDAV uploads: no / md5 / sha1 / sha256 / sha512 / b2 / blake2 / b2s / blake2s (volflag=put_ck)") ap2.add_argument("--bup-ck", metavar="ALG", type=u, default="sha512", help="default checksum-hasher for bup/basic-uploader: no / md5 / sha1 / sha256 / sha512 / b2 / blake2 / b2s / blake2s (volflag=bup_ck)") ap2.add_argument("--unpost", metavar="SEC", type=int, default=3600*12, help="grace period where uploads can be deleted by the uploader, even without delete permissions; 0=disabled, default=12h") ap2.add_argument("--unp-who", metavar="NUM", type=int, default=1, help="clients can undo recent uploads by using the unpost tab (requires \033[33m-e2d\033[0m). [\033[32m0\033[0m] = never allowed (disable feature), [\033[32m1\033[0m] = allow if client has the same IP as the upload AND is using the same account, [\033[32m2\033[0m] = just check the IP, [\033[32m3\033[0m] = just check account-name (volflag=unp_who)") ap2.add_argument("--apnd-who", metavar="NUM", type=u, default="dw", help="who can append to existing files? [\033[32mno\033[0m]=nobody, [\033[32maw\033[0m]=admin+write, [\033[32mdw\033[0m]=delete+write, [\033[32mw\033[0m]=write (volflag=apnd_who)") ap2.add_argument("--u2abort", metavar="NUM", type=int, default=1, help="clients can abort incomplete uploads by using the unpost tab (requires \033[33m-e2d\033[0m). [\033[32m0\033[0m] = never allowed (disable feature), [\033[32m1\033[0m] = allow if client has the same IP as the upload AND is using the same account, [\033[32m2\033[0m] = just check the IP, [\033[32m3\033[0m] = just check account-name (volflag=u2abort)") ap2.add_argument("--blank-wt", metavar="SEC", type=int, default=300, help="file write grace period (any client can write to a blank file last-modified more recently than \033[33mSEC\033[0m seconds ago)") ap2.add_argument("--reg-cap", metavar="N", type=int, default=38400, help="max number of uploads to keep in memory when running without \033[33m-e2d\033[0m; roughly 1 MiB RAM per 600") ap2.add_argument("--no-fpool", action="store_true", help="disable file-handle pooling -- instead, repeatedly close and reopen files during upload (bad idea to enable this on windows and/or cow filesystems)") ap2.add_argument("--use-fpool", action="store_true", help="force file-handle pooling, even when it might be dangerous (multiprocessing, filesystems lacking sparse-files support, ...)") ap2.add_argument("--chmod-f", metavar="UGO", type=u, default="", help="unix file permissions to use when creating files; default is probably 644 (OS-decided), see --help-chmod. Examples: [\033[32m644\033[0m] = owner-RW + all-R, [\033[32m755\033[0m] = owner-RWX + all-RX, [\033[32m777\033[0m] = full-yolo (volflag=chmod_f)") ap2.add_argument("--chmod-d", metavar="UGO", type=u, default="755", help="unix file permissions to use when creating directories; see --help-chmod. Examples: [\033[32m755\033[0m] = owner-RW + all-R, [\033[32m2750\033[0m] = setgid + owner-RW + group-R, [\033[32m777\033[0m] = full-yolo (volflag=chmod_d)") ap2.add_argument("--uid", metavar="N", type=int, default=-1, help="unix user-id to chown new files/folders to; default = -1 = do-not-change (volflag=uid)") ap2.add_argument("--gid", metavar="N", type=int, default=-1, help="unix group-id to chown new files/folders to; default = -1 = do-not-change (volflag=gid)") ap2.add_argument("--wram", action="store_true", help="allow uploading even if a volume is inside a ramdisk, meaning that all data will be lost on the next server reboot (volflag=wram)") ap2.add_argument("--dedup", action="store_true", help="enable symlink-based upload deduplication (volflag=dedup)") ap2.add_argument("--safe-dedup", metavar="N", type=int, default=50, help="how careful to be when deduplicating files; [\033[32m1\033[0m] = just verify the filesize, [\033[32m50\033[0m] = verify file contents have not been altered (volflag=safededup)") ap2.add_argument("--hardlink", action="store_true", help="enable hardlink-based dedup; will fallback on symlinks when that is impossible (across filesystems) (volflag=hardlink)") ap2.add_argument("--hardlink-only", action="store_true", help="do not fallback to symlinks when a hardlink cannot be made (volflag=hardlinkonly)") ap2.add_argument("--reflink", action="store_true", help="enable reflink-based dedup; will fallback on full copies when that is impossible (non-CoW filesystem) (volflag=reflink)") ap2.add_argument("--no-dupe", action="store_true", help="reject duplicate files during upload; only matches within the same volume (volflag=nodupe)") ap2.add_argument("--no-dupe-m", action="store_true", help="also reject dupes when moving a file into another volume (volflag=nodupem)") ap2.add_argument("--no-clone", action="store_true", help="do not use existing data on disk to satisfy dupe uploads; reduces server HDD reads in exchange for much more network load (volflag=noclone)") ap2.add_argument("--no-snap", action="store_true", help="disable snapshots -- forget unfinished uploads on shutdown; don't create .hist/up2k.snap files -- abandoned/interrupted uploads must be cleaned up manually") ap2.add_argument("--snap-wri", metavar="SEC", type=int, default=300, help="write upload state to ./hist/up2k.snap every \033[33mSEC\033[0m seconds; allows resuming incomplete uploads after a server crash") ap2.add_argument("--snap-drop", metavar="MIN", type=float, default=1440.0, help="forget unfinished uploads after \033[33mMIN\033[0m minutes; impossible to resume them after that (360=6h, 1440=24h)") ap2.add_argument("--rm-partial", action="store_true", help="delete the .PARTIAL file when an unfinished upload expires after \033[33m--snap-drop\033[0m (volflag=rm_partial)") ap2.add_argument("--u2ts", metavar="TXT", type=u, default="c", help="how to timestamp uploaded files; [\033[32mc\033[0m]=client-last-modified, [\033[32mu\033[0m]=upload-time, [\033[32mfc\033[0m]=force-c, [\033[32mfu\033[0m]=force-u (volflag=u2ts)") ap2.add_argument("--rotf-tz", metavar="TXT", type=u, default="UTC", help="default timezone for the rotf upload rule; examples: [\033[32mEurope/Oslo\033[0m], [\033[32mAmerica/Toronto\033[0m], [\033[32mAntarctica/South_Pole\033[0m] (volflag=rotf_tz)") ap2.add_argument("--rand", action="store_true", help="force randomized filenames, \033[33m--nrand\033[0m chars long (volflag=rand)") ap2.add_argument("--nrand", metavar="NUM", type=int, default=9, help="randomized filenames length (volflag=nrand)") ap2.add_argument("--magic", action="store_true", help="enable filetype detection on nameless uploads (volflag=magic)") ap2.add_argument("--df", metavar="GiB", type=u, default="0", help="ensure \033[33mGiB\033[0m free disk space by rejecting upload requests; assumes gigabytes unless a unit suffix is given: [\033[32m256m\033[0m], [\033[32m4\033[0m], [\033[32m2T\033[0m] (volflag=df)") ap2.add_argument("--sparse", metavar="MiB", type=int, default=4, help="windows-only: minimum size of incoming uploads through up2k before they are made into sparse files") ap2.add_argument("--turbo", metavar="LVL", type=int, default=0, help="configure turbo-mode in up2k client; [\033[32m-1\033[0m] = forbidden/always-off, [\033[32m0\033[0m] = default-off and warn if enabled, [\033[32m1\033[0m] = default-off, [\033[32m2\033[0m] = on, [\033[32m3\033[0m] = on and disable datecheck") ap2.add_argument("--nosubtle", metavar="N", type=int, default=0, help="when to use a wasm-hasher instead of the browser's builtin; faster on chrome, but buggy in older chrome versions. [\033[32m0\033[0m] = only when necessary (non-https), [\033[32m1\033[0m] = always (all browsers), [\033[32m2\033[0m] = always on chrome/firefox, [\033[32m3\033[0m] = always on chrome, [\033[32mN\033[0m] = chrome-version N and newer (recommendation: 137)") ap2.add_argument("--u2j", metavar="JOBS", type=int, default=2, help="web-client: number of file chunks to upload in parallel; 1 or 2 is good when latency is low (same-country), 2~4 for android-clients, 2~6 for cross-atlantic. Max is 6 in most browsers. Big values increase network-speed but may reduce HDD-speed") ap2.add_argument("--u2sz", metavar="N,N,N", type=u, default="1,64,96", help="web-client: default upload chunksize (MiB); sets \033[33mmin,default,max\033[0m in the settings gui. Each HTTP POST will aim for \033[33mdefault\033[0m, and never exceed \033[33mmax\033[0m. Cloudflare max is 96. Big values are good for cross-atlantic but may increase HDD fragmentation on some FS. Disable this optimization with [\033[32m1,1,1\033[0m]") ap2.add_argument("--u2ow", metavar="NUM", type=int, default=0, help="web-client: default setting for when to replace/overwrite existing files; [\033[32m0\033[0m]=never, [\033[32m1\033[0m]=if-client-newer, [\033[32m2\033[0m]=always (volflag=u2ow)") ap2.add_argument("--u2sort", metavar="TXT", type=u, default="s", help="upload order; [\033[32ms\033[0m]=smallest-first, [\033[32mn\033[0m]=alphabetical, [\033[32mfs\033[0m]=force-s, [\033[32mfn\033[0m]=force-n -- alphabetical is a bit slower on fiber/LAN but makes it easier to eyeball if everything went fine") ap2.add_argument("--write-uplog", action="store_true", help="write POST reports to textfiles in working-directory") def add_network(ap): ap2 = ap.add_argument_group("network options") ap2.add_argument("-i", metavar="IP", type=u, default="::", help="IPs and/or unix-sockets to listen on (comma-separated list; see \033[33m--help-bind\033[0m). Default: all IPv4 and IPv6") ap2.add_argument("-p", metavar="PORT", type=u, default="3923", help="ports to listen on (comma/range); ignored for unix-sockets") ap2.add_argument("--ll", action="store_true", help="include link-local IPv4/IPv6 in mDNS replies, even if the NIC has routable IPs (breaks some mDNS clients)") ap2.add_argument("--rproxy", metavar="DEPTH", type=int, default=9999999, help="which ip to associate clients with; [\033[32m0\033[0m]=tcp, [\033[32m1\033[0m]=origin (first x-fwd, unsafe), [\033[32m-1\033[0m]=closest-proxy, [\033[32m-2\033[0m]=second-hop, [\033[32m-3\033[0m]=third-hop") ap2.add_argument("--xff-hdr", metavar="NAME", type=u, default="x-forwarded-for", help="if reverse-proxied, which http header to read the client's real ip from") ap2.add_argument("--xf-host", metavar="NAME", type=u, default="x-forwarded-host", help="if reverse-proxied, which http header to read the correct Host value from; this header must contain the server's external domain name") ap2.add_argument("--xf-proto", metavar="NAME", type=u, default="x-forwarded-proto", help="if reverse-proxied, which http header to read the correct protocol value from; this header must contain either 'http' or 'https'") ap2.add_argument("--xf-proto-fb", metavar="T", type=u, default="", help="protocol to assume if the X-Forwarded-Proto header (\033[33m--xf-proto\033[0m) is not provided by the reverseproxy; either 'http' or 'https'") ap2.add_argument("--xff-src", metavar="CIDR", type=u, default="127.0.0.0/8, ::1/128", help="list of trusted reverse-proxy CIDRs (comma-separated); only accept the real-ip header (\033[33m--xff-hdr\033[0m) and IdP headers if the incoming connection is from an IP within either of these subnets. Specify [\033[32mlan\033[0m] to allow all LAN / private / non-internet IPs. Can be disabled with [\033[32many\033[0m] if you are behind cloudflare (or similar) and are using \033[32m--xff-hdr=cf-connecting-ip\033[0m (or similar)") ap2.add_argument("--ipa", metavar="CIDR", type=u, default="", help="only accept connections from IP-addresses inside \033[33mCIDR\033[0m (comma-separated); examples: [\033[32mlan\033[0m] or [\033[32m10.89.0.0/16, 192.168.33.0/24\033[0m]\n └─for performance and security, this only looks at the TCP/Network-level IP, and will NOT work behind a reverseproxy") ap2.add_argument("--ipar", metavar="CIDR", type=u, default="", help="only accept connections from IP-addresses inside \033[33mCIDR\033[0m (comma-separated).\n └─this is reverseproxy-compatible; reads client-IP from 'X-Forwarded-For' if possible, with TCP/Network IP as fallback") ap2.add_argument("--rp-loc", metavar="PATH", type=u, default="", help="if reverse-proxying on a location instead of a dedicated domain/subdomain, provide the base location here; example: [\033[32m/foo/bar\033[0m]") ap2.add_argument("--cachectl", metavar="TXT", default="no-cache", help="default-value of the 'Cache-Control' response-header (controls caching in webbrowsers). Default prevents repeated downloading of the same file unless necessary (browser will ask copyparty if the file has changed). Examples: [\033[32mmax-age=604869\033[0m] will cache for 7 days, [\033[32mno-store, max-age=0\033[0m] will always redownload. (volflag=cachectl)") ap2.add_argument("--http-vary", metavar="TXT", type=u, default="Origin, PW, Cookie", help="value of the 'Vary' response-header; a hint for caching proxies") ap2.add_argument("--http-no-tcp", action="store_true", help="do not listen on TCP/IP for http/https; only listen on unix-domain-sockets") if ANYWIN: ap2.add_argument("--reuseaddr", action="store_true", help="set reuseaddr on listening sockets on windows; allows rapid restart of copyparty at the expense of being able to accidentally start multiple instances") elif not MACOS: ap2.add_argument("--freebind", action="store_true", help="allow listening on IPs which do not yet exist, for example if the network interfaces haven't finished going up. Only makes sense for IPs other than '0.0.0.0', '127.0.0.1', '::', and '::1'. May require running as root (unless net.ipv6.ip_nonlocal_bind)") ap2.add_argument("--wr-h-eps", metavar="PATH", type=u, default="", help="write list of listening-on ip:port to textfile at \033[33mPATH\033[0m when http-servers have started") ap2.add_argument("--wr-h-aon", metavar="PATH", type=u, default="", help="write list of accessible-on ip:port to textfile at \033[33mPATH\033[0m when http-servers have started") ap2.add_argument("--s-thead", metavar="SEC", type=int, default=120, help="socket timeout (read request header)") ap2.add_argument("--s-tbody", metavar="SEC", type=float, default=128.0, help="socket timeout (read/write request/response bodies). Use 60 on fast servers (default is extremely safe). Disable with 0 if reverse-proxied for a 2%% speed boost") ap2.add_argument("--s-rd-sz", metavar="B", type=int, default=256*1024, help="socket read size in bytes (indirectly affects filesystem writes; recommendation: keep equal-to or lower-than \033[33m--iobuf\033[0m)") ap2.add_argument("--s-wr-sz", metavar="B", type=int, default=256*1024, help="socket write size in bytes") ap2.add_argument("--s-wr-slp", metavar="SEC", type=float, default=0.0, help="debug: socket write delay in seconds") ap2.add_argument("--rsp-slp", metavar="SEC", type=float, default=0.0, help="debug: response delay in seconds") ap2.add_argument("--rsp-jtr", metavar="SEC", type=float, default=0.0, help="debug: response delay, random duration 0..\033[33mSEC\033[0m") def add_tls(ap, cert_path): ap2 = ap.add_argument_group("SSL/TLS options") ap2.add_argument("--http-only", action="store_true", help="disable ssl/tls -- force plaintext") ap2.add_argument("--https-only", action="store_true", help="disable plaintext -- force tls") ap2.add_argument("--cert", metavar="PATH", type=u, default=cert_path, help="path to file containing a concatenation of TLS key and certificate chain") ap2.add_argument("--ssl-ver", metavar="LIST", type=u, default="", help="set allowed ssl/tls versions; [\033[32mhelp\033[0m] shows available versions; default is what your python version considers safe") ap2.add_argument("--ciphers", metavar="LIST", type=u, default="", help="set allowed ssl/tls ciphers; [\033[32mhelp\033[0m] shows available ciphers") ap2.add_argument("--ssl-dbg", action="store_true", help="dump some tls info") ap2.add_argument("--ssl-log", metavar="PATH", type=u, default="", help="log master secrets for later decryption in wireshark") def add_cert(ap, cert_path): cert_dir = os.path.dirname(cert_path) ap2 = ap.add_argument_group("TLS certificate generator options") ap2.add_argument("--no-crt", action="store_true", help="disable automatic certificate creation") ap2.add_argument("--crt-ns", metavar="N,N", type=u, default="", help="comma-separated list of FQDNs (domains) to add into the certificate") ap2.add_argument("--crt-exact", action="store_true", help="do not add wildcard entries for each \033[33m--crt-ns\033[0m") ap2.add_argument("--crt-noip", action="store_true", help="do not add autodetected IP addresses into cert") ap2.add_argument("--crt-nolo", action="store_true", help="do not add 127.0.0.1 / localhost into cert") ap2.add_argument("--crt-nohn", action="store_true", help="do not add mDNS names / hostname into cert") ap2.add_argument("--crt-dir", metavar="PATH", default=cert_dir, help="where to save the CA cert") ap2.add_argument("--crt-cdays", metavar="D", type=float, default=3650.0, help="ca-certificate expiration time in days") ap2.add_argument("--crt-sdays", metavar="D", type=float, default=365.0, help="server-cert expiration time in days") ap2.add_argument("--crt-cn", metavar="TXT", type=u, default="partyco", help="CA/server-cert common-name") ap2.add_argument("--crt-cnc", metavar="TXT", type=u, default="--crt-cn", help="override CA name") ap2.add_argument("--crt-cns", metavar="TXT", type=u, default="--crt-cn cpp", help="override server-cert name") ap2.add_argument("--crt-back", metavar="HRS", type=float, default=72.0, help="backdate in hours") ap2.add_argument("--crt-alg", metavar="S-N", type=u, default="ecdsa-256", help="algorithm and keysize; one of these: \033[32mecdsa-256 rsa-4096 rsa-2048\033[0m") def add_auth(ap): idp_db = os.path.join(E.cfg, "idp.db") ses_db = os.path.join(E.cfg, "sessions.db") ap2 = ap.add_argument_group("IdP / identity provider / user authentication options") ap2.add_argument("--idp-h-usr", metavar="HN", type=u, action="append", help="\033[34mREPEATABLE:\033[0m bypass the copyparty authentication checks if the request-header \033[33mHN\033[0m contains a username to associate the request with (for use with authentik/oauth/...)\n\033[1;31mWARNING:\033[0m if you enable this, make sure clients are unable to specify this header themselves; must be washed away and replaced by a reverse-proxy") ap2.add_argument("--idp-hm-usr", metavar="T", type=u, action="append", help="\033[34mREPEATABLE:\033[0m bypass the copyparty authentication checks if the request-header \033[33mT\033[0m is provided, and its value exists in a mapping defined by this option; see --help-idp") ap2.add_argument("--idp-h-grp", metavar="HN", type=u, default="", help="assume the request-header \033[33mHN\033[0m contains the groupname of the requesting user; can be referenced in config files for group-based access control") ap2.add_argument("--idp-h-key", metavar="HN", type=u, default="", help="optional but recommended safeguard; your reverse-proxy will insert a secret header named \033[33mHN\033[0m into all requests, and the other IdP headers will be ignored if this header is not present") ap2.add_argument("--idp-gsep", metavar="RE", type=u, default="|:;+,", help="if there are multiple groups in \033[33m--idp-h-grp\033[0m, they are separated by one of the characters in \033[33mRE\033[0m") ap2.add_argument("--idp-chsub", metavar="TXT", type=u, default="", help="characters to replace in usernames/groupnames; a list of pairs of characters separated by | so for example | _| will replace spaces with _ to make configuration easier, or |%%_|^_|@_| will replace %%/^/@ with _") ap2.add_argument("--idp-db", metavar="PATH", type=u, default=idp_db, help="where to store the known IdP users/groups (if you run multiple copyparty instances, make sure they use different DBs)") ap2.add_argument("--idp-store", metavar="N", type=int, default=1, help="how to use \033[33m--idp-db\033[0m; [\033[32m0\033[0m] = entirely disable, [\033[32m1\033[0m] = write-only (effectively disabled), [\033[32m2\033[0m] = remember users, [\033[32m3\033[0m] = remember users and groups.\nNOTE: Will remember and restore the IdP-volumes of all users for all eternity if set to 2 or 3, even when user is deleted from your IdP") ap2.add_argument("--idp-adm", metavar="U,U", type=u, default="", help="comma-separated list of users allowed to use /?idp (the cache management UI)") ap2.add_argument("--idp-cookie", metavar="S", type=int, default=0, help="generate a session-token for IdP users which is written to cookie \033[33mcppws\033[0m (or \033[33mcppwd\033[0m if plaintext), to reduce the load on the IdP server, lifetime \033[33mS\033[0m seconds.\n └─note: The expiration time is a client hint only; the actual lifetime of the session-token is infinite (until next restart with \033[33m--ses-db\033[0m wiped)") ap2.add_argument("--idp-login", metavar="L", type=u, default="", help="replace all login-buttons with a link to URL \033[33mL\033[0m (unless \033[32mpw\033[0m is in \033[33m--auth-ord\033[0m then both will be shown); [\033[32m{dst}\033[0m] expands to url of current page") ap2.add_argument("--idp-login-t", metavar="T", type=u, default="Login with SSO", help="the label/text for the idp-login button") ap2.add_argument("--idp-logout", metavar="L", type=u, default="", help="replace all logout-buttons with a link to URL \033[33mL\033[0m") ap2.add_argument("--auth-ord", metavar="TXT", type=u, default="idp,ipu", help="controls auth precedence; examples: [\033[32mpw,idp,ipu\033[0m], [\033[32mipu,pw,idp\033[0m], see --help-auth-ord") ap2.add_argument("--pw-hdr", metavar="NAME", type=u, default="pw", help="lowercase name of password-header (NAME: foo); \033[1;31mWARNING:\033[0m Changing this will break support for many clients") ap2.add_argument("--pw-urlp", metavar="NAME", type=u, default="pw", help="lowercase name of password url-param (?NAME=foo); \033[1;31mWARNING:\033[0m Changing this will break support for many clients") ap2.add_argument("--no-bauth", action="store_true", help="disable basic-authentication support; do not accept passwords from the 'Authenticate' header at all. NOTE: This breaks support for the android app") ap2.add_argument("--bauth-last", action="store_true", help="keeps basic-authentication enabled, but only as a last-resort; if a cookie is also provided then the cookie wins") ap2.add_argument("--ses-db", metavar="PATH", type=u, default=ses_db, help="where to store the sessions database (if you run multiple copyparty instances, make sure they use different DBs)") ap2.add_argument("--ses-len", metavar="CHARS", type=int, default=20, help="session key length; default is 120 bits ((20//4)*4*6)") ap2.add_argument("--no-ses", action="store_true", help="disable sessions; use plaintext passwords in cookies") ap2.add_argument("--grp-all", metavar="NAME", type=u, default="acct", help="the name of the auto-generated group which contains every username which is known") ap2.add_argument("--ipu", metavar="CIDR=USR", type=u, action="append", help="\033[34mREPEATABLE:\033[0m users with IP matching \033[33mCIDR\033[0m are auto-authenticated as username \033[33mUSR\033[0m; example: [\033[32m172.16.24.0/24=dave]") ap2.add_argument("--ipr", metavar="CIDR=USR", type=u, action="append", help="\033[34mREPEATABLE:\033[0m username \033[33mUSR\033[0m can only connect from an IP matching one or more \033[33mCIDR\033[0m (comma-sep.); example: [\033[32m192.168.123.0/24,172.16.0.0/16=dave]") ap2.add_argument("--have-idp-hdrs", type=u, default="", help=argparse.SUPPRESS) ap2.add_argument("--have-ipu-or-ipr", type=u, default="", help=argparse.SUPPRESS) ap2.add_argument("--ao-idp-before-pw", type=u, default="", help=argparse.SUPPRESS) ap2.add_argument("--ao-h-before-hm", type=u, default="", help=argparse.SUPPRESS) ap2.add_argument("--ao-ipu-wins", type=u, default="", help=argparse.SUPPRESS) ap2.add_argument("--ao-have-pw", type=u, default="", help=argparse.SUPPRESS) def add_chpw(ap): db_path = os.path.join(E.cfg, "chpw.json") ap2 = ap.add_argument_group("user-changeable passwords options") ap2.add_argument("--chpw", action="store_true", help="allow users to change their own passwords") ap2.add_argument("--chpw-no", metavar="U,U,U", type=u, action="append", help="\033[34mREPEATABLE:\033[0m do not allow password-changes for this comma-separated list of usernames") ap2.add_argument("--chpw-db", metavar="PATH", type=u, default=db_path, help="where to store the passwords database (if you run multiple copyparty instances, make sure they use different DBs)") ap2.add_argument("--chpw-len", metavar="N", type=int, default=8, help="minimum password length") ap2.add_argument("--chpw-v", metavar="LVL", type=int, default=2, help="verbosity of summary on config load [\033[32m0\033[0m] = nothing at all, [\033[32m1\033[0m] = number of users, [\033[32m2\033[0m] = list users with default-pw, [\033[32m3\033[0m] = list all users") def add_zeroconf(ap): ap2 = ap.add_argument_group("Zeroconf options") ap2.add_argument("-z", action="store_true", help="enable all zeroconf backends (mdns, ssdp)") ap2.add_argument("--z-on", metavar="NETS", type=u, default="", help="enable zeroconf ONLY on the comma-separated list of subnets and/or interface names/indexes\n └─example: \033[32meth0, wlo1, virhost0, 192.168.123.0/24, fd00:fda::/96\033[0m") ap2.add_argument("--z-off", metavar="NETS", type=u, default="", help="disable zeroconf on the comma-separated list of subnets and/or interface names/indexes") ap2.add_argument("--z-chk", metavar="SEC", type=int, default=10, help="check for network changes every \033[33mSEC\033[0m seconds (0=disable)") ap2.add_argument("-zv", action="store_true", help="verbose all zeroconf backends") ap2.add_argument("--mc-hop", metavar="SEC", type=int, default=0, help="rejoin multicast groups every \033[33mSEC\033[0m seconds (workaround for some switches/routers which cause mDNS to suddenly stop working after some time); try [\033[32m300\033[0m] or [\033[32m180\033[0m]\n └─note: can be due to firewalls; make sure UDP port 5353 is open in both directions (on clients too)") def add_zc_mdns(ap): ap2 = ap.add_argument_group("Zeroconf-mDNS options; also see --help-zm") ap2.add_argument("--zm", action="store_true", help="announce the enabled protocols over mDNS (multicast DNS-SD) -- compatible with KDE, gnome, macOS, ...") ap2.add_argument("--zm-on", metavar="NETS", type=u, default="", help="enable mDNS ONLY on the comma-separated list of subnets and/or interface names/indexes") ap2.add_argument("--zm-off", metavar="NETS", type=u, default="", help="disable mDNS on the comma-separated list of subnets and/or interface names/indexes") ap2.add_argument("--zm4", action="store_true", help="IPv4 only -- try this if some clients can't connect") ap2.add_argument("--zm6", action="store_true", help="IPv6 only") ap2.add_argument("--zmv", action="store_true", help="verbose mdns") ap2.add_argument("--zmvv", action="store_true", help="verboser mdns") ap2.add_argument("--zm-http", metavar="PORT", type=int, default=-1, help="port to announce for http/webdav; [\033[32m-1\033[0m] = auto, [\033[32m0\033[0m] = disabled, [\033[32m4649\033[0m] = port 4649") ap2.add_argument("--zm-https", metavar="PORT", type=int, default=-1, help="port to announce for https/webdavs; [\033[32m-1\033[0m] = auto, [\033[32m0\033[0m] = disabled, [\033[32m4649\033[0m] = port 4649") ap2.add_argument("--zm-no-pe", action="store_true", help="mute parser errors (invalid incoming MDNS packets)") ap2.add_argument("--zm-nwa-1", action="store_true", help="disable workaround for avahi-bug #379 (corruption in Avahi's mDNS reflection feature)") ap2.add_argument("--zms", metavar="dhf", type=u, default="", help="list of services to announce -- d=webdav h=http f=ftp s=smb -- lowercase=plaintext uppercase=TLS -- default: all enabled services except http/https (\033[32mDdfs\033[0m if \033[33m--ftp\033[0m and \033[33m--smb\033[0m is set, \033[32mDd\033[0m otherwise)") ap2.add_argument("--zm-ld", metavar="PATH", type=u, default="", help="link a specific folder for webdav shares") ap2.add_argument("--zm-lh", metavar="PATH", type=u, default="", help="link a specific folder for http shares") ap2.add_argument("--zm-lf", metavar="PATH", type=u, default="", help="link a specific folder for ftp shares") ap2.add_argument("--zm-ls", metavar="PATH", type=u, default="", help="link a specific folder for smb shares") ap2.add_argument("--zm-fqdn", metavar="FQDN", type=u, default="--name.local", help="the domain to announce; NOTE: using anything other than .local is nonstandard and could cause problems") ap2.add_argument("--zm-mnic", action="store_true", help="merge NICs which share subnets; assume that same subnet means same network") ap2.add_argument("--zm-msub", action="store_true", help="merge subnets on each NIC -- always enabled for ipv6 -- reduces network load, but gnome-gvfs clients may stop working, and clients cannot be in subnets that the server is not") ap2.add_argument("--zm-noneg", action="store_true", help="disable NSEC replies -- try this if some clients don't see copyparty") ap2.add_argument("--zm-spam", metavar="SEC", type=float, default=0.0, help="send unsolicited announce every \033[33mSEC\033[0m; useful if clients have IPs in a subnet which doesn't overlap with the server, or to avoid some firewall issues") def add_zc_ssdp(ap): ap2 = ap.add_argument_group("Zeroconf-SSDP options") ap2.add_argument("--zs", action="store_true", help="announce the enabled protocols over SSDP -- compatible with Windows") ap2.add_argument("--zs-on", metavar="NETS", type=u, default="", help="enable SSDP ONLY on the comma-separated list of subnets and/or interface names/indexes") ap2.add_argument("--zs-off", metavar="NETS", type=u, default="", help="disable SSDP on the comma-separated list of subnets and/or interface names/indexes") ap2.add_argument("--zsv", action="store_true", help="verbose SSDP") ap2.add_argument("--zsl", metavar="PATH", type=u, default="/?hc", help="location to include in the url (or a complete external URL), for example [\033[32mpriv/?pw=hunter2\033[0m] (goes directly to /priv/ with password hunter2) or [\033[32m?hc=priv&pw=hunter2\033[0m] (shows mounting options for /priv/ with password)") ap2.add_argument("--zsid", metavar="UUID", type=u, default=zsid, help="USN (device identifier) to announce") def add_sftp(ap): ap2 = ap.add_argument_group("SFTP options") ap2.add_argument("--sftp", metavar="PORT", type=int, default=0, help="enable SFTP server on \033[33mPORT\033[0m, for example \033[32m3922") ap2.add_argument("--sftpv", action="store_true", help="verbose") ap2.add_argument("--sftpvv", action="store_true", help="verboser") ap2.add_argument("--sftp-i", metavar="IP", type=u, default="-i", help="IPs to listen on (comma-separated list). Set this to override \033[33m-i\033[0m for this protocol") ap2.add_argument("--sftp4", action="store_true", help="only listen on IPv4") ap2.add_argument("--sftp-key", metavar="U K", type=u, action="append", help="\033[34mREPEATABLE:\033[0m add ssh-key \033[33mK\033[0m for user \033[33mU\033[0m (username, space, key-type, space, base64); if user has multiple keys, then repeat this option for each key\n └─commandline example: --sftp-key 'david ssh-ed25519 AAAAC3NzaC...'\n └─config-file example: sftp-key: david ssh-ed25519 AAAAC3NzaC...") ap2.add_argument("--sftp-key2u", action="append", help=argparse.SUPPRESS) ap2.add_argument("--sftp-pw", action="store_true", help="allow password-authentication with sftp (not just ssh-keys)") ap2.add_argument("--sftp-anon", metavar="TXT", type=u, default="", help="allow anonymous/unauthenticated connections with \033[33mTXT\033[0m as username") ap2.add_argument("--sftp-hostk", metavar="FP", type=u, default=E.cfg, help="path to folder with hostkeys, for example 'ssh_host_rsa_key'; missing keys will be generated") ap2.add_argument("--sftp-banner", metavar="T", type=u, default="", help="bannertext to send when someone connects; can be @filepath") ap2.add_argument("--sftp-ipa", metavar="CIDR", type=u, default="", help="only accept connections from IP-addresses inside \033[33mCIDR\033[0m (comma-separated); specify [\033[32many\033[0m] to disable inheriting \033[33m--ipa\033[0m / \033[33m--ipar\033[0m. Examples: [\033[32mlan\033[0m] or [\033[32m10.89.0.0/16, 192.168.33.0/24\033[0m]") def add_ftp(ap): ap2 = ap.add_argument_group("FTP options (TCP only)") ap2.add_argument("--ftp", metavar="PORT", type=int, default=0, help="enable FTP server on \033[33mPORT\033[0m, for example \033[32m3921") ap2.add_argument("--ftps", metavar="PORT", type=int, default=0, help="enable FTPS server on \033[33mPORT\033[0m, for example \033[32m3990") ap2.add_argument("--ftpv", action="store_true", help="verbose") ap2.add_argument("--ftp-i", metavar="IP", type=u, default="-i", help="IPs to listen on (comma-separated list). Set this to override \033[33m-i\033[0m for this protocol") ap2.add_argument("--ftp4", action="store_true", help="only listen on IPv4") ap2.add_argument("--ftp-ipa", metavar="CIDR", type=u, default="", help="only accept connections from IP-addresses inside \033[33mCIDR\033[0m (comma-separated); specify [\033[32many\033[0m] to disable inheriting \033[33m--ipa\033[0m / \033[33m--ipar\033[0m. Examples: [\033[32mlan\033[0m] or [\033[32m10.89.0.0/16, 192.168.33.0/24\033[0m]") ap2.add_argument("--ftp-no-ow", action="store_true", help="if target file exists, reject upload instead of overwrite") ap2.add_argument("--ftp-wt", metavar="SEC", type=int, default=7, help="grace period for resuming interrupted uploads (any client can write to any file last-modified more recently than \033[33mSEC\033[0m seconds ago)") ap2.add_argument("--ftp-nat", metavar="ADDR", type=u, default="", help="the NAT address to use for passive connections") ap2.add_argument("--ftp-pr", metavar="P-P", type=u, default="", help="the range of TCP ports to use for passive connections, for example \033[32m12000-13000") def add_webdav(ap): ap2 = ap.add_argument_group("WebDAV options") ap2.add_argument("--daw", action="store_true", help="enable full write support, even if client may not be webdav. Some webdav clients need this option for editing existing files; not necessary for clients that send the 'x-oc-mtime' header. Regardless, the delete-permission must always be given. \033[1;31mWARNING:\033[0m This has side-effects -- PUT-operations will now \033[1;31mOVERWRITE\033[0m existing files, rather than inventing new filenames to avoid loss of data. You might want to instead set this as a volflag where needed. By not setting this flag, uploaded files can get written to a filename which the client does not expect (which might be okay, depending on client)") ap2.add_argument("--dav-inf", action="store_true", help="allow depth:infinite requests (recursive file listing); extremely server-heavy but required for spec compliance -- luckily few clients rely on this") ap2.add_argument("--dav-mac", action="store_true", help="disable apple-garbage filter -- allow macos to create junk files (._* and .DS_Store, .Spotlight-*, .fseventsd, .Trashes, .AppleDouble, __MACOS)") ap2.add_argument("--dav-rt", action="store_true", help="show symlink-destination's lastmodified instead of the link itself; always enabled for recursive listings (volflag=davrt)") ap2.add_argument("--dav-auth", action="store_true", help="force auth for all folders (required by davfs2 when only some folders are world-readable) (volflag=davauth)") ap2.add_argument("--dav-ua1", metavar="PTN", type=u, default=r" kioworker/", help="regex of user-agents which ARE webdav-clients, and expect 401 from GET requests; disable with [\033[32mno\033[0m] or blank") ap2.add_argument("--dav-port", metavar="P", type=int, default=0, help="additional port to listen on for misbehaving webdav clients which pretend they are graphical browsers; an alternative/supplement to dav-ua1") ap2.add_argument("--ua-nodav", metavar="PTN", type=u, default=r"^(Mozilla/|NetworkingExtension/|com\.apple\.WebKit)", help="regex of user-agents which are NOT webdav-clients") ap2.add_argument("--p-nodav", metavar="P,P", type=u, default="", help="server-ports (comma-sep.) which are NOT webdav-clients; an alternative/supplement to ua-nodav") def add_tftp(ap): ap2 = ap.add_argument_group("TFTP options (UDP only)") ap2.add_argument("--tftp", metavar="PORT", type=int, default=0, help="enable TFTP server on \033[33mPORT\033[0m, for example \033[32m69 \033[0mor \033[32m3969") ap2.add_argument("--tftp-i", metavar="IP", type=u, default="-i", help="IPs to listen on (comma-separated list). Set this to override \033[33m-i\033[0m for this protocol") ap2.add_argument("--tftp4", action="store_true", help="only listen on IPv4") ap2.add_argument("--tftpv", action="store_true", help="verbose") ap2.add_argument("--tftpvv", action="store_true", help="verboser") ap2.add_argument("--tftp-no-fast", action="store_true", help="debug: disable optimizations") ap2.add_argument("--tftp-lsf", metavar="PTN", type=u, default="\\.?(dir|ls)(\\.txt)?", help="return a directory listing if a file with this name is requested and it does not exist; defaults matches .ls, dir, .dir.txt, ls.txt, ...") ap2.add_argument("--tftp-nols", action="store_true", help="if someone tries to download a directory, return an error instead of showing its directory listing") ap2.add_argument("--tftp-ipa", metavar="CIDR", type=u, default="", help="only accept connections from IP-addresses inside \033[33mCIDR\033[0m (comma-separated); specify [\033[32many\033[0m] to disable inheriting \033[33m--ipa\033[0m / \033[33m--ipar\033[0m. Examples: [\033[32mlan\033[0m] or [\033[32m10.89.0.0/16, 192.168.33.0/24\033[0m]") ap2.add_argument("--tftp-pr", metavar="P-P", type=u, default="", help="the range of UDP ports to use for data transfer, for example \033[32m12000-13000") def add_smb(ap): ap2 = ap.add_argument_group("SMB/CIFS options") ap2.add_argument("--smb", action="store_true", help="enable smb (read-only) -- this requires running copyparty as root on linux and macos unless \033[33m--smb-port\033[0m is set above 1024 and your OS does port-forwarding from 445 to that.\n\033[1;31mWARNING:\033[0m this protocol is DANGEROUS and buggy! Never expose to the internet!") ap2.add_argument("--smb-i", metavar="IP", type=u, default="-i", help="IPs to listen on (comma-separated list). Set this to override \033[33m-i\033[0m for this protocol") ap2.add_argument("--smbw", action="store_true", help="enable write support (please dont)") ap2.add_argument("--smb1", action="store_true", help="disable SMBv2, only enable SMBv1 (CIFS)") ap2.add_argument("--smb-port", metavar="PORT", type=int, default=445, help="port to listen on -- if you change this value, you must NAT from TCP:445 to this port using iptables or similar") ap2.add_argument("--smb-nwa-1", action="store_true", help="truncate directory listings to 64kB (~400 files); avoids impacket-0.11 bug, fixes impacket-0.12 performance") ap2.add_argument("--smb-nwa-2", action="store_true", help="disable impacket workaround for filecopy globs") ap2.add_argument("--smba", action="store_true", help="small performance boost: disable per-account permissions, enables account coalescing instead (if one user has write/delete-access, then everyone does)") ap2.add_argument("--smbv", action="store_true", help="verbose") ap2.add_argument("--smbvv", action="store_true", help="verboser") ap2.add_argument("--smbvvv", action="store_true", help="verbosest") def add_opds(ap): ap2 = ap.add_argument_group("OPDS options") ap2.add_argument("--opds", action="store_true", help="enable opds -- allows e-book readers to browse and download files (volflag=opds)") ap2.add_argument("--opds-exts", metavar="T,T", type=u, default="epub,cbz,pdf", help="file formats to list in OPDS feeds; leave empty to show everything (volflag=opds_exts)") def add_handlers(ap): ap2 = ap.add_argument_group("handlers (see --help-handlers)") ap2.add_argument("--on404", metavar="PY", type=u, action="append", help="\033[34mREPEATABLE:\033[0m handle 404s by executing \033[33mPY\033[0m file") ap2.add_argument("--on403", metavar="PY", type=u, action="append", help="\033[34mREPEATABLE:\033[0m handle 403s by executing \033[33mPY\033[0m file") ap2.add_argument("--hot-handlers", action="store_true", help="recompile handlers on each request -- expensive but convenient when hacking on stuff") def add_hooks(ap): ap2 = ap.add_argument_group("event hooks (see --help-hooks)") ap2.add_argument("--xbu", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m before a file upload starts") ap2.add_argument("--xau", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m after a file upload finishes") ap2.add_argument("--xiu", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m after all uploads finish and volume is idle") ap2.add_argument("--xbc", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m before a file copy") ap2.add_argument("--xac", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m after a file copy") ap2.add_argument("--xbr", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m before a file move/rename") ap2.add_argument("--xar", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m after a file move/rename") ap2.add_argument("--xbd", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m before a file delete") ap2.add_argument("--xad", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m after a file delete") ap2.add_argument("--xm", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m on message") ap2.add_argument("--xban", metavar="CMD", type=u, action="append", help="\033[34mREPEATABLE:\033[0m execute \033[33mCMD\033[0m if someone gets banned (pw/404/403/url)") ap2.add_argument("--hook-v", action="store_true", help="verbose hooks") def add_stats(ap): ap2 = ap.add_argument_group("grafana/prometheus metrics endpoint") ap2.add_argument("--stats", action="store_true", help="enable openmetrics at /.cpr/metrics for admin accounts") ap2.add_argument("--stats-u", metavar="U,U", type=u, default="", help="comma-separated list of users allowed to access /.cpr/metrics even if they aren't admin") ap2.add_argument("--nos-hdd", action="store_true", help="disable disk-space metrics (used/free space)") ap2.add_argument("--nos-vol", action="store_true", help="disable volume size metrics (num files, total bytes, vmaxb/vmaxn)") ap2.add_argument("--nos-vst", action="store_true", help="disable volume state metrics (indexing, analyzing, activity)") ap2.add_argument("--nos-dup", action="store_true", help="disable dupe-files metrics (good idea; very slow)") ap2.add_argument("--nos-unf", action="store_true", help="disable unfinished-uploads metrics") def add_yolo(ap): ap2 = ap.add_argument_group("yolo options") ap2.add_argument("--allow-csrf", action="store_true", help="disable csrf protections; let other domains/sites impersonate you through cross-site requests") ap2.add_argument("--cookie-lax", action="store_true", help="allow cookies from other domains (if you follow a link from another website into your server, you will arrive logged-in); this reduces protection against CSRF") ap2.add_argument("--no-fnugg", action="store_true", help="disable the smoketest for caching-related issues in the web-UI") ap2.add_argument("--getmod", action="store_true", help="permit ?move=[...] and ?delete as GET") ap2.add_argument("--wo-up-readme", action="store_true", help="allow users with write-only access to upload logues and readmes without adding the _wo_ filename prefix (volflag=wo_up_readme)") ap2.add_argument("--unsafe-state", action="store_true", help="when one of the emergency fallback locations are used for runtime state ($TMPDIR, /tmp), certain features will be force-disabled for security reasons by default. This option overrides that safeguard and allows unsafe storage of secrets") def add_optouts(ap): ap2 = ap.add_argument_group("opt-outs") ap2.add_argument("-nw", action="store_true", help="never write anything to disk (debug/benchmark)") ap2.add_argument("--keep-qem", action="store_true", help="do not disable quick-edit-mode on windows (it is disabled to avoid accidental text selection in the terminal window, as this would pause execution)") ap2.add_argument("--no-dav", action="store_true", help="disable webdav support") ap2.add_argument("--no-del", action="store_true", help="disable delete operations") ap2.add_argument("--no-mv", action="store_true", help="disable move/rename operations") ap2.add_argument("--no-cp", action="store_true", help="disable copy operations") ap2.add_argument("--no-fs-abrt", action="store_true", help="disable ability to abort ongoing copy/move") ap2.add_argument("-nih", action="store_true", help="no info hostname -- removes it from the UI corner, but the value of \033[33m--bname\033[0m still shows in the browsertab title") ap2.add_argument("-nid", action="store_true", help="no info disk-usage -- don't show in UI. This is the same as \033[33m--du-who no\033[0m") ap2.add_argument("-nb", action="store_true", help="no powered-by-copyparty branding in UI") ap2.add_argument("--smsg", metavar="T,T", type=u, default="POST", help="HTTP-methods to allow ?smsg for; will execute xm hooks like urlform / message-to-serverlog; dangerous example: [\033[32mGET,POST\033[0m]. \033[1;31mWARNING:\033[0m The default (POST) is safe, but GET is dangerous; security/CSRF hazard") ap2.add_argument("--zipmaxn", metavar="N", type=u, default="0", help="reject download-as-zip if more than \033[33mN\033[0m files in total; optionally takes a unit suffix: [\033[32m256\033[0m], [\033[32m9K\033[0m], [\033[32m4G\033[0m] (volflag=zipmaxn)") ap2.add_argument("--zipmaxs", metavar="SZ", type=u, default="0", help="reject download-as-zip if total download size exceeds \033[33mSZ\033[0m bytes; optionally takes a unit suffix: [\033[32m256M\033[0m], [\033[32m4G\033[0m], [\033[32m2T\033[0m] (volflag=zipmaxs)") ap2.add_argument("--zipmaxt", metavar="TXT", type=u, default="", help="custom errormessage when download size exceeds max (volflag=zipmaxt)") ap2.add_argument("--zipmaxu", action="store_true", help="authenticated users bypass the zip size limit (volflag=zipmaxu)") ap2.add_argument("--zip-who", metavar="LVL", type=int, default=3, help="who can download as zip/tar? [\033[32m0\033[0m]=nobody, [\033[32m1\033[0m]=admins, [\033[32m2\033[0m]=authenticated-with-read-access, [\033[32m3\033[0m]=everyone-with-read-access (volflag=zip_who)\n\033[1;31mWARNING:\033[0m if a nested volume has a more restrictive value than a parent volume, then this will be \033[33mignored\033[0m if the download is initiated from the parent, more lenient volume") ap2.add_argument("--ua-nozip", metavar="PTN", type=u, default=BAD_BOTS, help="regex of user-agents to reject from download-as-zip/tar; disable with [\033[32mno\033[0m] or blank") ap2.add_argument("--no-zip", action="store_true", help="disable download as zip/tar; same as \033[33m--zip-who=0\033[0m") ap2.add_argument("--no-tarcmp", action="store_true", help="disable download as compressed tar (?tar=gz, ?tar=bz2, ?tar=xz, ?tar=gz:9, ...)") ap2.add_argument("--no-lifetime", action="store_true", help="do not allow clients (or server config) to schedule an upload to be deleted after a given time") ap2.add_argument("--no-pipe", action="store_true", help="disable race-the-beam (lockstep download of files which are currently being uploaded) (volflag=nopipe)") ap2.add_argument("--no-tail", action="store_true", help="disable streaming a growing files with ?tail (volflag=notail)") ap2.add_argument("--no-db-ip", action="store_true", help="do not write uploader-IP into the database; will also disable unpost, you may want \033[32m--forget-ip\033[0m instead (volflag=no_db_ip)") ap2.add_argument("--no-zls", action="store_true", help="disable browsing the contents of zip/cbz files, does not affect thumbnails") def add_safety(ap): ap2 = ap.add_argument_group("safety options") ap2.add_argument("-s", action="count", default=0, help="increase safety: Disable thumbnails / potentially dangerous software (ffmpeg/pillow/vips), hide partial uploads, avoid crawlers.\n └─Alias of\033[32m --dotpart --no-thumb --no-mtag-ff --no-robots --force-js") ap2.add_argument("-ss", action="store_true", help="further increase safety: Prevent js-injection, accidental move/delete, broken symlinks, webdav requires login, 404 on 403, ban on excessive 404s.\n └─Alias of\033[32m -s --unpost=0 --no-del --no-mv --reflink --dav-auth --vague-403 -nih") ap2.add_argument("-sss", action="store_true", help="further increase safety: Enable logging to disk, scan for dangerous symlinks.\n └─Alias of\033[32m -ss --no-dav --no-logues --no-readme -lo=cpp-%%Y-%%m%%d-%%H%%M%%S.txt.xz --ls=**,*,ln,p,r") ap2.add_argument("--ls", metavar="U[,V[,F]]", type=u, default="", help="do a sanity/safety check of all volumes on startup; arguments \033[33mUSER\033[0m,\033[33mVOL\033[0m,\033[33mFLAGS\033[0m (see \033[33m--help-ls\033[0m); example [\033[32m**,*,ln,p,r\033[0m]") ap2.add_argument("--xvol", action="store_true", help="never follow symlinks leaving the volume root, unless the link is into another volume where the user has similar access (volflag=xvol)") ap2.add_argument("--xdev", action="store_true", help="stay within the filesystem of the volume root; do not descend into other devices (symlink or bind-mount to another HDD, ...) (volflag=xdev)") ap2.add_argument("--vol-nospawn", action="store_true", help="if a volume's folder does not exist on the HDD, then do not create it (continue with warning) (volflag=nospawn)") ap2.add_argument("--vol-or-crash", action="store_true", help="if a volume's folder does not exist on the HDD, then burst into flames (volflag=assert_root)") ap2.add_argument("--no-dot-mv", action="store_true", help="disallow moving dotfiles; makes it impossible to move folders containing dotfiles") ap2.add_argument("--no-dot-ren", action="store_true", help="disallow renaming dotfiles; makes it impossible to turn something into a dotfile") ap2.add_argument("--no-logues", action="store_true", help="disable rendering .prologue/.epilogue.html into directory listings") ap2.add_argument("--no-readme", action="store_true", help="disable rendering readme/preadme.md into directory listings") ap2.add_argument("--vague-403", action="store_true", help="send 404 instead of 403 (security through ambiguity, very enterprise). \033[1;31mWARNING:\033[0m Not compatible with WebDAV") ap2.add_argument("--force-js", action="store_true", help="don't send folder listings as HTML, force clients to use the embedded json instead -- slight protection against misbehaving search engines which ignore \033[33m--no-robots\033[0m") ap2.add_argument("--no-robots", action="store_true", help="adds http and html headers asking search engines to not index anything (volflag=norobots)") ap2.add_argument("--logout", metavar="H", type=float, default=8086.0, help="logout clients after \033[33mH\033[0m hours of inactivity; [\033[32m0.0028\033[0m]=10sec, [\033[32m0.1\033[0m]=6min, [\033[32m24\033[0m]=day, [\033[32m168\033[0m]=week, [\033[32m720\033[0m]=month, [\033[32m8760\033[0m]=year)") ap2.add_argument("--dont-ban", metavar="TXT", type=u, default="no", help="anyone at this accesslevel or above will not get banned: [\033[32mav\033[0m]=admin-in-volume, [\033[32maa\033[0m]=has-admin-anywhere, [\033[32mrw\033[0m]=read-write, [\033[32mauth\033[0m]=authenticated, [\033[32many\033[0m]=disable-all-bans, [\033[32mno\033[0m]=anyone-can-get-banned") ap2.add_argument("--banmsg", metavar="TXT", type=u, default="thank you for playing \u00a0 (see fileserver log and readme)", help="the response to send to banned users; can be @ban.html to send the contents of ban.html") ap2.add_argument("--ban-pw", metavar="N,W,B", type=u, default="9,60,1440", help="more than \033[33mN\033[0m wrong passwords in \033[33mW\033[0m minutes = ban for \033[33mB\033[0m minutes; disable with [\033[32mno\033[0m]") ap2.add_argument("--ban-pwc", metavar="N,W,B", type=u, default="5,60,1440", help="more than \033[33mN\033[0m password-changes in \033[33mW\033[0m minutes = ban for \033[33mB\033[0m minutes; disable with [\033[32mno\033[0m]") ap2.add_argument("--ban-404", metavar="N,W,B", type=u, default="50,60,1440", help="hitting more than \033[33mN\033[0m 404's in \033[33mW\033[0m minutes = ban for \033[33mB\033[0m minutes; only affects users who cannot see directory listings because their access is either g/G/h") ap2.add_argument("--ban-403", metavar="N,W,B", type=u, default="9,2,1440", help="hitting more than \033[33mN\033[0m 403's in \033[33mW\033[0m minutes = ban for \033[33mB\033[0m minutes; [\033[32m1440\033[0m]=day, [\033[32m10080\033[0m]=week, [\033[32m43200\033[0m]=month") ap2.add_argument("--ban-422", metavar="N,W,B", type=u, default="9,2,1440", help="hitting more than \033[33mN\033[0m 422's in \033[33mW\033[0m minutes = ban for \033[33mB\033[0m minutes (invalid requests, attempted exploits ++)") ap2.add_argument("--ban-url", metavar="N,W,B", type=u, default="9,2,1440", help="hitting more than \033[33mN\033[0m sus URL's in \033[33mW\033[0m minutes = ban for \033[33mB\033[0m minutes; applies only to permissions g/G/h (decent replacement for \033[33m--ban-404\033[0m if that can't be used)") ap2.add_argument("--sus-urls", metavar="R", type=u, default=r"\.php$|(^|/)wp-(admin|content|includes)/", help="URLs which are considered sus / eligible for banning; disable with blank or [\033[32mno\033[0m]") ap2.add_argument("--nonsus-urls", metavar="R", type=u, default=r"^(favicon\..{3}|robots\.txt)$|^apple-touch-icon|^\.well-known", help="harmless URLs ignored from 403/404-bans; disable with blank or [\033[32mno\033[0m]") ap2.add_argument("--early-ban", action="store_true", help="if a client is banned, reject its connection as soon as possible; not a good idea to enable when proxied behind cloudflare since it could ban your reverse-proxy") ap2.add_argument("--cookie-nmax", metavar="N", type=int, default=50, help="reject HTTP-request from client if they send more than N cookies") ap2.add_argument("--cookie-cmax", metavar="N", type=int, default=8192, help="reject HTTP-request from client if more than N characters in Cookie header") ap2.add_argument("--aclose", metavar="MIN", type=int, default=10, help="if a client maxes out the server connection limit, downgrade it from connection:keep-alive to connection:close for \033[33mMIN\033[0m minutes (and also kill its active connections) -- disable with 0") ap2.add_argument("--loris", metavar="B", type=int, default=60, help="if a client maxes out the server connection limit without sending headers, ban it for \033[33mB\033[0m minutes; disable with [\033[32m0\033[0m]") ap2.add_argument("--acao", metavar="V[,V]", type=u, default="*", help="Access-Control-Allow-Origin; list of origins (domains/IPs without port) to accept requests from; [\033[32mhttps://1.2.3.4\033[0m]. Default [\033[32m*\033[0m] allows requests from all sites but removes cookies and http-auth; only ?pw=hunter2 survives") ap2.add_argument("--acam", metavar="V[,V]", type=u, default="GET,HEAD", help="Access-Control-Allow-Methods; list of methods to accept from offsite ('*' behaves like \033[33m--acao\033[0m's description)") def add_salt(ap, fk_salt, dk_salt, ah_salt): ap2 = ap.add_argument_group("salting options") ap2.add_argument("--ah-alg", metavar="ALG", type=u, default="none", help="account-pw hashing algorithm; one of these, best to worst: \033[32margon2 scrypt sha2 none\033[0m (each optionally followed by alg-specific comma-sep. config)") ap2.add_argument("--ah-salt", metavar="SALT", type=u, default=ah_salt, help="account-pw salt; ignored if \033[33m--ah-alg\033[0m is none (default)") ap2.add_argument("--ah-gen", metavar="PW", type=u, default="", help="generate hashed password for \033[33mPW\033[0m, or read passwords from STDIN if \033[33mPW\033[0m is [\033[32m-\033[0m]") ap2.add_argument("--ah-cli", action="store_true", help="launch an interactive shell which hashes passwords without ever storing or displaying the original passwords") ap2.add_argument("--fk-salt", metavar="SALT", type=u, default=fk_salt, help="per-file accesskey salt; used to generate unpredictable URLs for hidden files") ap2.add_argument("--dk-salt", metavar="SALT", type=u, default=dk_salt, help="per-directory accesskey salt; used to generate unpredictable URLs to share folders with users who only have the 'get' permission") ap2.add_argument("--warksalt", metavar="SALT", type=u, default="hunter2", help="up2k file-hash salt; serves no purpose, no reason to change this (but delete all databases if you do)") ap2.add_argument("--show-ah-salt", action="store_true", help="on startup, print the effective value of \033[33m--ah-salt\033[0m (the autogenerated value in $XDG_CONFIG_HOME unless otherwise specified)") ap2.add_argument("--show-fk-salt", action="store_true", help="on startup, print the effective value of \033[33m--fk-salt\033[0m (the autogenerated value in $XDG_CONFIG_HOME unless otherwise specified)") ap2.add_argument("--show-dk-salt", action="store_true", help="on startup, print the effective value of \033[33m--dk-salt\033[0m (the autogenerated value in $XDG_CONFIG_HOME unless otherwise specified)") def add_shutdown(ap): ap2 = ap.add_argument_group("shutdown options") ap2.add_argument("--ign-ebind", action="store_true", help="continue running even if it's impossible to listen on some of the requested endpoints") ap2.add_argument("--ign-ebind-all", action="store_true", help="continue running even if it's impossible to receive connections at all") ap2.add_argument("--exit", metavar="WHEN", type=u, default="", help="shutdown after \033[33mWHEN\033[0m has finished; [\033[32mcfg\033[0m] config parsing, [\033[32midx\033[0m] volscan + multimedia indexing") def add_logging(ap): ap2 = ap.add_argument_group("logging options") ap2.add_argument("-q", action="store_true", help="quiet; disable most STDOUT messages") ap2.add_argument("-lo", metavar="PATH", type=u, default="", help="logfile; use .txt for plaintext or .xz for compressed. Example: \033[32mcpp-%%Y-%%m%%d-%%H%%M%%S.txt.xz\033[0m (NB: some errors may appear on STDOUT only)") ap2.add_argument("--flo", metavar="N", type=int, default=1, help="log format for \033[33m-lo\033[0m; [\033[32m1\033[0m]=classic/colors, [\033[32m2\033[0m]=no-color") ap2.add_argument("--no-ansi", action="store_true", default=not VT100, help="disable colors; same as environment-variable NO_COLOR") ap2.add_argument("--ansi", action="store_true", help="force colors; overrides environment-variable NO_COLOR") ap2.add_argument("--no-logflush", action="store_true", help="don't flush the logfile after each write; tiny bit faster") ap2.add_argument("--no-voldump", action="store_true", help="do not list volumes and permissions on startup") ap2.add_argument("--log-utc", action="store_true", help="do not use local timezone; assume the TZ env-var is UTC (tiny bit faster)") ap2.add_argument("--log-tdec", metavar="N", type=int, default=3, help="timestamp resolution / number of timestamp decimals") ap2.add_argument("--log-date", metavar="TXT", type=u, default="", help="date-format, for example [\033[32m%%Y-%%m-%%d\033[0m] (default is disabled; no date, just HH:MM:SS)") ap2.add_argument("--log-badpwd", metavar="N", type=int, default=2, help="log failed login attempt passwords: 0=terse, 1=plaintext, 2=hashed") ap2.add_argument("--log-badxml", action="store_true", help="log any invalid XML received from a client") ap2.add_argument("--log-conn", action="store_true", help="debug: print tcp-server msgs") ap2.add_argument("--log-htp", action="store_true", help="debug: print http-server threadpool scaling") ap2.add_argument("--ihead", metavar="HEADER", type=u, action='append', help="print request \033[33mHEADER\033[0m; [\033[32m*\033[0m]=all") ap2.add_argument("--ohead", metavar="HEADER", type=u, action='append', help="print response \033[33mHEADER\033[0m; [\033[32m*\033[0m]=all") ap2.add_argument("--lf-url", metavar="RE", type=u, default=r"^/\.cpr/|[?&]th=[xwjp]|/\.(_|ql_|DS_Store$|localized$)", help="dont log URLs matching regex \033[33mRE\033[0m") ap2.add_argument("--scan-st-r", metavar="SEC", type=float, default=0.1, help="fs-indexing: wait \033[33mSEC\033[0m between each status-message") ap2.add_argument("--scan-pr-r", metavar="SEC", type=float, default=10, help="fs-indexing: wait \033[33mSEC\033[0m between each 'progress:' message") ap2.add_argument("--scan-pr-s", metavar="MiB", type=float, default=1, help="fs-indexing: say 'file: <name>' when a file larger than \033[33mMiB\033[0m is about to be hashed") def add_admin(ap): ap2 = ap.add_argument_group("admin panel options") ap2.add_argument("--no-reload", action="store_true", help="disable ?reload=cfg (reload users/volumes/volflags from config file)") ap2.add_argument("--no-rescan", action="store_true", help="disable ?scan (volume reindexing)") ap2.add_argument("--no-stack", action="store_true", help="disable ?stack (list all stacks); same as --stack-who=no") ap2.add_argument("--no-ups-page", action="store_true", help="disable ?ru (list of recent uploads)") ap2.add_argument("--no-up-list", action="store_true", help="don't show list of incoming files in controlpanel") ap2.add_argument("--dl-list", metavar="LVL", type=int, default=2, help="who can see active downloads in the controlpanel? [\033[32m0\033[0m]=nobody, [\033[32m1\033[0m]=admins, [\033[32m2\033[0m]=everyone") ap2.add_argument("--ups-who", metavar="LVL", type=int, default=2, help="who can see recent uploads on the ?ru page? [\033[32m0\033[0m]=nobody, [\033[32m1\033[0m]=admins, [\033[32m2\033[0m]=everyone (volflag=ups_who)") ap2.add_argument("--ups-when", action="store_true", help="let everyone see upload timestamps on the ?ru page, not just admins") ap2.add_argument("--stack-who", metavar="LVL", type=u, default="a", help="who can see the ?stack page (list of threads)? [\033[32mno\033[0m]=nobody, [\033[32ma\033[0m]=admins, [\033[32mrw\033[0m]=read+write, [\033[32mall\033[0m]=everyone") ap2.add_argument("--stack-v", action="store_true", help="verbose ?stack") def add_thumbnail(ap): th_ram = (RAM_AVAIL or RAM_TOTAL or 9) * 0.6 th_ram = int(max(min(th_ram, 6), 0.3) * 10) / 10 ap2 = ap.add_argument_group("thumbnail options") ap2.add_argument("--no-thumb", action="store_true", help="disable all thumbnails (volflag=dthumb)") ap2.add_argument("--no-vthumb", action="store_true", help="disable video thumbnails (volflag=dvthumb)") ap2.add_argument("--no-athumb", action="store_true", help="disable audio thumbnails (spectrograms) (volflag=dathumb)") ap2.add_argument("--th-size", metavar="WxH", default="320x256", help="thumbnail res (volflag=thsize)") ap2.add_argument("--th-mt", metavar="CORES", type=int, default=CORES, help="num cpu cores to use for generating thumbnails") ap2.add_argument("--th-convt", metavar="SEC", type=float, default=60.0, help="convert-to-image timeout in seconds (volflag=convt)") ap2.add_argument("--ac-convt", metavar="SEC", type=float, default=150.0, help="convert-to-audio timeout in seconds (volflag=aconvt)") ap2.add_argument("--th-ram-max", metavar="GB", type=float, default=th_ram, help="max memory usage (GiB) permitted by thumbnailer; not very accurate") ap2.add_argument("--th-crop", metavar="TXT", type=u, default="y", help="crop thumbnails to 4:3 or keep dynamic height; client can override in UI unless force. [\033[32my\033[0m]=crop, [\033[32mn\033[0m]=nocrop, [\033[32mfy\033[0m]=force-y, [\033[32mfn\033[0m]=force-n (volflag=crop)") ap2.add_argument("--th-x3", metavar="TXT", type=u, default="n", help="show thumbs at 3x resolution; client can override in UI unless force. [\033[32my\033[0m]=yes, [\033[32mn\033[0m]=no, [\033[32mfy\033[0m]=force-yes, [\033[32mfn\033[0m]=force-no (volflag=th3x)") ap2.add_argument("--th-qv", metavar="N", type=int, default=40, help="webp/jpg thumbnail quality (10~90); higher is larger filesize and better quality (volflag=th_qv)") ap2.add_argument("--th-qvx", metavar="N", type=int, default=64, help="jxl thumbnail quality (10~90); higher is larger filesize and better quality (volflag=th_qvx)") ap2.add_argument("--th-dec", metavar="LIBS", default="vips,raw,pil,ff", help="image decoders, in order of preference") ap2.add_argument("--th-no-jpg", action="store_true", help="disable jpg output") ap2.add_argument("--th-no-webp", action="store_true", help="disable webp output") ap2.add_argument("--th-no-jxl", action="store_true", help="disable jpeg-xl output") ap2.add_argument("--th-ff-jpg", action="store_true", help="force jpg output for video thumbs (avoids issues on some FFmpeg builds)") ap2.add_argument("--th-ff-swr", action="store_true", help="use swresample instead of soxr for audio thumbs (faster, lower accuracy, avoids issues on some FFmpeg builds)") ap2.add_argument("--th-poke", metavar="SEC", type=int, default=300, help="activity labeling cooldown -- avoids doing keepalive pokes (updating the mtime) on thumbnail folders more often than \033[33mSEC\033[0m seconds") ap2.add_argument("--th-clean", metavar="SEC", type=int, default=43200, help="cleanup interval; 0=disabled") ap2.add_argument("--th-maxage", metavar="SEC", type=int, default=604800, help="max folder age -- folders which haven't been poked for longer than \033[33m--th-poke\033[0m seconds will get deleted every \033[33m--th-clean\033[0m seconds") ap2.add_argument("--th-covers", metavar="N,N", type=u, default="folder.png,folder.jpg,cover.png,cover.jpg", help="folder thumbnails to stat/look for; enabling \033[33m-e2d\033[0m will make these case-insensitive, and try them as dotfiles (.folder.jpg), and also automatically select thumbnails for all folders that contain pics, even if none match this pattern") ap2.add_argument("--th-spec-p", metavar="N", type=u, default=1, help="for music, do spectrograms or embedded coverart? [\033[32m0\033[0m]=only-art, [\033[32m1\033[0m]=prefer-art, [\033[32m2\033[0m]=only-spec") # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html # https://github.com/libvips/libvips # https://stackoverflow.com/a/47612661 # ffmpeg -hide_banner -demuxers | awk '/^ D /{print$2}' | while IFS= read -r x; do ffmpeg -hide_banner -h demuxer=$x; done | grep -E '^Demuxer |extensions:' ap2.add_argument("--th-r-pil", metavar="T,T", type=u, default="avif,avifs,blp,bmp,cbz,dcx,dds,dib,emf,eps,epub,fits,flc,fli,fpx,gif,heic,heics,heif,heifs,icns,ico,im,j2p,j2k,jp2,jpeg,jpg,jpx,jxl,pbm,pcx,pgm,png,pnm,ppm,psd,qoi,sgi,spi,tga,tif,tiff,webp,wmf,xbm,xpm", help="image formats to decode using pillow") ap2.add_argument("--th-r-vips", metavar="T,T", type=u, default="3fr,avif,cr2,cr3,crw,dcr,dng,erf,exr,fit,fits,fts,gif,hdr,heic,heics,heif,heifs,jp2,jpeg,jpg,jpx,jxl,k25,mdc,mef,mrw,nef,nii,pfm,pgm,png,ppm,raf,raw,sr2,srf,svg,tif,tiff,webp,x3f", help="image formats to decode using pyvips") ap2.add_argument("--th-r-raw", metavar="T,T", type=u, default="3fr,arw,cr2,cr3,crw,dcr,dng,erf,k25,kdc,mdc,mef,mos,mrw,nef,nrw,orf,pef,raf,raw,sr2,srf,srw,x3f", help="image formats to decode using rawpy") ap2.add_argument("--th-r-ffi", metavar="T,T", type=u, default="apng,avif,avifs,bmp,cbz,dds,dib,epub,fit,fits,fts,gif,hdr,heic,heics,heif,heifs,icns,ico,jp2,jpeg,jpg,jpx,jxl,pbm,pcx,pfm,pgm,png,pnm,ppm,psd,qoi,sgi,tga,tif,tiff,webp,xbm,xpm", help="image formats to decode using ffmpeg") ap2.add_argument("--th-r-ffv", metavar="T,T", type=u, default="3gp,asf,av1,avc,avi,flv,h264,h265,hevc,m4v,mjpeg,mjpg,mkv,mov,mp4,mpeg,mpeg2,mpegts,mpg,mpg2,mts,nut,ogm,ogv,rm,ts,vob,webm,wmv", help="video formats to decode using ffmpeg") ap2.add_argument("--th-r-ffa", metavar="T,T", type=u, default="aac,ac3,aif,aiff,alac,alaw,amr,apac,ape,au,bonk,dfpwm,dts,flac,gsm,ilbc,it,itgz,itxz,itz,m4a,m4b,m4r,mdgz,mdxz,mdz,mo3,mod,mp2,mp3,mpc,mptm,mt2,mulaw,oga,ogg,okt,opus,ra,s3m,s3gz,s3xz,s3z,tak,tta,ulaw,wav,wma,wv,xm,xmgz,xmxz,xmz,xpk", help="audio formats to decode using ffmpeg") ap2.add_argument("--th-spec-cnv", metavar="T", type=u, default="it,itgz,itxz,itz,mdgz,mdxz,mdz,mo3,mod,s3m,s3gz,s3xz,s3z,xm,xmgz,xmxz,xmz,xpk", help="audio formats which provoke https://trac.ffmpeg.org/ticket/10797 (huge ram usage for s3xmodit spectrograms)") ap2.add_argument("--au-unpk", metavar="E=F.C", type=u, default="mdz=mod.zip, mdgz=mod.gz, mdxz=mod.xz, s3z=s3m.zip, s3gz=s3m.gz, s3xz=s3m.xz, xmz=xm.zip, xmgz=xm.gz, xmxz=xm.xz, itz=it.zip, itgz=it.gz, itxz=it.xz, cbz=jpg.cbz, epub=jpg.epub", help="audio/image formats to decompress before passing to ffmpeg") def add_transcoding(ap): ap2 = ap.add_argument_group("transcoding options") ap2.add_argument("--q-opus", metavar="KBPS", type=int, default=128, help="target bitrate for transcoding to opus; set 0 to disable") ap2.add_argument("--q-mp3", metavar="QUALITY", type=u, default="q2", help="target quality for transcoding to mp3, for example [\033[32m192k\033[0m] (CBR) or [\033[32mq0\033[0m] (CQ/CRF, q0=maxquality, q9=smallest); set 0 to disable") ap2.add_argument("--allow-wav", action="store_true", help="allow transcoding to wav (lossless, uncompressed)") ap2.add_argument("--allow-flac", action="store_true", help="allow transcoding to flac (lossless, compressed)") ap2.add_argument("--no-caf", action="store_true", help="disable transcoding to caf-opus (affects iOS v12~v17), will use mp3 instead") ap2.add_argument("--no-owa", action="store_true", help="disable transcoding to webm-opus (iOS v18 and later), will use mp3 instead") ap2.add_argument("--no-acode", action="store_true", help="disable audio transcoding") ap2.add_argument("--no-bacode", action="store_true", help="disable batch audio transcoding by folder download (zip/tar)") ap2.add_argument("--ac-maxage", metavar="SEC", type=int, default=86400, help="delete cached transcode output after \033[33mSEC\033[0m seconds") def add_tail(ap): ap2 = ap.add_argument_group("tailing options (realtime streaming of a growing file)") ap2.add_argument("--tail-who", metavar="LVL", type=int, default=2, help="who can tail? [\033[32m0\033[0m]=nobody, [\033[32m1\033[0m]=admins, [\033[32m2\033[0m]=authenticated-with-read-access, [\033[32m3\033[0m]=everyone-with-read-access (volflag=tail_who)") ap2.add_argument("--tail-cmax", metavar="N", type=int, default=64, help="do not allow starting a new tail if more than \033[33mN\033[0m active downloads") ap2.add_argument("--tail-tmax", metavar="SEC", type=float, default=0, help="terminate connection after \033[33mSEC\033[0m seconds; [\033[32m0\033[0m]=never (volflag=tail_tmax)") ap2.add_argument("--tail-rate", metavar="SEC", type=float, default=0.2, help="check for new data every \033[33mSEC\033[0m seconds (volflag=tail_rate)") ap2.add_argument("--tail-ka", metavar="SEC", type=float, default=3.0, help="send a zerobyte if connection is idle for \033[33mSEC\033[0m seconds to prevent disconnect") ap2.add_argument("--tail-fd", metavar="SEC", type=float, default=1.0, help="check if file was replaced (new fd) if idle for \033[33mSEC\033[0m seconds (volflag=tail_fd)") def add_rss(ap): ap2 = ap.add_argument_group("RSS options") ap2.add_argument("--rss", action="store_true", help="enable RSS output (experimental) (volflag=rss)") ap2.add_argument("--rss-nf", metavar="HITS", type=int, default=250, help="default number of files to return (url-param 'nf')") ap2.add_argument("--rss-fext", metavar="E,E", type=u, default="", help="default list of file extensions to include (url-param 'fext'); blank=all") ap2.add_argument("--rss-sort", metavar="ORD", type=u, default="m", help="default sort order (url-param 'sort'); [\033[32mm\033[0m]=last-modified [\033[32mu\033[0m]=upload-time [\033[32mn\033[0m]=filename [\033[32ms\033[0m]=filesize; Uppercase=oldest-first. Note that upload-time is 0 for non-uploaded files (volflag=rss_sort)") ap2.add_argument("--rss-fmt-t", metavar="TXT", type=u, default="{fname}", help="title format (url-param 'rss_fmt_t') (volflag=rss_fmt_t)") ap2.add_argument("--rss-fmt-d", metavar="TXT", type=u, default="{artist} - {title}", help="description format (url-param 'rss_fmt_d') (volflag=rss_fmt_d)") def add_db_general(ap, hcores): noidx = APPLESAN_TXT if MACOS else "" ap2 = ap.add_argument_group("general db options") ap2.add_argument("-e2d", action="store_true", help="enable up2k database; this enables file search, upload-undo, improves deduplication") ap2.add_argument("-e2ds", action="store_true", help="scan writable folders for new files on startup; sets \033[33m-e2d\033[0m") ap2.add_argument("-e2dsa", action="store_true", help="scans all folders on startup; sets \033[33m-e2ds\033[0m") ap2.add_argument("-e2v", action="store_true", help="verify file integrity; rehash all files and compare with db") ap2.add_argument("-e2vu", action="store_true", help="on hash mismatch: update the database with the new hash") ap2.add_argument("-e2vp", action="store_true", help="on hash mismatch: panic and quit copyparty") ap2.add_argument("--hist", metavar="PATH", type=u, default="", help="where to store volume data (db, thumbs); default is a folder named \".hist\" inside each volume (volflag=hist)") ap2.add_argument("--dbpath", metavar="PATH", type=u, default="", help="override where the volume databases are to be placed; default is the same as \033[33m--hist\033[0m (volflag=dbpath)") ap2.add_argument("--fika", metavar="TXT", type=u, default="ucd", help="list of user-actions to allow while filesystem-indexer is still busy; set blank to never interrupt indexing (old default). [\033[32mu\033[0m]=uploads, [\033[32mc\033[0m]=filecopy, [\033[32mm\033[0m]=move/rename, [\033[32md\033[0m]=delete. NOTE: [\033[32mm\033[0m] is untested/scary, and blank is recommended if dedup enabled") ap2.add_argument("--no-hash", metavar="PTN", type=u, default="", help="regex: disable hashing of matching absolute-filesystem-paths during e2ds folder scans (must be specified as one big regex, not multiple times) (volflag=nohash)") ap2.add_argument("--no-idx", metavar="PTN", type=u, default=noidx, help="regex: disable indexing of matching absolute-filesystem-paths during e2ds folder scan (must be specified as one big regex, not multiple times) (volflag=noidx)") ap2.add_argument("--no-dirsz", action="store_true", help="do not show total recursive size of folders in listings, show inode size instead; slightly faster (volflag=nodirsz)") ap2.add_argument("--re-dirsz", action="store_true", help="if the directory-sizes in the UI are bonkers, use this along with \033[33m-e2dsa\033[0m to rebuild the index from scratch") ap2.add_argument("--no-dhash", action="store_true", help="disable rescan acceleration; do full database integrity check -- makes the db ~5%% smaller and bootup/rescans 3~10x slower") ap2.add_argument("--re-dhash", action="store_true", help="force a cache rebuild on startup; enable this once if it gets out of sync (should never be necessary)") ap2.add_argument("--no-forget", action="store_true", help="never forget indexed files, even when deleted from disk -- makes it impossible to ever upload the same file twice -- only useful for offloading uploads to a cloud service or something (volflag=noforget)") ap2.add_argument("--forget-ip", metavar="MIN", type=int, default=0, help="remove uploader-IP from database (and make unpost impossible) \033[33mMIN\033[0m minutes after upload, for GDPR reasons. Default [\033[32m0\033[0m] is never-forget. [\033[32m1440\033[0m]=day, [\033[32m10080\033[0m]=week, [\033[32m43200\033[0m]=month. (volflag=forget_ip)") ap2.add_argument("--dbd", metavar="PROFILE", default="wal", help="database durability profile; sets the tradeoff between robustness and speed, see \033[33m--help-dbd\033[0m (volflag=dbd)") ap2.add_argument("--xlink", action="store_true", help="on upload: check all volumes for dupes, not just the target volume (probably buggy, not recommended) (volflag=xlink)") ap2.add_argument("--hash-mt", metavar="CORES", type=int, default=hcores, help="num cpu cores to use for file hashing; set 0 or 1 for single-core hashing") ap2.add_argument("--re-maxage", metavar="SEC", type=int, default=0, help="rescan filesystem for changes every \033[33mSEC\033[0m seconds; 0=off (volflag=scan)") ap2.add_argument("--db-act", metavar="SEC", type=float, default=10.0, help="defer any scheduled volume reindexing until \033[33mSEC\033[0m seconds after last db write (uploads, renames, ...)") ap2.add_argument("--srch-icase", action="store_true", help="case-insensitive search for all unicode characters (the default is icase for just ascii). NOTE: will make searches much slower (around 4x), and NOTE: only applies to filenames/paths, not tags") ap2.add_argument("--srch-time", metavar="SEC", type=int, default=45, help="search deadline -- terminate searches running for more than \033[33mSEC\033[0m seconds") ap2.add_argument("--srch-hits", metavar="N", type=int, default=7999, help="max search results to allow clients to fetch; 125 results will be shown initially") ap2.add_argument("--srch-excl", metavar="PTN", type=u, default="", help="regex: exclude files from search results if the file-URL matches \033[33mPTN\033[0m (case-sensitive). Example: [\033[32mpassword|logs/[0-9]\033[0m] any URL containing 'password' or 'logs/DIGIT' (volflag=srch_excl)") ap2.add_argument("--dotsrch", action="store_true", help="show dotfiles in search results (volflags: dotsrch | nodotsrch)") def add_db_metadata(ap): ap2 = ap.add_argument_group("metadata db options") ap2.add_argument("-e2t", action="store_true", help="enable metadata indexing; makes it possible to search for artist/title/codec/resolution/...") ap2.add_argument("-e2ts", action="store_true", help="scan newly discovered files for metadata on startup; sets \033[33m-e2t\033[0m") ap2.add_argument("-e2tsr", action="store_true", help="delete all metadata from DB and do a full rescan; sets \033[33m-e2ts\033[0m") ap2.add_argument("--no-mutagen", action="store_true", help="use FFprobe for tags instead; will detect more tags") ap2.add_argument("--no-mtag-ff", action="store_true", help="never use FFprobe as tag reader; is probably safer") ap2.add_argument("--mtag-to", metavar="SEC", type=int, default=60, help="timeout for FFprobe tag-scan") ap2.add_argument("--mtag-mt", metavar="CORES", type=int, default=CORES, help="num cpu cores to use for tag scanning") ap2.add_argument("--mtag-v", action="store_true", help="verbose tag scanning; print errors from mtp subprocesses and such") ap2.add_argument("--mtag-vv", action="store_true", help="debug mtp settings and mutagen/FFprobe parsers") ap2.add_argument("--db-xattr", metavar="t,t", type=u, default="", help="read file xattrs as metadata tags; [\033[32ma,b\033[0m] reads keys \033[33ma\033[0m and \033[33mb\033[0m as tags \033[33ma\033[0m and \033[33mb\033[0m, [\033[32ma=foo,b=bar\033[0m] reads keys \033[33ma\033[0m and \033[33mb\033[0m as tags \033[33mfoo\033[0m and \033[33mbar\033[0m, [\033[32m~~a,b\033[0m] does everything except \033[33ma\033[0m and \033[33mb\033[0m, [\033[32m~~\033[0m] does everything. NOTE: Each tag must also be enabled with \033[33m-mte\033[0m (volflag=db_xattr)") ap2.add_argument("-mtm", metavar="M=t,t,t", type=u, action="append", help="\033[34mREPEATABLE:\033[0m add/replace metadata mapping") ap2.add_argument("-mte", metavar="M,M,M", type=u, help="tags to index/display (comma-sep.); either an entire replacement list, or add/remove stuff on the default-list with +foo or /bar", default=DEF_MTE) ap2.add_argument("-mth", metavar="M,M,M", type=u, help="tags to hide by default (comma-sep.); assign/add/remove same as \033[33m-mte\033[0m", default=DEF_MTH) ap2.add_argument("-mtp", metavar="M=[f,]BIN", type=u, action="append", help="\033[34mREPEATABLE:\033[0m read tag \033[33mM\033[0m using program \033[33mBIN\033[0m to parse the file") ap2.add_argument("--have-db-xattr", action="store_true", help=argparse.SUPPRESS) def add_txt(ap): ap2 = ap.add_argument_group("textfile options") ap2.add_argument("--rw-edit", metavar="T,T", type=u, default="md", help="comma-sep. list of file-extensions to allow editing with permissions read+write; all others require read+write+delete (volflag=rw_edit)") ap2.add_argument("--md-no-br", action="store_true", help="markdown: disable newline-is-newline; will only render a newline into the html given two trailing spaces or a double-newline (volflag=md_no_br)") ap2.add_argument("--md-hist", metavar="TXT", type=u, default="s", help="where to store old version of markdown files; [\033[32ms\033[0m]=subfolder, [\033[32mv\033[0m]=volume-histpath, [\033[32mn\033[0m]=nope/disabled (volflag=md_hist)") ap2.add_argument("--txt-eol", metavar="TYPE", type=u, default="", help="enable EOL conversion when writing documents; supported: CRLF, LF (volflag=txt_eol)") ap2.add_argument("-mcr", metavar="SEC", type=int, default=60, help="the textfile editor will check for serverside changes every \033[33mSEC\033[0m seconds") ap2.add_argument("-emp", action="store_true", help="enable markdown plugins -- neat but dangerous, big XSS risk") ap2.add_argument("--exp", action="store_true", help="enable textfile expansion -- replace {{self.ip}} and such; see \033[33m--help-exp\033[0m (volflag=exp)") ap2.add_argument("--exp-md", metavar="V,V,V", type=u, default=DEF_EXP, help="comma/space-separated list of placeholders to expand in markdown files; add/remove stuff on the default list with +hdr_foo or /vf.scan (volflag=exp_md)") ap2.add_argument("--exp-lg", metavar="V,V,V", type=u, default=DEF_EXP, help="comma/space-separated list of placeholders to expand in prologue/epilogue files (volflag=exp_lg)") ap2.add_argument("--ua-nodoc", metavar="PTN", type=u, default=BAD_BOTS, help="regex of user-agents to reject from viewing documents through ?doc=[...]; disable with [\033[32mno\033[0m] or blank") def add_og(ap): ap2 = ap.add_argument_group("og / open graph / discord-embed options") ap2.add_argument("--og", action="store_true", help="disable hotlinking and return an html document instead; this is required by open-graph, but can also be useful on its own (volflag=og)") ap2.add_argument("--og-ua", metavar="RE", type=u, default="", help="only disable hotlinking / engage OG behavior if the useragent matches regex \033[33mRE\033[0m (volflag=og_ua)") ap2.add_argument("--og-tpl", metavar="PATH", type=u, default="", help="do not return the regular copyparty html, but instead load the jinja2 template at \033[33mPATH\033[0m (if path contains 'EXT' then EXT will be replaced with the requested file's extension) (volflag=og_tpl)") ap2.add_argument("--og-no-head", action="store_true", help="do not automatically add OG entries into <head> (useful if you're doing this yourself in a template or such) (volflag=og_no_head)") ap2.add_argument("--og-th", metavar="FMT", type=u, default="jf3", help="thumbnail format; j=jpeg, jf=jpeg-uncropped, jf3=jpeg-uncropped-large, w=webm, ... (volflag=og_th)") ap2.add_argument("--og-title", metavar="TXT", type=u, default="", help="fallback title if there is nothing in the \033[33m-e2t\033[0m database (volflag=og_title)") ap2.add_argument("--og-title-a", metavar="T", type=u, default="🎵 {{ artist }} - {{ title }}", help="audio title format; takes any metadata key (volflag=og_title_a)") ap2.add_argument("--og-title-v", metavar="T", type=u, default="{{ title }}", help="video title format; takes any metadata key (volflag=og_title_v)") ap2.add_argument("--og-title-i", metavar="T", type=u, default="{{ title }}", help="image title format; takes any metadata key (volflag=og_title_i)") ap2.add_argument("--og-s-title", action="store_true", help="force default title; do not read from tags (volflag=og_s_title)") ap2.add_argument("--og-desc", metavar="TXT", type=u, default="", help="description text; same for all files, disable with [\033[32m-\033[0m] (volflag=og_desc)") ap2.add_argument("--og-site", metavar="TXT", type=u, default="", help="sitename; defaults to \033[33m--name\033[0m, disable with [\033[32m-\033[0m] (volflag=og_site)") ap2.add_argument("--tcolor", metavar="RGB", type=u, default="333", help="accent color (3 or 6 hex digits); may also affect safari and/or android-chrome (volflag=tcolor)") ap2.add_argument("--uqe", action="store_true", help="query-string parceling; translate a request for \033[33m/foo/.uqe/BASE64\033[0m into \033[33m/foo?TEXT\033[0m, or \033[33m/foo/?TEXT\033[0m if the first character in \033[33mTEXT\033[0m is a slash. Automatically enabled for \033[33m--og\033[0m") def add_ui(ap, retry: int): THEMES = 10 ap2 = ap.add_argument_group("ui options") ap2.add_argument("--grid", action="store_true", help="show grid/thumbnails by default (volflag=grid)") ap2.add_argument("--gsel", action="store_true", help="select files in grid by ctrl-click (volflag=gsel)") ap2.add_argument("--localtime", action="store_true", help="default to local timezone instead of UTC") ap2.add_argument("--ui-filesz", metavar="FMT", type=u, default="1", help="default filesize format; one of these: 0, 1, 2, 2c, 3, 3c, 4, 4c, 5, 5c, fuzzy (see UI)") ap2.add_argument("--rcm", metavar="TXT", default="yy", help="rightclick-menu; two yes/no options: 1st y/n is enable-custom-menu, 2nd y/n is enable-double") ap2.add_argument("--lang", metavar="LANG", type=u, default="eng", help="language, for example \033[32meng\033[0m / \033[32mnor\033[0m / ...") ap2.add_argument("--theme", metavar="NUM", type=int, default=0, help="default theme to use (0..%d)" % (THEMES - 1,)) ap2.add_argument("--themes", metavar="NUM", type=int, default=THEMES, help="number of themes installed") ap2.add_argument("--au-vol", metavar="0-100", type=int, default=50, choices=range(0, 101), help="default audio/video volume percent") ap2.add_argument("--sort", metavar="C,C,C", type=u, default="href", help="default sort order, comma-separated column IDs (see header tooltips), prefix with '-' for descending. Examples: \033[32mhref -href ext sz ts tags/Album tags/.tn\033[0m (volflag=sort)") ap2.add_argument("--nsort", action="store_true", help="default-enable natural sort of filenames with leading numbers (volflag=nsort)") ap2.add_argument("--hsortn", metavar="N", type=int, default=2, help="number of sorting rules to include in media URLs by default (volflag=hsortn)") ap2.add_argument("--see-dots", action="store_true", help="default-enable seeing dotfiles; only takes effect if user has the necessary permissions") ap2.add_argument("--qdel", metavar="LVL", type=int, default=2, help="number of confirmations to show when deleting files (2/1/0)") ap2.add_argument("--dlni", action="store_true", help="force download (don't show inline) when files are clicked (volflag:dlni)") ap2.add_argument("--unlist", metavar="REGEX", type=u, default="", help="don't show files/folders matching \033[33mREGEX\033[0m in file list. WARNING: Purely cosmetic! Does not affect API calls, just the browser. Example: [\033[32m\\.(js|css)$\033[0m] (volflag=unlist)") ap2.add_argument("--favico", metavar="TXT", type=u, default="c 000 none" if retry else "🎉 000 none", help="\033[33mfavicon-text\033[0m [ \033[33mforeground\033[0m [ \033[33mbackground\033[0m ] ], set blank to disable") ap2.add_argument("--ufavico", metavar="TXT", type=u, default="", help="URL to .ico/png/gif/svg file; \033[33m--favico\033[0m takes precedence unless disabled (volflag=ufavico)") ap2.add_argument("--ext-th", metavar="E=VP", type=u, action="append", help="\033[34mREPEATABLE:\033[0m use thumbnail-image \033[33mVP\033[0m for file-extension \033[33mE\033[0m, example: [\033[32mexe=/.res/exe.png\033[0m] (volflag=ext_th)") ap2.add_argument("--mpmc", type=u, default="", help=argparse.SUPPRESS) ap2.add_argument("--notooltips", action="store_true", help="tooltips disabled as default") ap2.add_argument("--spinner", metavar="TXT", type=u, default="🌲", help="\033[33memoji\033[0m or \033[33memoji,css\033[0m Example: [\033[32m🥖,padding:0\033[0m]") ap2.add_argument("--css-browser", metavar="L", type=u, default="", help="URL to additional CSS to include in the filebrowser html") ap2.add_argument("--js-browser", metavar="L", type=u, default="", help="URL to additional JS to include in the filebrowser html") ap2.add_argument("--js-other", metavar="L", type=u, default="", help="URL to additional JS to include in all other pages") ap2.add_argument("--html-head", metavar="TXT", type=u, default="", help="text to append to the <head> of all HTML pages (except for basic-browser); can be @PATH to send the contents of a file at PATH, and/or begin with %% to render as jinja2 template (volflag=html_head)") ap2.add_argument("--html-head-s", metavar="T", type=u, default="", help="text to append to the <head> of all HTML pages (except for basic-browser); similar to (and can be combined with) --html-head but only accepts static text (volflag=html_head_s)") ap2.add_argument("--ih", action="store_true", help="if a folder contains index.html, show that instead of the directory listing by default (can be changed in the client settings UI, or add ?v to URL for override)") ap2.add_argument("--textfiles", metavar="CSV", type=u, default="txt,nfo,diz,cue,readme", help="file extensions to present as plaintext") ap2.add_argument("--txt-max", metavar="KiB", type=int, default=64, help="max size of embedded textfiles on ?doc= (anything bigger will be lazy-loaded by JS)") ap2.add_argument("--prologues", metavar="T,T", type=u, default=".prologue.html", help="comma-sep. list of filenames to scan for and use as prologues (embed above/before directory listing) (volflag=prologues)") ap2.add_argument("--epilogues", metavar="T,T", type=u, default=".epilogue.html", help="comma-sep. list of filenames to scan for and use as epilogues (embed below/after directory listing) (volflag=epilogues)") ap2.add_argument("--preadmes", metavar="T,T", type=u, default="preadme.md,PREADME.md", help="comma-sep. list of filenames to scan for and use as preadmes (embed above/before directory listing) (volflag=preadmes)") ap2.add_argument("--readmes", metavar="T,T", type=u, default="readme.md,README.md", help="comma-sep. list of filenames to scan for and use as readmes (embed below/after directory listing) (volflag=readmes)") ap2.add_argument("--doctitle", metavar="TXT", type=u, default="copyparty @ --name", help="title / service-name to show in html documents") ap2.add_argument("--bname", metavar="TXT", type=u, default="--name", help="server name (displayed in filebrowser document title)") ap2.add_argument("--pb-url", metavar="URL", type=u, default=URL_PRJ, help="powered-by link; disable with \033[33m-nb\033[0m") ap2.add_argument("--ver", action="store_true", help="show version on the control panel (incompatible with \033[33m-nb\033[0m). This is the same as --ver-who all") ap2.add_argument("--ver-who", metavar="TXT", type=u, default="no", help="only show version for: [\033[32ma\033[0m]=admin-permission-anywhere, [\033[32mauth\033[0m]=authenticated, [\033[32mall\033[0m]=anyone") ap2.add_argument("--du-who", metavar="TXT", type=u, default="all", help="only show disk usage for: [\033[32mno\033[0m]=nobody, [\033[32ma\033[0m]=admin-permission, [\033[32mrw\033[0m]=read-write, [\033[32mw\033[0m]=write, [\033[32mauth\033[0m]=authenticated, [\033[32mall\033[0m]=anyone (volflag=du_who)") ap2.add_argument("--ver-iwho", type=int, default=0, help=argparse.SUPPRESS) ap2.add_argument("--du-iwho", type=int, default=0, help=argparse.SUPPRESS) ap2.add_argument("--k304", metavar="NUM", type=int, default=0, help="configure the option to enable/disable k304 on the controlpanel (workaround for buggy reverse-proxies); [\033[32m0\033[0m] = hidden and default-off, [\033[32m1\033[0m] = visible and default-off, [\033[32m2\033[0m] = visible and default-on") ap2.add_argument("--no304", metavar="NUM", type=int, default=0, help="configure the option to enable/disable no304 on the controlpanel (workaround for buggy caching in browsers); [\033[32m0\033[0m] = hidden and default-off, [\033[32m1\033[0m] = visible and default-off, [\033[32m2\033[0m] = visible and default-on") ap2.add_argument("--ctl-re", metavar="SEC", type=int, default=1, help="the controlpanel Refresh-button will autorefresh every SEC; [\033[32m0\033[0m] = just once") ap2.add_argument("--md-sbf", metavar="FLAGS", type=u, default="downloads forms popups scripts top-navigation-by-user-activation", help="list of capabilities to allow in the iframe 'sandbox' attribute for README.md docs (volflag=md_sbf); see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox") ap2.add_argument("--lg-sbf", metavar="FLAGS", type=u, default="downloads forms popups scripts top-navigation-by-user-activation", help="list of capabilities to allow in the iframe 'sandbox' attribute for prologue/epilogue docs (volflag=lg_sbf)") ap2.add_argument("--md-sba", metavar="TXT", type=u, default="", help="the value of the iframe 'allow' attribute for README.md docs, for example [\033[32mfullscreen\033[0m] (volflag=md_sba)") ap2.add_argument("--lg-sba", metavar="TXT", type=u, default="", help="the value of the iframe 'allow' attribute for prologue/epilogue docs (volflag=lg_sba); see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy#iframes") ap2.add_argument("--no-sb-md", action="store_true", help="don't sandbox README/PREADME.md documents (volflags: no_sb_md | sb_md)") ap2.add_argument("--no-sb-lg", action="store_true", help="don't sandbox prologue/epilogue docs (volflags: no_sb_lg | sb_lg); enables non-js support") ap2.add_argument("--ui-nombar", action="store_true", help="hide top-menu in the UI (volflag=ui_nombar)") ap2.add_argument("--ui-noacci", action="store_true", help="hide account-info in the UI (volflag=ui_noacci)") ap2.add_argument("--ui-nosrvi", action="store_true", help="hide server-info in the UI (volflag=ui_nosrvi)") ap2.add_argument("--ui-nonav", action="store_true", help="hide navpane+breadcrumbs (volflag=ui_nonav)") ap2.add_argument("--ui-notree", action="store_true", help="hide navpane in the UI (volflag=ui_notree)") ap2.add_argument("--ui-nocpla", action="store_true", help="hide cpanel-link in the UI (volflag=ui_nocpla)") ap2.add_argument("--ui-nolbar", action="store_true", help="hide link-bar in the UI (volflag=ui_nolbar)") ap2.add_argument("--ui-noctxb", action="store_true", help="hide context-buttons in the UI (volflag=ui_noctxb)") ap2.add_argument("--ui-norepl", action="store_true", help="hide repl-button in the UI (volflag=ui_norepl)") ap2.add_argument("--have-unlistc", action="store_true", help=argparse.SUPPRESS) def add_debug(ap): ap2 = ap.add_argument_group("debug options") ap2.add_argument("--vc", action="store_true", help="verbose config file parser (explain config)") ap2.add_argument("--cgen", action="store_true", help="generate config file from current config (best-effort; probably buggy)") ap2.add_argument("--deps", action="store_true", help="list information about detected optional dependencies") if hasattr(select, "poll"): ap2.add_argument("--no-poll", action="store_true", help="kernel-bug workaround: disable poll; use select instead (limits max num clients to ~700)") ap2.add_argument("--no-sendfile", action="store_true", help="kernel-bug workaround: disable sendfile; do a safe and slow read-send-loop instead") ap2.add_argument("--no-scandir", action="store_true", help="kernel-bug workaround: disable scandir; do a listdir + stat on each file instead") ap2.add_argument("--no-fastboot", action="store_true", help="wait for initial filesystem indexing before accepting client requests") ap2.add_argument("--no-htp", action="store_true", help="disable httpserver threadpool, create threads as-needed instead") ap2.add_argument("--rm-sck", action="store_true", help="when listening on unix-sockets, do a basic delete+bind instead of the default atomic bind") ap2.add_argument("--srch-dbg", action="store_true", help="explain search processing, and do some extra expensive sanity checks") ap2.add_argument("--rclone-mdns", action="store_true", help="use mdns-domain instead of server-ip on /?hc") ap2.add_argument("--stackmon", metavar="P,S", type=u, default="", help="write stacktrace to \033[33mP\033[0math every \033[33mS\033[0m second, for example --stackmon=\033[32m./st/%%Y-%%m/%%d/%%H%%M.xz,60") ap2.add_argument("--log-thrs", metavar="SEC", type=float, default=0.0, help="list active threads every \033[33mSEC\033[0m") ap2.add_argument("--log-fk", metavar="REGEX", type=u, default="", help="log filekey params for files where path matches \033[33mREGEX\033[0m; [\033[32m.\033[0m] (a single dot) = all files") ap2.add_argument("--bak-flips", action="store_true", help="[up2k] if a client uploads a bitflipped/corrupted chunk, store a copy according to \033[33m--bf-nc\033[0m and \033[33m--bf-dir\033[0m") ap2.add_argument("--bf-nc", metavar="NUM", type=int, default=200, help="bak-flips: stop if there's more than \033[33mNUM\033[0m files at \033[33m--kf-dir\033[0m already; default: 6.3 GiB max (200*32M)") ap2.add_argument("--bf-dir", metavar="PATH", type=u, default="bf", help="bak-flips: store corrupted chunks at \033[33mPATH\033[0m; default: folder named 'bf' wherever copyparty was started") ap2.add_argument("--bf-log", metavar="PATH", type=u, default="", help="bak-flips: log corruption info to a textfile at \033[33mPATH\033[0m") ap2.add_argument("--no-cfg-cmt-warn", action="store_true", help=argparse.SUPPRESS) # fmt: on def run_argparse( argv: list[str], formatter: Any, retry: int, nc: int, verbose=True ) -> argparse.Namespace: ap = argparse.ArgumentParser( formatter_class=formatter, usage=argparse.SUPPRESS, prog="copyparty", description="http file sharing hub v{} ({})".format(S_VERSION, S_BUILD_DT), ) cert_path = os.path.join(E.cfg, "cert.pem") fk_salt = get_salt("fk", 18) dk_salt = get_salt("dk", 30) ah_salt = get_salt("ah", 18) # alpine peaks at 5 threads for some reason, # all others scale past that (but try to avoid SMT), # 5 should be plenty anyways (3 GiB/s on most machines) hcores = min(CORES, 5 if CORES > 8 else 4) tty = os.environ.get("TERM", "").lower() == "linux" srvname = get_srvname(verbose) add_general(ap, nc, srvname) add_network(ap) add_tls(ap, cert_path) add_cert(ap, cert_path) add_auth(ap) add_chpw(ap) add_qr(ap, tty) add_zeroconf(ap) add_zc_mdns(ap) add_zc_ssdp(ap) add_fs(ap) add_share(ap) add_upload(ap) add_db_general(ap, hcores) add_db_metadata(ap) add_thumbnail(ap) add_transcoding(ap) add_rss(ap) add_sftp(ap) add_ftp(ap) add_webdav(ap) add_tftp(ap) add_smb(ap) add_opds(ap) add_safety(ap) add_salt(ap, fk_salt, dk_salt, ah_salt) add_optouts(ap) add_shutdown(ap) add_yolo(ap) add_handlers(ap) add_hooks(ap) add_stats(ap) add_txt(ap) add_tail(ap) add_og(ap) add_ui(ap, retry) add_admin(ap) add_logging(ap) add_debug(ap) ap2 = ap.add_argument_group("help sections") sects = get_sects() for k, h, _ in sects: ap2.add_argument("--help-" + k, action="store_true", help=h) if retry: a = ["ascii", "replace"] for x in ap._actions: try: x.default = x.default.encode(*a).decode(*a) except: pass try: if x.help and x.help is not argparse.SUPPRESS: x.help = x.help.replace("└─", "`-").encode(*a).decode(*a) if retry > 2: x.help = RE_ANSI.sub("", x.help) except: pass ret = ap.parse_args(args=argv[1:]) for k, h, t in sects: k2 = "help_" + k.replace("-", "_") if vars(ret)[k2]: lprint("# %s help page (%s)" % (k, h)) lprint(t.rstrip() + "\033[0m") sys.exit(0) return ret def main(argv: Optional[list[str]] = None) -> None: if argv is None: argv = sys.argv if "--versionb" in argv: print(S_VERSION) sys.exit(0) time.strptime("19970815", "%Y%m%d") # python#7980 if WINDOWS: os.system("rem") # enables colors init_E(E) f = '\033[36mcopyparty v{} "\033[35m{}\033[36m" ({})\n{}\033[0;36m\n sqlite {} | jinja {} | pyftpd {} | tftp {} | miko {}\n\033[0m' f = f.format( S_VERSION, CODENAME, S_BUILD_DT, PY_DESC.replace("[", "\033[90m["), SQLITE_VER, JINJA_VER, PYFTPD_VER, PARTFTPY_VER, MIKO_VER, ) lprint(f) if "--version" in argv: sys.exit(0) if "--license" in argv: showlic() sys.exit(0) if "--mimes" in argv: print("\n".join("%8s %s" % (k, v) for k, v in sorted(MIMES.items()))) sys.exit(0) if EXE: print("pybin: {}\n".format(pybin), end="") for n, zs in enumerate(argv): if zs.startswith("--sfx-tpoke="): Daemon(sfx_tpoke, "sfx-tpoke", (zs.split("=", 1)[1],)) argv.pop(n) break ensure_locale() ensure_webdeps() argv = expand_cfg(argv) deprecated: list[tuple[str, str]] = [ ("--salt", "--warksalt"), ("--hdr-au-usr", "--idp-h-usr"), ("--idp-h-sep", "--idp-gsep"), ("--th-no-crop", "--th-crop=n"), ("--never-symlink", "--hardlink-only"), ] for dk, nk in deprecated: idx = -1 ov = "" for n, k in enumerate(argv): if k == dk or k.startswith(dk + "="): idx = n if "=" in k: ov = "=" + k.split("=", 1)[1] if idx < 0: continue msg = "\033[1;31mWARNING:\033[0;1m\n {} \033[0;33mwas replaced with\033[0;1m {} \033[0;33mand will be removed\n\033[0m" lprint(msg.format(dk, nk)) argv[idx] = nk + ov time.sleep(2) da = len(argv) == 1 and not CFG_DEF try: if da: argv.extend(["--qr"]) if ANYWIN or not os.geteuid(): # win10 allows symlinks if admin; can be unexpected argv.extend(["-p80,443,3923", "--ign-ebind"]) except: pass if da: t = "no arguments provided; will use {}\n" lprint(t.format(" ".join(argv[1:]))) nc = 1024 try: import resource _, hard = resource.getrlimit(resource.RLIMIT_NOFILE) if hard > 0: # -1 == infinite nc = min(nc, int(hard / 4)) except: nc = 486 # mdns/ssdp restart headroom; select() maxfd is 512 on windows retry = 0 for fmtr in [RiceFormatter, RiceFormatter, Dodge11874, BasicDodge11874]: try: al = run_argparse(argv, fmtr, retry, nc) dal = run_argparse([], fmtr, retry, nc, False) break except SystemExit: raise except: retry += 1 t = "WARNING: due to limitations in your terminal and/or OS, the helptext cannot be displayed correctly. Will show a simplified version due to the following error:\n[ %s ]:\n%s\n" lprint(t % (fmtr, min_ex())) try: assert al # type: ignore assert dal # type: ignore al.E = E # __init__ is not shared when oxidized except: sys.exit(1) quotecheck(al) if al.chdir: os.chdir(al.chdir) if al.ansi: al.no_ansi = False elif not al.no_ansi: al.ansi = VT100 if WINDOWS and not al.keep_qem and not al.ah_cli: try: disable_quickedit() except: lprint("\nfailed to disable quick-edit-mode:\n" + min_ex() + "\n") if not al.ansi: al.wintitle = "" # propagate implications for k1, k2 in IMPLICATIONS: if getattr(al, k1, None): setattr(al, k2, True) # propagate unplications for k1, k2 in UNPLICATIONS: if getattr(al, k1): setattr(al, k2, False) protos = "ftp tftp sftp smb".split() opts = ["%s_i" % (zs,) for zs in protos] for opt in opts: if getattr(al, opt) == "-i": setattr(al, opt, al.i) for opt in ["i"] + opts: zs = getattr(al, opt) if not HAVE_IPV6 and zs == "::": zs = "0.0.0.0" setattr(al, opt, [x.strip() for x in zs.split(",")]) try: if "-" in al.p: lo, hi = [int(x) for x in al.p.split("-")] al.p = list(range(lo, hi + 1)) else: al.p = [int(x) for x in al.p.split(",")] except: raise Exception("invalid value for -p") for arg, kname, okays in [["--u2sort", "u2sort", "s n fs fn"]]: val = unicode(getattr(al, kname)) if val not in okays.split(): zs = "argument {} cannot be '{}'; try one of these: {}" raise Exception(zs.format(arg, val, okays)) if not al.qrs and [k for k in argv if k.startswith("--qr")]: al.qr = True if al.ihead: al.ihead = [x.lower() for x in al.ihead] if al.ohead: al.ohead = [x.lower() for x in al.ohead] if HAVE_SSL: if al.ssl_ver: configure_ssl_ver(al) if al.ciphers: configure_ssl_ciphers(al) else: warn("ssl module does not exist; cannot enable https") al.http_only = True if PY2 and WINDOWS and al.e2d: warn( "windows py2 cannot do unicode filenames with -e2d\n" + " (if you crash with codec errors then that is why)" ) if PY2 and al.smb: print("error: python2 cannot --smb") return if not PY36: al.no_scandir = True if not hasattr(os, "sendfile"): al.no_sendfile = True if not hasattr(select, "poll"): al.no_poll = True # signal.signal(signal.SIGINT, sighandler) SvcHub(al, dal, argv, "".join(printed)).run() if __name__ == "__main__": main()
--- +++ @@ -110,6 +110,10 @@ super(RiceFormatter, self).__init__(*args, **kwargs) def _get_help_string(self, action: argparse.Action) -> str: + """ + same as ArgumentDefaultsHelpFormatter(HelpFormatter) + except the help += [...] line now has colors + """ fmt = "\033[36m (default: \033[35m%(default)s\033[36m)\033[0m" if not VT100: fmt = " (default: %(default)s)" @@ -127,6 +131,7 @@ return ret # type: ignore def _fill_text(self, text: str, width: int, indent: str) -> str: + """same as RawDescriptionHelpFormatter(HelpFormatter)""" return "".join(indent + line + "\n" for line in text.splitlines()) def __add_whitespace(self, idx: int, iWSpace: int, text: str) -> str: @@ -2262,4 +2267,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/__main__.py
Help me write clear docstrings
# coding: utf-8 from __future__ import print_function, unicode_literals import threading import time import traceback import queue from .__init__ import CORES, TYPE_CHECKING from .broker_mpw import MpWorker from .broker_util import ExceptionalQueue, NotExQueue, try_exec from .util import Daemon, mp if TYPE_CHECKING: from .svchub import SvcHub if True: # pylint: disable=using-constant-test from typing import Any, Union class MProcess(mp.Process): def __init__( self, q_pend: queue.Queue[tuple[int, str, list[Any]]], q_yield: queue.Queue[tuple[int, str, list[Any]]], target: Any, args: Any, ) -> None: super(MProcess, self).__init__(target=target, args=args) self.q_pend = q_pend self.q_yield = q_yield class BrokerMp(object): def __init__(self, hub: "SvcHub") -> None: self.hub = hub self.log = hub.log self.args = hub.args self.procs = [] self.mutex = threading.Lock() self.retpend: dict[int, Any] = {} self.retpend_mutex = threading.Lock() self.num_workers = self.args.j or CORES self.log("broker", "booting {} subprocesses".format(self.num_workers)) for n in range(1, self.num_workers + 1): q_pend: queue.Queue[tuple[int, str, list[Any]]] = mp.Queue(1) # type: ignore q_yield: queue.Queue[tuple[int, str, list[Any]]] = mp.Queue(64) # type: ignore proc = MProcess(q_pend, q_yield, MpWorker, (q_pend, q_yield, self.args, n)) Daemon(self.collector, "mp-sink-{}".format(n), (proc,)) self.procs.append(proc) proc.start() Daemon(self.periodic, "mp-periodic") def shutdown(self) -> None: self.log("broker", "shutting down") for n, proc in enumerate(self.procs): name = "mp-shut-%d-%d" % (n, len(self.procs)) Daemon(proc.q_pend.put, name, ((0, "shutdown", []),)) with self.mutex: procs = self.procs self.procs = [] while procs: if procs[-1].is_alive(): time.sleep(0.05) continue procs.pop() def reload(self) -> None: self.log("broker", "reloading") for _, proc in enumerate(self.procs): proc.q_pend.put((0, "reload", [])) def reload_sessions(self) -> None: for _, proc in enumerate(self.procs): proc.q_pend.put((0, "reload_sessions", [])) def collector(self, proc: MProcess) -> None: while True: msg = proc.q_yield.get() retq_id, dest, args = msg if dest == "log": self.log(*args) elif dest == "retq": with self.retpend_mutex: retq = self.retpend.pop(retq_id) retq.put(args[0]) else: # new ipc invoking managed service in hub try: obj = self.hub for node in dest.split("."): obj = getattr(obj, node) # TODO will deadlock if dest performs another ipc rv = try_exec(retq_id, obj, *args) except: rv = ["exception", "stack", traceback.format_exc()] if retq_id: proc.q_pend.put((retq_id, "retq", rv)) def ask(self, dest: str, *args: Any) -> Union[ExceptionalQueue, NotExQueue]: # new non-ipc invoking managed service in hub obj = self.hub for node in dest.split("."): obj = getattr(obj, node) rv = try_exec(True, obj, *args) retq = ExceptionalQueue(1) retq.put(rv) return retq def wask(self, dest: str, *args: Any) -> list[Union[ExceptionalQueue, NotExQueue]]: # call from hub to workers ret = [] for p in self.procs: retq = ExceptionalQueue(1) retq_id = id(retq) with self.retpend_mutex: self.retpend[retq_id] = retq p.q_pend.put((retq_id, dest, list(args))) ret.append(retq) return ret def say(self, dest: str, *args: Any) -> None: if dest == "httpsrv.listen": for p in self.procs: p.q_pend.put((0, dest, [args[0], len(self.procs)])) elif dest == "httpsrv.set_netdevs": for p in self.procs: p.q_pend.put((0, dest, list(args))) elif dest == "cb_httpsrv_up": self.hub.cb_httpsrv_up() elif dest == "httpsrv.set_bad_ver": for p in self.procs: p.q_pend.put((0, dest, list(args))) else: raise Exception("what is " + str(dest)) def periodic(self) -> None: while True: time.sleep(1) tdli = {} tdls = {} qs = self.wask("httpsrv.read_dls") for q in qs: qr = q.get() dli, dls = qr tdli.update(dli) tdls.update(dls) tdl = (tdli, tdls) for p in self.procs: p.q_pend.put((0, "httpsrv.write_dls", tdl))
--- +++ @@ -33,6 +33,7 @@ class BrokerMp(object): + """external api; manages MpWorkers""" def __init__(self, hub: "SvcHub") -> None: self.hub = hub @@ -85,6 +86,7 @@ proc.q_pend.put((0, "reload_sessions", [])) def collector(self, proc: MProcess) -> None: + """receive message from hub in other process""" while True: msg = proc.q_yield.get() retq_id, dest, args = msg @@ -139,6 +141,11 @@ return ret def say(self, dest: str, *args: Any) -> None: + """ + send message to non-hub component in other process, + returns a Queue object which eventually contains the response if want_retval + (not-impl here since nothing uses it yet) + """ if dest == "httpsrv.listen": for p in self.procs: p.q_pend.put((0, dest, [args[0], len(self.procs)])) @@ -171,4 +178,4 @@ tdls.update(dls) tdl = (tdli, tdls) for p in self.procs: - p.q_pend.put((0, "httpsrv.write_dls", tdl))+ p.q_pend.put((0, "httpsrv.write_dls", tdl))
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/broker_mp.py
Document this code for team use
# coding: utf-8 from __future__ import print_function, unicode_literals import argparse from queue import Queue from .__init__ import TYPE_CHECKING from .authsrv import AuthSrv from .util import HMaccas, Pebkac if True: # pylint: disable=using-constant-test from typing import Any, Optional, Union from .util import RootLogger if TYPE_CHECKING: from .httpsrv import HttpSrv class ExceptionalQueue(Queue, object): def get(self, block: bool = True, timeout: Optional[float] = None) -> Any: rv = super(ExceptionalQueue, self).get(block, timeout) if isinstance(rv, list): if rv[0] == "exception": if rv[1] == "pebkac": raise Pebkac(*rv[2:]) else: raise rv[2] return rv class NotExQueue(object): def __init__(self, rv: Any) -> None: self.rv = rv def get(self) -> Any: return self.rv class BrokerCli(object): log: "RootLogger" args: argparse.Namespace asrv: AuthSrv httpsrv: "HttpSrv" iphash: HMaccas def __init__(self) -> None: pass def ask(self, dest: str, *args: Any) -> Union[ExceptionalQueue, NotExQueue]: return ExceptionalQueue(1) def say(self, dest: str, *args: Any) -> None: pass def try_exec(want_retval: Union[bool, int], func: Any, *args: list[Any]) -> Any: try: return func(*args) except Pebkac as ex: if not want_retval: raise return ["exception", "pebkac", ex.code, str(ex)] except Exception as ex: if not want_retval: raise return ["exception", "stack", ex]
--- +++ @@ -33,6 +33,9 @@ class NotExQueue(object): + """ + BrokerThr uses this instead of ExceptionalQueue; 7x faster + """ def __init__(self, rv: Any) -> None: self.rv = rv @@ -42,6 +45,10 @@ class BrokerCli(object): + """ + helps mypy understand httpsrv.broker but still fails a few levels deeper, + for example resolving httpconn.* in httpcli -- see lines tagged #mypy404 + """ log: "RootLogger" args: argparse.Namespace @@ -73,4 +80,4 @@ if not want_retval: raise - return ["exception", "stack", ex]+ return ["exception", "stack", ex]
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/broker_util.py
Create docstrings for each class method
#!/usr/bin/env python3 from __future__ import print_function, unicode_literals S_VERSION = "2.19" S_BUILD_DT = "2026-01-18" """ u2c.py: upload to copyparty 2021, ed <irc.rizon.net>, MIT-Licensed https://github.com/9001/copyparty/blob/hovudstraum/bin/u2c.py - dependencies: no - supports python 2.6, 2.7, and 3.3 through 3.14 - if something breaks just try again and it'll autoresume """ import atexit import base64 import binascii import datetime import hashlib import json import math import os import platform import re import signal import socket import stat import sys import threading import time EXE = bool(getattr(sys, "frozen", False)) try: import argparse except: m = "\n ERROR: need 'argparse'; download it here:\n https://github.com/ThomasWaldmann/argparse/raw/master/argparse.py\n" print(m) raise PY2 = sys.version_info < (3,) PY27 = sys.version_info > (2, 7) and PY2 PY37 = sys.version_info > (3, 7) if PY2: import httplib as http_client from Queue import Queue from urllib import quote, unquote from urlparse import urlsplit, urlunsplit sys.dont_write_bytecode = True bytes = str files_decoder = lambda s: unicode(s, "utf8") else: from urllib.parse import quote_from_bytes as quote from urllib.parse import unquote_to_bytes as unquote from urllib.parse import urlsplit, urlunsplit import http.client as http_client from queue import Queue unicode = str files_decoder = unicode WTF8 = "replace" if PY2 else "surrogateescape" VT100 = platform.system() != "Windows" try: UTC = datetime.timezone.utc except: TD_ZERO = datetime.timedelta(0) class _UTC(datetime.tzinfo): def utcoffset(self, dt): return TD_ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return TD_ZERO UTC = _UTC() try: _b64etl = bytes.maketrans(b"+/", b"-_") def ub64enc(bs): x = binascii.b2a_base64(bs, newline=False) return x.translate(_b64etl) ub64enc(b"a") except: ub64enc = base64.urlsafe_b64encode class Fatal(Exception): pass class Daemon(threading.Thread): def __init__(self, target, name=None, a=None): threading.Thread.__init__(self, name=name) self.a = a or () self.fun = target self.daemon = True self.start() def run(self): try: signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGINT, signal.SIGTERM]) except: pass self.fun(*self.a) class HSQueue(Queue): def _init(self, maxsize): from collections import deque self.q = deque() def _qsize(self): return len(self.q) def _put(self, item): if item and item.nhs: self.q.appendleft(item) else: self.q.append(item) def _get(self): return self.q.popleft() class HCli(object): def __init__(self, ar): self.ar = ar url = urlsplit(ar.url) tls = url.scheme.lower() == "https" try: addr, port = url.netloc.split(":") except: addr = url.netloc port = 443 if tls else 80 self.addr = addr self.port = int(port) self.tls = tls self.verify = ar.te or not ar.td self.conns = [] self.hconns = [] if tls: import ssl if not self.verify: self.ctx = ssl._create_unverified_context() elif self.verify is True: self.ctx = None else: self.ctx = ssl.create_default_context(cafile=self.verify) self.ctx.check_hostname = ar.teh self.base_hdrs = { "Accept": "*/*", "Connection": "keep-alive", "Host": url.netloc, "Origin": self.ar.burl, "User-Agent": "u2c/%s" % (S_VERSION,), } def _connect(self, timeout): args = {} if PY37: args["blocksize"] = 1048576 if not self.tls: C = http_client.HTTPConnection else: C = http_client.HTTPSConnection if self.ctx: args = {"context": self.ctx} return C(self.addr, self.port, timeout=timeout, **args) def req(self, meth, vpath, hdrs, body=None, ctype=None): now = time.time() hdrs.update(self.base_hdrs) if self.ar.a: hdrs["PW"] = self.ar.a if self.ar.ba: hdrs["Authorization"] = self.ar.ba if ctype: hdrs["Content-Type"] = ctype if meth == "POST" and CLEN not in hdrs: hdrs[CLEN] = ( 0 if not body else body.len if hasattr(body, "len") else len(body) ) # large timeout for handshakes (safededup) conns = self.hconns if ctype == MJ else self.conns while conns and self.ar.cxp < now - conns[0][0]: conns.pop(0)[1].close() c = conns.pop()[1] if conns else self._connect(999 if ctype == MJ else 128) try: c.request(meth, vpath, body, hdrs) if PY27: rsp = c.getresponse(buffering=True) else: rsp = c.getresponse() data = rsp.read() conns.append((time.time(), c)) return rsp.status, data.decode("utf-8") except http_client.BadStatusLine: if self.ar.cxp > 4: t = "\nWARNING: --cxp probably too high; reducing from %d to 4" print(t % (self.ar.cxp,)) self.ar.cxp = 4 c.close() raise except: c.close() raise MJ = "application/json" MO = "application/octet-stream" MM = "application/x-www-form-urlencoded" CLEN = "Content-Length" web = None # type: HCli links = [] # type: list[str] linkmtx = threading.Lock() linkfile = None class File(object): def __init__(self, top, rel, size, lmod): self.top = top # type: bytes self.rel = rel.replace(b"\\", b"/") # type: bytes self.size = size # type: int self.lmod = lmod # type: float self.abs = os.path.join(top, rel) # type: bytes self.name = self.rel.split(b"/")[-1].decode("utf-8", WTF8) # type: str # set by get_hashlist self.cids = [] # type: list[tuple[str, int, int]] # [ hash, ofs, sz ] self.kchunks = {} # type: dict[str, tuple[int, int]] # hash: [ ofs, sz ] self.t_hash = 0.0 # type: float # set by handshake self.recheck = False # duplicate; redo handshake after all files done self.ucids = [] # type: list[str] # chunks which need to be uploaded self.wark = "" # type: str self.url = "" # type: str self.nhs = 0 # type: int # set by upload self.t0_up = 0.0 # type: float self.t1_up = 0.0 # type: float self.nojoin = 0 # type: int self.up_b = 0 # type: int self.up_c = 0 # type: int self.cd = 0 # type: int class FileSlice(object): def __init__(self, file, cids): # type: (File, str) -> None self.file = file self.cids = cids self.car, tlen = file.kchunks[cids[0]] for cid in cids[1:]: ofs, clen = file.kchunks[cid] if ofs != self.car + tlen: raise Exception(9) tlen += clen self.len = self.tlen = tlen self.cdr = self.car + self.len self.ofs = 0 # type: int self.f = None self.seek = self._seek0 self.read = self._read0 def subchunk(self, maxsz, nth): if self.tlen <= maxsz: return -1 if not nth: self.car0 = self.car self.cdr0 = self.cdr self.car = self.car0 + maxsz * nth if self.car >= self.cdr0: return -2 self.cdr = self.car + min(self.cdr0 - self.car, maxsz) self.len = self.cdr - self.car self.seek(0) return nth def unsub(self): self.car = self.car0 self.cdr = self.cdr0 self.len = self.tlen def _open(self): self.seek = self._seek self.read = self._read self.f = open(self.file.abs, "rb", 512 * 1024) self.f.seek(self.car) # https://stackoverflow.com/questions/4359495/what-is-exactly-a-file-like-object-in-python # IOBase, RawIOBase, BufferedIOBase funs = "close closed __enter__ __exit__ __iter__ isatty __next__ readable seekable writable" try: for fun in funs.split(): setattr(self, fun, getattr(self.f, fun)) except: pass # py27 probably def close(self, *a, **ka): return # until _open def tell(self): return self.ofs def _seek(self, ofs, wh=0): assert self.f # !rm if wh == 1: ofs = self.ofs + ofs elif wh == 2: ofs = self.len + ofs # provided ofs is negative if ofs < 0: ofs = 0 elif ofs >= self.len: ofs = self.len - 1 self.ofs = ofs self.f.seek(self.car + ofs) def _read(self, sz): assert self.f # !rm sz = min(sz, self.len - self.ofs) ret = self.f.read(sz) self.ofs += len(ret) return ret def _seek0(self, ofs, wh=0): self._open() return self.seek(ofs, wh) def _read0(self, sz): self._open() return self.read(sz) class MTHash(object): def __init__(self, cores): self.f = None self.sz = 0 self.csz = 0 self.omutex = threading.Lock() self.imutex = threading.Lock() self.work_q = Queue() self.done_q = Queue() self.thrs = [] for _ in range(cores): self.thrs.append(Daemon(self.worker)) def hash(self, f, fsz, chunksz, pcb=None, pcb_opaque=None): with self.omutex: self.f = f self.sz = fsz self.csz = chunksz chunks = {} nchunks = int(math.ceil(fsz / chunksz)) for nch in range(nchunks): self.work_q.put(nch) ex = "" for nch in range(nchunks): qe = self.done_q.get() try: nch, dig, ofs, csz = qe chunks[nch] = [dig, ofs, csz] except: ex = ex or qe if pcb: pcb(pcb_opaque, chunksz * nch) if ex: raise Exception(ex) ret = [] for n in range(nchunks): ret.append(chunks[n]) self.f = None self.csz = 0 self.sz = 0 return ret def worker(self): while True: ofs = self.work_q.get() try: v = self.hash_at(ofs) except Exception as ex: v = str(ex) self.done_q.put(v) def hash_at(self, nch): f = self.f assert f ofs = ofs0 = nch * self.csz hashobj = hashlib.sha512() chunk_sz = chunk_rem = min(self.csz, self.sz - ofs) while chunk_rem > 0: with self.imutex: f.seek(ofs) buf = f.read(min(chunk_rem, 1024 * 1024 * 12)) if not buf: raise Exception("EOF at " + str(ofs)) hashobj.update(buf) chunk_rem -= len(buf) ofs += len(buf) digest = ub64enc(hashobj.digest()[:33]).decode("utf-8") return nch, digest, ofs0, chunk_sz _print = print def safe_print(*a, **ka): ka["end"] = "" zs = " ".join([unicode(x) for x in a]) _print(zs + "\n", **ka) def eprint(*a, **ka): ka["file"] = sys.stderr ka["end"] = "" if not PY2: ka["flush"] = True _print(*a, **ka) if PY2 or not VT100: sys.stderr.flush() def flushing_print(*a, **ka): try: safe_print(*a, **ka) except: v = " ".join(str(x) for x in a) v = v.encode("ascii", "replace").decode("ascii") safe_print(v, **ka) if "flush" not in ka: sys.stdout.flush() print = safe_print if VT100 else flushing_print def termsize(): try: w, h = os.get_terminal_size() return w, h except: pass env = os.environ def ioctl_GWINSZ(fd): try: import fcntl import struct import termios r = struct.unpack(b"hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, b"AAAA")) return r[::-1] except: return None cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass try: return cr or (int(env["COLUMNS"]), int(env["LINES"])) except: return 80, 25 class CTermsize(object): def __init__(self): self.ev = False self.margin = None self.g = None self.w, self.h = termsize() try: signal.signal(signal.SIGWINCH, self.ev_sig) except: return Daemon(self.worker) def worker(self): while True: time.sleep(0.5) if not self.ev: continue self.ev = False self.w, self.h = termsize() if self.margin is not None: self.scroll_region(self.margin) def ev_sig(self, *a, **ka): self.ev = True def scroll_region(self, margin): self.margin = margin if margin is None: self.g = None eprint("\033[s\033[r\033[u") else: self.g = 1 + self.h - margin t = "%s\033[%dA" % ("\n" * margin, margin) eprint("%s\033[s\033[1;%dr\033[u" % (t, self.g - 1)) ss = CTermsize() def undns(url): usp = urlsplit(url) hn = usp.hostname gai = None eprint("resolving host [%s] ..." % (hn,)) try: gai = socket.getaddrinfo(hn, None) hn = gai[0][4][0] except KeyboardInterrupt: raise except: t = "\n\033[31mfailed to resolve upload destination host;\033[0m\ngai=%r\n" eprint(t % (gai,)) raise if usp.port: hn = "%s:%s" % (hn, usp.port) if usp.username or usp.password: hn = "%s:%s@%s" % (usp.username, usp.password, hn) usp = usp._replace(netloc=hn) url = urlunsplit(usp) eprint(" %s\n" % (url,)) return url def _scd(err, top): top_ = os.path.join(top, b"") with os.scandir(top) as dh: for fh in dh: abspath = top_ + fh.name try: yield [abspath, fh.stat()] except Exception as ex: err.append((abspath, str(ex))) def _lsd(err, top): top_ = os.path.join(top, b"") for name in os.listdir(top): abspath = top_ + name try: yield [abspath, os.stat(abspath)] except Exception as ex: err.append((abspath, str(ex))) if hasattr(os, "scandir") and sys.version_info > (3, 6): statdir = _scd else: statdir = _lsd def walkdir(err, top, excl, seen): atop = os.path.abspath(os.path.realpath(top)) if atop in seen: err.append((top, "recursive-symlink")) return seen = seen[:] + [atop] for ap, inf in sorted(statdir(err, top)): if excl.match(ap): continue if stat.S_ISDIR(inf.st_mode): yield ap, inf try: for x in walkdir(err, ap, excl, seen): yield x except Exception as ex: err.append((ap, str(ex))) elif stat.S_ISREG(inf.st_mode): yield ap, inf else: err.append((ap, "irregular filetype 0%o" % (inf.st_mode,))) def walkdirs(err, tops, excl): sep = "{0}".format(os.sep).encode("ascii") if not VT100: excl = excl.replace("/", r"\\") za = [] for td in tops: try: ap = os.path.abspath(os.path.realpath(td)) if td[-1:] in (b"\\", b"/"): ap += sep except: # maybe cpython #88013 (ok) ap = td za.append(ap) za = [x if x.startswith(b"\\\\") else b"\\\\?\\" + x for x in za] za = [x.replace(b"/", b"\\") for x in za] tops = za ptn = re.compile(excl.encode("utf-8") or b"\n", re.I) for top in tops: isdir = os.path.isdir(top) if top[-1:] == sep: stop = top.rstrip(sep) yield stop, b"", os.stat(stop) else: stop, dn = os.path.split(top) if isdir: yield stop, dn, os.stat(stop) if isdir: for ap, inf in walkdir(err, top, ptn, []): yield stop, ap[len(stop) :].lstrip(sep), inf else: d, n = top.rsplit(sep, 1) yield d or b"/", n, os.stat(top) # mostly from copyparty/util.py def quotep(btxt): # type: (bytes) -> bytes quot1 = quote(btxt, safe=b"/") if not PY2: quot1 = quot1.encode("ascii") return quot1.replace(b" ", b"%20") # type: ignore # from copyparty/util.py def humansize(sz, terse=False): for unit in ["B", "KiB", "MiB", "GiB", "TiB"]: if sz < 1024: break sz /= 1024.0 ret = " ".join([str(sz)[:4].rstrip("."), unit]) if not terse: return ret return ret.replace("iB", "").replace(" ", "") # from copyparty/up2k.py def up2k_chunksize(filesize): chunksize = 1024 * 1024 stepsize = 512 * 1024 while True: for mul in [1, 2]: nchunks = math.ceil(filesize * 1.0 / chunksize) if nchunks <= 256 or (chunksize >= 32 * 1024 * 1024 and nchunks <= 4096): return chunksize chunksize += stepsize stepsize *= mul # mostly from copyparty/up2k.py def get_hashlist(file, pcb, mth): # type: (File, Any, Any) -> None chunk_sz = up2k_chunksize(file.size) file_rem = file.size file_ofs = 0 ret = [] with open(file.abs, "rb", 512 * 1024) as f: t0 = time.time() if mth and file.size >= 1024 * 512: ret = mth.hash(f, file.size, chunk_sz, pcb, file) file_rem = 0 while file_rem > 0: # same as `hash_at` except for `imutex` / bufsz hashobj = hashlib.sha512() chunk_sz = chunk_rem = min(chunk_sz, file_rem) while chunk_rem > 0: buf = f.read(min(chunk_rem, 64 * 1024)) if not buf: raise Exception("EOF at " + str(f.tell())) hashobj.update(buf) chunk_rem -= len(buf) digest = ub64enc(hashobj.digest()[:33]).decode("utf-8") ret.append([digest, file_ofs, chunk_sz]) file_ofs += chunk_sz file_rem -= chunk_sz if pcb: pcb(file, file_ofs) file.t_hash = time.time() - t0 file.cids = ret file.kchunks = {} for k, v1, v2 in ret: if k not in file.kchunks: file.kchunks[k] = [v1, v2] def printlink(ar, purl, name, fk): if not name: url = purl # srch else: name = quotep(name.encode("utf-8", WTF8)).decode("utf-8") if fk: url = "%s%s?k=%s" % (purl, name, fk) else: url = "%s%s" % (purl, name) url = "%s/%s" % (ar.burl, url.lstrip("/")) with linkmtx: if ar.u: links.append(url) if ar.ud: print(url) if linkfile: zs = "%s\n" % (url,) zb = zs.encode("utf-8", "replace") linkfile.write(zb) def handshake(ar, file, search): # type: (argparse.Namespace, File, bool) -> tuple[list[str], bool] req = { "hash": [x[0] for x in file.cids], "name": file.name, "lmod": file.lmod, "size": file.size, } if search: req["srch"] = 1 else: if ar.touch: req["umod"] = True if ar.owo: req["replace"] = "mt" elif ar.ow: req["replace"] = True file.recheck = False if file.url: url = file.url else: if b"/" in file.rel: url = quotep(file.rel.rsplit(b"/", 1)[0]).decode("utf-8") else: url = "" url = ar.vtop + url t0 = time.time() tmax = t0 + ar.t_hs while True: sc = 600 txt = "" t1 = time.time() if t1 >= tmax: print("\nERROR: server offline for longer than --t-hs; giving up") raise Fatal() try: zs = json.dumps(req, separators=(",\n", ": ")) sc, txt = web.req("POST", url, {}, zs.encode("utf-8"), MJ) if sc < 400: break raise Exception("http %d: %s" % (sc, txt)) except Exception as ex: em = str(ex).split("SSLError(")[-1].split("\nURL: ")[0].strip() if ( sc == 422 or "<pre>partial upload exists at a different" in txt or "<pre>source file busy; please try again" in txt ): file.recheck = True return [], False elif sc == 409 or "<pre>upload rejected, file already exists" in txt: return [], False elif sc == 403 or sc == 401: print("\nERROR: login required, or wrong password:\n%s" % (txt,)) raise Fatal() t = "handshake failed, retrying: %s\n t0=%.3f t1=%.3f t2=%.3f td1=%.3f td2=%.3f\n %s\n\n" now = time.time() eprint(t % (file.name, t0, t1, now, now - t0, now - t1, em)) time.sleep(ar.cd) try: r = json.loads(txt) except: raise Exception(txt) if search: if ar.uon and r["hits"]: printlink(ar, r["hits"][0]["rp"], "", "") return r["hits"], False file.url = quotep(r["purl"].encode("utf-8", WTF8)).decode("utf-8") file.name = r["name"] file.wark = r["wark"] if ar.uon and not r["hash"]: printlink(ar, file.url, r["name"], r.get("fk")) return r["hash"], r["sprs"] def upload(fsl, stats, maxsz): # type: (FileSlice, str, int) -> None ctxt = fsl.cids[0] if len(fsl.cids) > 1: n = 192 // len(fsl.cids) n = 9 if n > 9 else 2 if n < 2 else n zsl = [zs[:n] for zs in fsl.cids[1:]] ctxt += ",%d,%s" % (n, "".join(zsl)) headers = { "X-Up2k-Hash": ctxt, "X-Up2k-Wark": fsl.file.wark, } if stats: headers["X-Up2k-Stat"] = stats nsub = 0 try: while nsub != -1: nsub = fsl.subchunk(maxsz, nsub) if nsub == -2: return if nsub >= 0: headers["X-Up2k-Subc"] = str(maxsz * nsub) headers.pop(CLEN, None) nsub += 1 sc, txt = web.req("POST", fsl.file.url, headers, fsl, MO) if sc == 400: if ( "already being written" in txt or "already got that" in txt or "only sibling chunks" in txt ): fsl.file.nojoin = 1 if sc >= 400: raise Exception("http %s: %s" % (sc, txt)) finally: if fsl.f: fsl.f.close() if nsub != -1: fsl.unsub() class Ctl(object): def _scan(self): ar = self.ar eprint("\nscanning %d locations\n" % (len(ar.files),)) nfiles = 0 nbytes = 0 err = [] for _, _, inf in walkdirs(err, ar.files, ar.x): if stat.S_ISDIR(inf.st_mode): continue nfiles += 1 nbytes += inf.st_size if err: eprint("\n# failed to access %d paths:\n" % (len(err),)) for ap, msg in err: if ar.v: eprint("%s\n `-%s\n\n" % (ap.decode("utf-8", "replace"), msg)) else: eprint(ap.decode("utf-8", "replace") + "\n") eprint("^ failed to access those %d paths ^\n\n" % (len(err),)) if not ar.v: eprint("hint: set -v for detailed error messages\n") if not ar.ok: eprint("hint: aborting because --ok is not set\n") return eprint("found %d files, %s\n\n" % (nfiles, humansize(nbytes))) return nfiles, nbytes def __init__(self, ar, stats=None): self.ok = False self.panik = 0 self.errs = 0 self.ar = ar self.stats = stats or self._scan() if not self.stats: return self.nfiles, self.nbytes = self.stats self.filegen = walkdirs([], ar.files, ar.x) self.recheck = [] # type: list[File] self.last_file = None if ar.safe: self._safe() else: self.at_hash = 0.0 self.at_up = 0.0 self.at_upr = 0.0 self.hash_f = 0 self.hash_c = 0 self.hash_b = 0 self.up_f = 0 self.up_c = 0 self.up_b = 0 # num bytes handled self.up_br = 0 # num bytes actually transferred self.uploader_busy = 0 self.serialized = False self.t0 = time.time() self.t0_up = None self.spd = None self.eta = "99:99:99" self.mutex = threading.Lock() self.exit_cond = threading.Condition() self.uploader_alive = ar.j self.handshaker_alive = ar.j self.q_handshake = HSQueue() # type: Queue[File] self.q_upload = Queue() # type: Queue[FileSlice] self.st_hash = [None, "(idle, starting...)"] # type: tuple[File, int] self.st_up = [None, "(idle, starting...)"] # type: tuple[File, int] self.mth = MTHash(ar.J) if ar.J > 1 else None self._fancy() file = self.last_file if self.up_br and file: zs = quotep(file.name.encode("utf-8", WTF8)) web.req("POST", file.url, {}, b"msg=upload-queue-empty;" + zs, MM) self.ok = not self.errs def _safe(self): search = self.ar.s nf = 0 for top, rel, inf in self.filegen: if stat.S_ISDIR(inf.st_mode) or not rel: continue nf += 1 file = File(top, rel, inf.st_size, inf.st_mtime) upath = file.abs.decode("utf-8", "replace") print("%d %s\n hash..." % (self.nfiles - nf, upath)) get_hashlist(file, None, None) while True: print(" hs...") try: hs, _ = handshake(self.ar, file, search) except Fatal: sys.exit(1) if search: if hs: for hit in hs: print(" found: %s/%s" % (self.ar.burl, hit["rp"])) else: print(" NOT found") break file.ucids = hs if not hs: break print("%d %s" % (self.nfiles - nf, upath)) ncs = len(hs) for nc, cid in enumerate(hs): print(" %d up %s" % (ncs - nc, cid)) stats = "%d/0/0/%d" % (nf, self.nfiles - nf) fslice = FileSlice(file, [cid]) upload(fslice, stats, self.ar.szm) print(" ok!") if file.recheck: self.recheck.append(file) if not self.recheck: return eprint("finalizing %d duplicate files\n" % (len(self.recheck),)) for file in self.recheck: handshake(self.ar, file, False) def _fancy(self): atexit.register(self.cleanup_vt100) if VT100 and not self.ar.ns: ss.scroll_region(3) Daemon(self.hasher) for _ in range(self.ar.j): Daemon(self.handshaker) Daemon(self.uploader) last_sp = -1 while True: with self.exit_cond: self.exit_cond.wait(0.07) if self.panik: sys.exit(1) with self.mutex: if not self.handshaker_alive and not self.uploader_alive: break st_hash = self.st_hash[:] st_up = self.st_up[:] if VT100 and not self.ar.ns: maxlen = ss.w - len(str(self.nfiles)) - 14 txt = "\033[s\033[%dH" % (ss.g,) for y, k, st, f in [ [0, "hash", st_hash, self.hash_f], [1, "send", st_up, self.up_f], ]: txt += "\033[%dH%s:" % (ss.g + y, k) file, arg = st if not file: txt += " %s\033[K" % (arg,) else: if y: p = 100 * file.up_b / file.size else: p = 100 * arg / file.size name = file.abs.decode("utf-8", "replace")[-maxlen:] if "/" in name: name = "\033[36m%s\033[0m/%s" % tuple(name.rsplit("/", 1)) txt += "%6.1f%% %d %s\033[K" % (p, self.nfiles - f, name) txt += "\033[%dH " % (ss.g + 2,) else: txt = " " if not VT100: # OSC9;4 (taskbar-progress) sp = int(self.up_b * 100 / self.nbytes) or 1 if last_sp != sp: last_sp = sp txt += "\033]9;4;1;%d\033\\" % (sp,) if not self.up_br: spd = self.hash_b / ((time.time() - self.t0) or 1) eta = (self.nbytes - self.hash_b) / (spd or 1) else: spd = self.up_br / ((time.time() - self.t0_up) or 1) spd = self.spd = (self.spd or spd) * 0.9 + spd * 0.1 eta = (self.nbytes - self.up_b) / (spd or 1) spd = humansize(spd) self.eta = str(datetime.timedelta(seconds=int(eta))) if eta > 2591999: self.eta = self.eta.split(",")[0] # truncate HH:MM:SS sleft = humansize(self.nbytes - self.up_b) nleft = self.nfiles - self.up_f tail = "\033[K\033[u" if VT100 and not self.ar.ns else "\r" t = "%s eta @ %s/s, %s, %d# left" % (self.eta, spd, sleft, nleft) if not self.hash_b: t = " now hashing..." eprint(txt + "\033]0;{0}\033\\\r{0}{1}".format(t, tail)) if self.ar.wlist: self.at_hash = time.time() - self.t0 if self.hash_b and self.at_hash: spd = humansize(self.hash_b / self.at_hash) eprint("\nhasher: %.2f sec, %s/s\n" % (self.at_hash, spd)) if self.up_br and self.at_up: spd = humansize(self.up_br / self.at_up) eprint("upload: %.2f sec, %s/s\n" % (self.at_up, spd)) if not self.recheck: return eprint("finalizing %d duplicate files\n" % (len(self.recheck),)) for file in self.recheck: handshake(self.ar, file, False) def cleanup_vt100(self): if VT100: ss.scroll_region(None) else: eprint("\033]9;4;0\033\\") eprint("\033[J\033]0;\033\\") def cb_hasher(self, file, ofs): self.st_hash = [file, ofs] def hasher(self): ptn = re.compile(self.ar.x.encode("utf-8"), re.I) if self.ar.x else None sep = "{0}".format(os.sep).encode("ascii") prd = None ls = {} for top, rel, inf in self.filegen: isdir = stat.S_ISDIR(inf.st_mode) if self.ar.z or self.ar.drd: rd = rel if isdir else os.path.dirname(rel) srd = rd.decode("utf-8", "replace").replace("\\", "/").rstrip("/") if srd: srd += "/" if prd != rd: prd = rd ls = {} try: print(" ls ~{0}".format(srd)) zt = ( self.ar.vtop, quotep(rd.replace(b"\\", b"/")).decode("utf-8"), ) sc, txt = web.req("GET", "%s%s?ls&lt&dots" % zt, {}) if sc >= 400: raise Exception("http %s" % (sc,)) j = json.loads(txt) for f in j["dirs"] + j["files"]: rfn = f["href"].split("?")[0].rstrip("/") ls[unquote(rfn.encode("utf-8", WTF8))] = f except Exception as ex: print(" mkdir ~{0} ({1})".format(srd, ex)) if self.ar.drd: dp = os.path.join(top, rd) try: lnodes = set(os.listdir(dp)) except: lnodes = list(ls) # fs eio; don't delete if ptn: zs = dp.replace(sep, b"/").rstrip(b"/") + b"/" zls = [zs + x for x in lnodes] zls = [x for x in zls if not ptn.match(x)] lnodes = [x.split(b"/")[-1] for x in zls] bnames = [x for x in ls if x not in lnodes and x != b".hist"] vpath = self.ar.url.split("://")[-1].split("/", 1)[-1] names = [x.decode("utf-8", WTF8) for x in bnames] locs = [vpath + srd + x for x in names] while locs: req = locs while req: print("DELETING ~%s#%s" % (srd, len(req))) body = json.dumps(req).encode("utf-8") sc, txt = web.req("POST", "/?delete", {}, body, MJ) if sc == 413 and "json 2big" in txt: print(" (delete request too big; slicing...)") req = req[: len(req) // 2] continue elif sc >= 400: t = "delete request failed: %s %s" raise Exception(t % (sc, txt)) break locs = locs[len(req) :] if isdir: continue if self.ar.z: rf = ls.get(os.path.basename(rel), None) if rf and rf["sz"] == inf.st_size and abs(rf["ts"] - inf.st_mtime) <= 2: self.nfiles -= 1 self.nbytes -= inf.st_size continue file = File(top, rel, inf.st_size, inf.st_mtime) while True: with self.mutex: if ( self.hash_f - self.up_f == 1 or ( self.hash_b - self.up_b < 1024 * 1024 * 1024 and self.hash_c - self.up_c < 512 ) ) and ( not self.ar.nh or ( self.q_upload.empty() and self.q_handshake.empty() and not self.uploader_busy ) ): break time.sleep(0.05) get_hashlist(file, self.cb_hasher, self.mth) with self.mutex: self.hash_f += 1 self.hash_c += len(file.cids) self.hash_b += file.size if self.ar.wlist: self.up_f = self.hash_f self.up_c = self.hash_c self.up_b = self.hash_b if self.ar.wlist: vp = file.rel.decode("utf-8") if self.ar.chs: zsl = [ "%s %d %d" % (zsii[0], n, zsii[1]) for n, zsii in enumerate(file.cids) ] print("chs: %s\n%s" % (vp, "\n".join(zsl))) zsl = [self.ar.wsalt, str(file.size)] + [x[0] for x in file.cids] zb = hashlib.sha512("\n".join(zsl).encode("utf-8")).digest()[:33] wark = ub64enc(zb).decode("utf-8") if self.ar.jw: print("%s %s" % (wark, vp)) else: zd = datetime.datetime.fromtimestamp(max(0, file.lmod), UTC) dt = "%04d-%02d-%02d %02d:%02d:%02d" % ( zd.year, zd.month, zd.day, zd.hour, zd.minute, zd.second, ) print("%s %12d %s %s" % (dt, file.size, wark, vp)) continue self.q_handshake.put(file) self.st_hash = [None, "(finished)"] self._check_if_done() def _check_if_done(self): with self.mutex: if self.nfiles - self.up_f: return for _ in range(self.ar.j): self.q_handshake.put(None) def handshaker(self): search = self.ar.s while True: file = self.q_handshake.get() if not file: with self.mutex: self.handshaker_alive -= 1 self.q_upload.put(None) return chunksz = up2k_chunksize(file.size) upath = file.abs.decode("utf-8", "replace") if not VT100: upath = upath.lstrip("\\?") file.nhs += 1 if file.nhs > 32: print("ERROR: giving up on file %s" % (upath)) self.errs += 1 continue while time.time() < file.cd: time.sleep(0.1) try: hs, sprs = handshake(self.ar, file, search) except Fatal: self.panik = 1 break if search: if hs: for hit in hs: print("found: %s\n %s/%s" % (upath, self.ar.burl, hit["rp"])) else: print("NOT found: {0}".format(upath)) with self.mutex: self.up_f += 1 self.up_c += len(file.cids) self.up_b += file.size self._check_if_done() continue if file.recheck: self.recheck.append(file) with self.mutex: if hs and not sprs and not self.serialized: t = "server filesystem does not support sparse files; serializing uploads\n" eprint(t) self.serialized = True for _ in range(self.ar.j - 1): self.q_upload.put(None) if not hs: # all chunks done self.up_f += 1 self.up_c += len(file.cids) - file.up_c self.up_b += file.size - file.up_b if not file.recheck: self.up_done(file) if hs and file.up_c: # some chunks failed self.up_c -= len(hs) file.up_c -= len(hs) for cid in hs: sz = file.kchunks[cid][1] self.up_br -= sz self.up_b -= sz file.up_b -= sz if hs and not file.up_b: # first hs of this file; is this an upload resume? file.up_b = chunksz * max(0, len(file.kchunks) - len(hs)) file.ucids = hs if not hs: self.at_hash += file.t_hash if self.ar.spd: if VT100: c1 = "\033[36m" c2 = "\033[0m" else: c1 = c2 = "" spd_h = humansize(file.size / file.t_hash, True) if file.up_c: t_up = file.t1_up - file.t0_up spd_u = humansize(file.size / t_up, True) t = "uploaded %s %s(h:%.2fs,%s/s,up:%.2fs,%s/s)%s" print(t % (upath, c1, file.t_hash, spd_h, t_up, spd_u, c2)) else: t = " found %s %s(%.2fs,%s/s)%s" print(t % (upath, c1, file.t_hash, spd_h, c2)) else: kw = "uploaded" if file.up_c else " found" print("{0} {1}".format(kw, upath)) self._check_if_done() continue njoin = self.ar.sz // chunksz cs = hs[:] while cs: fsl = FileSlice(file, cs[:1]) try: if file.nojoin: raise Exception() for n in range(2, min(len(cs), njoin + 1)): fsl = FileSlice(file, cs[:n]) except: pass cs = cs[len(fsl.cids) :] self.q_upload.put(fsl) def uploader(self): while True: fsl = self.q_upload.get() if not fsl: done = False with self.mutex: self.uploader_alive -= 1 if not self.uploader_alive: done = not self.handshaker_alive self.st_up = [None, "(finished)"] if done: with self.exit_cond: self.exit_cond.notify_all() return file = fsl.file cids = fsl.cids self.last_file = file with self.mutex: if not self.uploader_busy: self.at_upr = time.time() self.uploader_busy += 1 if not file.t0_up: file.t0_up = time.time() if not self.t0_up: self.t0_up = file.t0_up stats = "%d/%d/%d/%d %d/%d %s" % ( self.up_f, len(self.recheck), self.uploader_busy, self.nfiles - self.up_f, self.nbytes // (1024 * 1024), (self.nbytes - self.up_b) // (1024 * 1024), self.eta, ) try: upload(fsl, stats, self.ar.szm) except Exception as ex: t = "upload failed, retrying: %s #%s+%d (%s)\n" eprint(t % (file.name, cids[0][:8], len(cids) - 1, ex)) file.cd = time.time() + self.ar.cd # handshake will fix it with self.mutex: sz = fsl.len file.ucids = [x for x in file.ucids if x not in cids] if not file.ucids: file.t1_up = time.time() self.q_handshake.put(file) self.st_up = [file, cids[0]] file.up_b += sz self.up_b += sz self.up_br += sz file.up_c += 1 self.up_c += 1 self.uploader_busy -= 1 if not self.uploader_busy: self.at_up += time.time() - self.at_upr def up_done(self, file): if self.ar.dl: os.unlink(file.abs) class APF(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass def main(): global web, linkfile time.strptime("19970815", "%Y%m%d") # python#7980 "".encode("idna") # python#29288 if not VT100: os.system("rem") # enables colors cores = (os.cpu_count() if hasattr(os, "cpu_count") else 0) or 2 hcores = min(cores, 3) # 4% faster than 4+ on py3.9 @ r5-4500U ver = "{0}, v{1}".format(S_BUILD_DT, S_VERSION) if "--version" in sys.argv: print(ver) return sys.argv = [x for x in sys.argv if x != "--ws"] # fmt: off ap = app = argparse.ArgumentParser(formatter_class=APF, description="copyparty up2k uploader / filesearch tool " + ver, epilog=""" NOTE: source file/folder selection uses rsync syntax, meaning that: "foo" uploads the entire folder to URL/foo/ "foo/" uploads the CONTENTS of the folder into URL/ NOTE: if server has --usernames enabled, then password is "username:password" """) ap.add_argument("url", type=unicode, help="server url, including destination folder") ap.add_argument("files", type=files_decoder, nargs="+", help="files and/or folders to process") ap.add_argument("-v", action="store_true", help="verbose") ap.add_argument("-a", metavar="PASSWD", default="", help="password (or $filepath) for copyparty (is sent in header 'PW')") ap.add_argument("--ba", metavar="PASSWD", default="", help="password (or $filepath) for basic-auth (usually not necessary)") ap.add_argument("-s", action="store_true", help="file-search (disables upload)") ap.add_argument("-x", type=unicode, metavar="REGEX", action="append", help="skip file if filesystem-abspath matches REGEX (option can be repeated), example: '.*/\\.hist/.*'") ap.add_argument("--ok", action="store_true", help="continue even if some local files are inaccessible") ap.add_argument("--touch", action="store_true", help="if last-modified timestamps differ, push local to server (need write+delete perms)") ap.add_argument("--ow", action="store_true", help="overwrite existing files instead of autorenaming") ap.add_argument("--owo", action="store_true", help="overwrite existing files if server-file is older") ap.add_argument("--spd", action="store_true", help="print speeds for each file") ap.add_argument("--version", action="store_true", help="show version and exit") ap = app.add_argument_group("print links") ap.add_argument("-u", action="store_true", help="print list of download-links after all uploads finished") ap.add_argument("-ud", action="store_true", help="print download-link after each upload finishes") ap.add_argument("-uf", type=unicode, metavar="PATH", help="print list of download-links to file") ap = app.add_argument_group("compatibility") ap.add_argument("--cls", action="store_true", help="clear screen before start") ap.add_argument("--rh", type=int, metavar="TRIES", default=0, help="resolve server hostname before upload (good for buggy networks, but TLS certs will break)") ap = app.add_argument_group("folder sync") ap.add_argument("--dl", action="store_true", help="delete local files after uploading") ap.add_argument("--dr", action="store_true", help="delete remote files which don't exist locally (implies --ow)") ap.add_argument("--drd", action="store_true", help="delete remote files during upload instead of afterwards; reduces peak disk space usage, but will reupload instead of detecting renames") ap = app.add_argument_group("file-ID calculator; enable with url '-' to list warks (file identifiers) instead of upload/search") ap.add_argument("--wsalt", type=unicode, metavar="S", default="hunter2", help="salt to use when creating warks; must match server config") ap.add_argument("--chs", action="store_true", help="verbose (print the hash/offset of each chunk in each file)") ap.add_argument("--jw", action="store_true", help="just identifier+filepath, not mtime/size too") ap = app.add_argument_group("performance tweaks") ap.add_argument("-j", type=int, metavar="CONNS", default=2, help="parallel connections") ap.add_argument("-J", type=int, metavar="CORES", default=hcores, help="num cpu-cores to use for hashing; set 0 or 1 for single-core hashing") ap.add_argument("--sz", type=int, metavar="MiB", default=64, help="try to make each POST this big") ap.add_argument("--szm", type=int, metavar="MiB", default=96, help="max size of each POST (default is cloudflare max)") ap.add_argument("-nh", action="store_true", help="disable hashing while uploading") ap.add_argument("-ns", action="store_true", help="no status panel (for slow consoles and macos)") ap.add_argument("--cxp", type=float, metavar="SEC", default=57, help="assume http connections expired after SEConds") ap.add_argument("--cd", type=float, metavar="SEC", default=5, help="delay before reattempting a failed handshake/upload") ap.add_argument("--t-hs", type=float, metavar="SEC", default=186, help="crash if handshakes fail due to server-offline for this long") ap.add_argument("--safe", action="store_true", help="use simple fallback approach") ap.add_argument("-z", action="store_true", help="ZOOMIN' (skip uploading files if they exist at the destination with the ~same last-modified timestamp, so same as yolo / turbo with date-chk but even faster)") ap = app.add_argument_group("tls") ap.add_argument("-te", metavar="PATH", help="path to ca.pem or cert.pem to expect/verify") ap.add_argument("-teh", action="store_true", help="require correct hostname in -te cert") ap.add_argument("-td", action="store_true", help="disable certificate check") # fmt: on try: ar = app.parse_args() finally: if EXE and not sys.argv[1:]: eprint("*** hit enter to exit ***") try: input() except: pass # msys2 doesn't uncygpath absolute paths with whitespace if not VT100: zsl = [] for fn in ar.files: if re.search("^/[a-z]/", fn): fn = r"%s:\%s" % (fn[1:2], fn[3:]) zsl.append(fn.replace("/", "\\")) ar.files = zsl fok = [] fng = [] for fn in ar.files: if os.path.exists(fn): fok.append(fn) elif VT100: fng.append(fn) else: # windows leaves glob-expansion to the invoked process... okayyy let's get to work from glob import glob fns = glob(fn) if fns: fok.extend(fns) else: fng.append(fn) if fng: t = "some files/folders were not found:\n %s" raise Exception(t % ("\n ".join(fng),)) ar.files = fok if ar.drd: ar.dr = True if ar.dr: ar.ow = True ar.sz *= 1024 * 1024 ar.szm *= 1024 * 1024 ar.x = "|".join(ar.x or []) setattr(ar, "wlist", ar.url == "-") setattr(ar, "uon", ar.u or ar.ud or ar.uf) if ar.uf: linkfile = open(ar.uf, "wb") for k in "dl dr drd wlist".split(): errs = [] if ar.safe and getattr(ar, k): errs.append(k) if errs: raise Exception("--safe is incompatible with " + str(errs)) ar.files = [ os.path.abspath(os.path.realpath(x.encode("utf-8"))) + (x[-1:] if x[-1:] in ("\\", "/") else "").encode("utf-8") for x in ar.files ] # urlsplit needs scheme; zs = ar.url.rstrip("/") + "/" if "://" not in zs: zs = "http://" + zs ar.url = zs url = urlsplit(zs) ar.burl = "%s://%s" % (url.scheme, url.netloc) ar.vtop = url.path if "https://" in ar.url.lower(): try: import ssl import zipfile except: t = "ERROR: https is not available for some reason; please use http" print("\n\n %s\n\n" % (t,)) raise for k in ("a", "ba"): zs = getattr(ar, k) if zs.startswith("$"): print("reading password from file [%s]" % (zs[1:],)) with open(zs[1:], "rb") as f: setattr(ar, k, f.read().decode("utf-8").strip()) if ar.ba: ar.ba = "Basic " + base64.b64encode(ar.ba.encode("utf-8")).decode("utf-8") for n in range(ar.rh): try: ar.url = undns(ar.url) break except KeyboardInterrupt: raise except: if n > ar.rh - 2: raise if ar.cls: eprint("\033[H\033[2J\033[3J", end="") web = HCli(ar) ctl = Ctl(ar) if ar.dr and not ar.drd and ctl.ok: print("\npass 2/2: delete") ar.drd = True ar.z = True ctl = Ctl(ar, ctl.stats) if links: print() print("\n".join(links)) if linkfile: linkfile.close() if ctl.errs: print("WARNING: %d errors" % (ctl.errs)) sys.exit(0 if ctl.ok else 1) if __name__ == "__main__": main()
--- +++ @@ -245,6 +245,7 @@ class File(object): + """an up2k upload task; represents a single file""" def __init__(self, top, rel, size, lmod): self.top = top # type: bytes @@ -277,6 +278,7 @@ class FileSlice(object): + """file-like object providing a fixed window into a file""" def __init__(self, file, cids): # type: (File, str) -> None @@ -596,6 +598,7 @@ def _scd(err, top): + """non-recursive listing of directory contents, along with stat() info""" top_ = os.path.join(top, b"") with os.scandir(top) as dh: for fh in dh: @@ -607,6 +610,7 @@ def _lsd(err, top): + """non-recursive listing of directory contents, along with stat() info""" top_ = os.path.join(top, b"") for name in os.listdir(top): abspath = top_ + name @@ -623,6 +627,7 @@ def walkdir(err, top, excl, seen): + """recursive statdir""" atop = os.path.abspath(os.path.realpath(top)) if atop in seen: err.append((top, "recursive-symlink")) @@ -646,6 +651,7 @@ def walkdirs(err, tops, excl): + """recursive statdir for a list of tops, yields [top, relpath, stat]""" sep = "{0}".format(os.sep).encode("ascii") if not VT100: excl = excl.replace("/", r"\\") @@ -697,6 +703,7 @@ # from copyparty/util.py def humansize(sz, terse=False): + """picks a sensible unit for the given extent""" for unit in ["B", "KiB", "MiB", "GiB", "TiB"]: if sz < 1024: break @@ -713,6 +720,7 @@ # from copyparty/up2k.py def up2k_chunksize(filesize): + """gives The correct chunksize for up2k hashing""" chunksize = 1024 * 1024 stepsize = 512 * 1024 while True: @@ -728,6 +736,7 @@ # mostly from copyparty/up2k.py def get_hashlist(file, pcb, mth): # type: (File, Any, Any) -> None + """generates the up2k hashlist from file contents, inserts it into `file`""" chunk_sz = up2k_chunksize(file.size) file_rem = file.size @@ -794,6 +803,11 @@ def handshake(ar, file, search): # type: (argparse.Namespace, File, bool) -> tuple[list[str], bool] + """ + performs a handshake with the server; reply is: + if search, a list of search results + otherwise, a list of chunks to upload + """ req = { "hash": [x[0] for x in file.cids], @@ -881,6 +895,7 @@ def upload(fsl, stats, maxsz): # type: (FileSlice, str, int) -> None + """upload a range of file data, defined by one or more `cid` (chunk-hash)""" ctxt = fsl.cids[0] if len(fsl.cids) > 1: @@ -928,6 +943,10 @@ class Ctl(object): + """ + the coordinator which runs everything in parallel + (hashing, handshakes, uploads) + """ def _scan(self): ar = self.ar @@ -1019,6 +1038,7 @@ self.ok = not self.errs def _safe(self): + """minimal basic slow boring fallback codepath""" search = self.ar.s nf = 0 for top, rel, inf in self.filegen: @@ -1723,4 +1743,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/9001/copyparty/HEAD/bin/u2c.py
Help me add docstrings to my project
# coding: utf-8 from __future__ import print_function, unicode_literals import argparse import base64 import hashlib import json import os import re import stat import sys import threading import time from datetime import datetime from .__init__ import ANYWIN, MACOS, PY2, TYPE_CHECKING, WINDOWS, E from .bos import bos from .cfg import flagdescs, permdescs, vf_bmap, vf_cmap, vf_vmap from .pwhash import PWHash from .util import ( DEF_MTE, DEF_MTH, EXTS, FAVICON_MIMES, FN_EMB, HAVE_SQLITE3, IMPLICATIONS, META_NOBOTS, MIMES, SQLITE_VER, UNPLICATIONS, UTC, ODict, Pebkac, absreal, afsenc, get_df, humansize, json_hesc, min_ex, odfusion, read_utf8, relchk, statdir, ub64enc, uncyg, undot, unhumanize, vjoin, vsplit, ) if HAVE_SQLITE3: import sqlite3 if True: # pylint: disable=using-constant-test from collections.abc import Iterable from typing import Any, Generator, Optional, Sequence, Union from .util import NamedLogger, RootLogger if TYPE_CHECKING: from .broker_mp import BrokerMp from .broker_thr import BrokerThr from .broker_util import BrokerCli # Vflags: TypeAlias = dict[str, str | bool | float | list[str]] # Vflags: TypeAlias = dict[str, Any] # Mflags: TypeAlias = dict[str, Vflags] if PY2: range = xrange # type: ignore LEELOO_DALLAS = "leeloo_dallas" ## ## you might be curious what Leeloo Dallas is doing here, so let me explain: ## ## certain daemonic tasks, namely: ## * deletion of expired files, running on a timer ## * deletion of sidecar files, initiated by plugins ## need to skip the usual permission-checks to do their thing, ## so we let Leeloo handle these ## ## and also, the smb-server has really shitty support for user-accounts ## so one popular way to avoid issues is by running copyparty without users; ## this makes all smb-clients identify as LD to gain unrestricted access ## ## Leeloo, being a fictional character from The Fifth Element, ## obviously does not exist and will never be able to access any copyparty ## instances from the outside (the username is rejected at every entrypoint) ## ## thanks for coming to my ted talk UP_MTE_MAP = { # db-order "w": "substr(w,1,16)", "up_ip": "ip", ".up_at": "at", "up_by": "un", } SEE_LOG = "see log for details" SEESLOG = " (see fileserver log for details)" SSEELOG = " ({})".format(SEE_LOG) BAD_CFG = "invalid config; {}".format(SEE_LOG) SBADCFG = " ({})".format(BAD_CFG) PTN_U_GRP = re.compile(r"\$\{u(%[+-][^}]+)\}") PTN_G_GRP = re.compile(r"\$\{g(%[+-][^}]+)\}") PTN_U_ANY = re.compile(r"(\${[u][}%])") PTN_G_ANY = re.compile(r"(\${[g][}%])") PTN_SIGIL = re.compile(r"(\${[ug][}%])") class CfgEx(Exception): pass class AXS(object): def __init__( self, uread: Optional[Union[list[str], set[str]]] = None, uwrite: Optional[Union[list[str], set[str]]] = None, umove: Optional[Union[list[str], set[str]]] = None, udel: Optional[Union[list[str], set[str]]] = None, uget: Optional[Union[list[str], set[str]]] = None, upget: Optional[Union[list[str], set[str]]] = None, uhtml: Optional[Union[list[str], set[str]]] = None, uadmin: Optional[Union[list[str], set[str]]] = None, udot: Optional[Union[list[str], set[str]]] = None, ) -> None: self.uread: set[str] = set(uread or []) self.uwrite: set[str] = set(uwrite or []) self.umove: set[str] = set(umove or []) self.udel: set[str] = set(udel or []) self.uget: set[str] = set(uget or []) self.upget: set[str] = set(upget or []) self.uhtml: set[str] = set(uhtml or []) self.uadmin: set[str] = set(uadmin or []) self.udot: set[str] = set(udot or []) def __repr__(self) -> str: ks = "uread uwrite umove udel uget upget uhtml uadmin udot".split() return "AXS(%s)" % (", ".join("%s=%r" % (k, self.__dict__[k]) for k in ks),) class Lim(object): def __init__( self, args: argparse.Namespace, log_func: Optional["RootLogger"] ) -> None: self.log_func = log_func self.use_scandir = not args.no_scandir self.reg: Optional[dict[str, dict[str, Any]]] = None # up2k registry self.chmod_d = 0o755 self.uid = self.gid = -1 self.chown = False self.nups: dict[str, list[float]] = {} # num tracker self.bups: dict[str, list[tuple[float, int]]] = {} # byte tracker list self.bupc: dict[str, int] = {} # byte tracker cache self.nosub = False # disallow subdirectories self.dfl = 0 # free disk space limit self.dft = 0 # last-measured time self.dfv = 0 # currently free self.vbmax = 0 # volume bytes max self.vnmax = 0 # volume max num files self.c_vb_v = 0 # cache: volume bytes used (value) self.c_vb_r = 0 # cache: volume bytes used (ref) self.smin = 0 # filesize min self.smax = 0 # filesize max self.bwin = 0 # bytes window self.bmax = 0 # bytes max self.nwin = 0 # num window self.nmax = 0 # num max self.rotn = 0 # rot num files self.rotl = 0 # rot depth self.rotf = "" # rot datefmt self.rotf_tz = UTC # rot timezone self.rot_re = re.compile("") # rotf check def log(self, msg: str, c: Union[int, str] = 0) -> None: if self.log_func: self.log_func("up-lim", msg, c) def set_rotf(self, fmt: str, tz: str) -> None: self.rotf = fmt.rstrip("/\\") if tz != "UTC": from zoneinfo import ZoneInfo self.rotf_tz = ZoneInfo(tz) r = re.escape(self.rotf).replace("%Y", "[0-9]{4}").replace("%j", "[0-9]{3}") r = re.sub("%[mdHMSWU]", "[0-9]{2}", r) self.rot_re = re.compile("(^|/)" + r + "$") def all( self, ip: str, rem: str, sz: int, ptop: str, abspath: str, broker: Optional[Union["BrokerCli", "BrokerMp", "BrokerThr"]] = None, reg: Optional[dict[str, dict[str, Any]]] = None, volgetter: str = "up2k.get_volsize", ) -> tuple[str, str]: if reg is not None and self.reg is None: self.reg = reg self.dft = 0 self.chk_nup(ip) self.chk_bup(ip) self.chk_rem(rem) if sz != -1: self.chk_sz(sz) else: sz = 0 self.chk_vsz(broker, ptop, sz, volgetter) self.chk_df(abspath, sz) # side effects; keep last-ish ap2, vp2 = self.rot(abspath) if abspath == ap2: return ap2, rem return ap2, ("{}/{}".format(rem, vp2) if rem else vp2) def chk_sz(self, sz: int) -> None: if sz < self.smin: raise Pebkac(400, "file too small") if self.smax and sz > self.smax: raise Pebkac(400, "file too big") def chk_vsz( self, broker: Optional[Union["BrokerCli", "BrokerMp", "BrokerThr"]], ptop: str, sz: int, volgetter: str = "up2k.get_volsize", ) -> None: if not broker or not self.vbmax + self.vnmax: return x = broker.ask(volgetter, ptop) self.c_vb_v, nfiles = x.get() if self.vbmax and self.vbmax < self.c_vb_v + sz: raise Pebkac(400, "volume has exceeded max size") if self.vnmax and self.vnmax < nfiles + 1: raise Pebkac(400, "volume has exceeded max num.files") def chk_df(self, abspath: str, sz: int, already_written: bool = False) -> None: if not self.dfl: return if self.dft < time.time(): self.dft = int(time.time()) + 300 df, du, err = get_df(abspath, True) if err: t = "failed to read disk space usage for %r: %s" self.log(t % (abspath, err), 3) self.dfv = 0xAAAAAAAAA # 42.6 GiB else: self.dfv = df or 0 for j in list(self.reg.values()) if self.reg else []: self.dfv -= int(j["size"] / (len(j["hash"]) or 999) * len(j["need"])) if already_written: sz = 0 if self.dfv - sz < self.dfl: self.dft = min(self.dft, int(time.time()) + 10) t = "server HDD is full; {} free, need {}" raise Pebkac(500, t.format(humansize(self.dfv - self.dfl), humansize(sz))) self.dfv -= int(sz) def chk_rem(self, rem: str) -> None: if self.nosub and rem: raise Pebkac(500, "no subdirectories allowed") def rot(self, path: str) -> tuple[str, str]: if not self.rotf and not self.rotn: return path, "" if self.rotf: path = path.rstrip("/\\") if self.rot_re.search(path.replace("\\", "/")): return path, "" suf = datetime.now(self.rotf_tz).strftime(self.rotf) if path: path += "/" return path + suf, suf ret = self.dive(path, self.rotl) if not ret: raise Pebkac(500, "no available slots in volume") d = ret[len(path) :].strip("/\\").replace("\\", "/") return ret, d def dive(self, path: str, lvs: int) -> Optional[str]: if not lvs: # at leaf level items = statdir(self.log_func, self.use_scandir, False, path, True) items = [ x for x in items if not stat.S_ISDIR(x[1].st_mode) and not x[0].endswith(".PARTIAL") ] return None if len(items) >= self.rotn else "" items = bos.listdir(path) dirs = [int(x) for x in items if x and all(y in "1234567890" for y in x)] dirs.sort() if not dirs: # no branches yet; make one sub = os.path.join(path, "0") bos.mkdir(sub, self.chmod_d) if self.chown: os.chown(sub, self.uid, self.gid) else: # try newest branch only sub = os.path.join(path, str(dirs[-1])) ret = self.dive(sub, lvs - 1) if ret is not None: return os.path.join(sub, ret) if len(dirs) >= self.rotn: # full branch or root return None # make a branch sub = os.path.join(path, str(dirs[-1] + 1)) bos.mkdir(sub, self.chmod_d) if self.chown: os.chown(sub, self.uid, self.gid) ret = self.dive(sub, lvs - 1) if ret is None: raise Pebkac(500, "rotation bug") return os.path.join(sub, ret) def nup(self, ip: str) -> None: try: self.nups[ip].append(time.time()) except: self.nups[ip] = [time.time()] def bup(self, ip: str, nbytes: int) -> None: v = (time.time(), nbytes) try: self.bups[ip].append(v) self.bupc[ip] += nbytes except: self.bups[ip] = [v] self.bupc[ip] = nbytes def chk_nup(self, ip: str) -> None: if not self.nmax or ip not in self.nups: return nups = self.nups[ip] cutoff = time.time() - self.nwin while nups and nups[0] < cutoff: nups.pop(0) if len(nups) >= self.nmax: raise Pebkac(429, "too many uploads") def chk_bup(self, ip: str) -> None: if not self.bmax or ip not in self.bups: return bups = self.bups[ip] cutoff = time.time() - self.bwin mark = self.bupc[ip] while bups and bups[0][0] < cutoff: mark -= bups.pop(0)[1] self.bupc[ip] = mark if mark >= self.bmax: raise Pebkac(429, "upload size limit exceeded") class VFS(object): def __init__( self, log: Optional["RootLogger"], realpath: str, vpath: str, vpath0: str, axs: AXS, flags: dict[str, Any], ) -> None: self.log = log self.realpath = realpath # absolute path on host filesystem self.vpath = vpath # absolute path in the virtual filesystem self.vpath0 = vpath0 # original vpath (before idp expansion) self.axs = axs self.uaxs: dict[ str, tuple[bool, bool, bool, bool, bool, bool, bool, bool, bool] ] = {} self.flags = flags # config options self.root = self self.dev = 0 # st_dev self.nodes: dict[str, VFS] = {} # child nodes self.histtab: dict[str, str] = {} # all realpath->histpath self.dbpaths: dict[str, str] = {} # all realpath->dbpath self.dbv: Optional[VFS] = None # closest full/non-jump parent self.lim: Optional[Lim] = None # upload limits; only set for dbv self.shr_src: Optional[tuple[VFS, str]] = None # source vfs+rem of a share self.shr_files: set[str] = set() # filenames to include from shr_src self.shr_owner: str = "" # uname self.shr_all_aps: list[tuple[str, list[VFS]]] = [] self.aread: dict[str, list[str]] = {} self.awrite: dict[str, list[str]] = {} self.amove: dict[str, list[str]] = {} self.adel: dict[str, list[str]] = {} self.aget: dict[str, list[str]] = {} self.apget: dict[str, list[str]] = {} self.ahtml: dict[str, list[str]] = {} self.aadmin: dict[str, list[str]] = {} self.adot: dict[str, list[str]] = {} self.js_ls = {} self.js_htm = "" self.all_vols: dict[str, VFS] = {} # flattened recursive self.all_nodes: dict[str, VFS] = {} # also jumpvols/shares self.all_fvols: dict[str, VFS] = {} # volumes which are files if realpath: rp = realpath + ("" if realpath.endswith(os.sep) else os.sep) vp = vpath + ("/" if vpath else "") self.histpath = os.path.join(realpath, ".hist") # db / thumbcache self.dbpath = self.histpath self.all_vols[vpath] = self self.all_nodes[vpath] = self self.all_aps = [(rp, [self])] self.all_vps = [(vp, self)] self.canonical = self._canonical self.dcanonical = self._dcanonical else: self.histpath = self.dbpath = "" self.all_aps = [] self.all_vps = [] self.canonical = self._canonical_null self.dcanonical = self._dcanonical_null self.get_dbv = self._get_dbv self.ls = self._ls def __repr__(self) -> str: return "VFS(%s)" % ( ", ".join( "%s=%r" % (k, self.__dict__[k]) for k in "realpath vpath axs flags".split() ) ) def get_all_vols( self, vols: dict[str, "VFS"], nodes: dict[str, "VFS"], aps: list[tuple[str, list["VFS"]]], vps: list[tuple[str, "VFS"]], ) -> None: nodes[self.vpath] = self if self.realpath: vols[self.vpath] = self rp = self.realpath rp += "" if rp.endswith(os.sep) else os.sep vp = self.vpath + ("/" if self.vpath else "") hit = next((x[1] for x in aps if x[0] == rp), None) if hit: hit.append(self) else: aps.append((rp, [self])) vps.append((vp, self)) for v in self.nodes.values(): v.get_all_vols(vols, nodes, aps, vps) def add(self, src: str, dst: str, dst0: str) -> "VFS": assert src == "/" or not src.endswith("/") # nosec assert not dst.endswith("/") # nosec if "/" in dst: # requires breadth-first population (permissions trickle down) name, dst = dst.split("/", 1) name0, dst0 = dst0.split("/", 1) if name in self.nodes: # exists; do not manipulate permissions return self.nodes[name].add(src, dst, dst0) vn = VFS( self.log, os.path.join(self.realpath, name) if self.realpath else "", "{}/{}".format(self.vpath, name).lstrip("/"), "{}/{}".format(self.vpath0, name0).lstrip("/"), self.axs, self._copy_flags(name), ) vn.dbv = self.dbv or self self.nodes[name] = vn return vn.add(src, dst, dst0) if dst in self.nodes: # leaf exists; return as-is return self.nodes[dst] # leaf does not exist; create and keep permissions blank vp = "{}/{}".format(self.vpath, dst).lstrip("/") vp0 = "{}/{}".format(self.vpath0, dst0).lstrip("/") vn = VFS(self.log, src, vp, vp0, AXS(), {}) vn.dbv = self.dbv or self self.nodes[dst] = vn return vn def _copy_flags(self, name: str) -> dict[str, Any]: flags = {k: v for k, v in self.flags.items()} hist = flags.get("hist") if hist and hist != "-": zs = "{}/{}".format(hist.rstrip("/"), name) flags["hist"] = os.path.expandvars(os.path.expanduser(zs)) dbp = flags.get("dbpath") if dbp and dbp != "-": zs = "{}/{}".format(dbp.rstrip("/"), name) flags["dbpath"] = os.path.expandvars(os.path.expanduser(zs)) return flags def bubble_flags(self) -> None: if self.dbv: for k, v in self.dbv.flags.items(): if k not in ("hist", "dbpath"): self.flags[k] = v for n in self.nodes.values(): n.bubble_flags() def _find(self, vpath: str) -> tuple["VFS", str]: if not vpath: return self, "" if "/" in vpath: name, rem = vpath.split("/", 1) else: name = vpath rem = "" if name in self.nodes: return self.nodes[name]._find(rem) return self, vpath def can_access( self, vpath: str, uname: str ) -> tuple[bool, bool, bool, bool, bool, bool, bool, bool, bool]: # NOTE: only used by get_perms, which is only used by hooks; the lowest of fruits if vpath: vn, _ = self._find(undot(vpath)) else: vn = self return vn.uaxs[uname] def get_perms(self, vpath: str, uname: str) -> str: zbl = self.can_access(vpath, uname) ret = "".join(ch for ch, ok in zip("rwmdgGha.", zbl) if ok) if "rwmd" in ret and "a." in ret: ret += "A" return ret def get( self, vpath: str, uname: str, will_read: bool, will_write: bool, will_move: bool = False, will_del: bool = False, will_get: bool = False, err: int = 403, ) -> tuple["VFS", str]: if relchk(vpath): if self.log: self.log("vfs", "invalid relpath %r @%s" % (vpath, uname)) raise Pebkac(422) cvpath = undot(vpath) vn, rem = self._find(cvpath) c: AXS = vn.axs for req, d, msg in [ (will_read, c.uread, "read"), (will_write, c.uwrite, "write"), (will_move, c.umove, "move"), (will_del, c.udel, "delete"), (will_get, c.uget, "get"), ]: if req and uname not in d and uname != LEELOO_DALLAS: if vpath != cvpath and vpath != "." and self.log: ap = vn.canonical(rem) t = "%s has no %s in %r => %r => %r" self.log("vfs", t % (uname, msg, vpath, cvpath, ap), 6) t = "you don't have %s-access in %r or below %r" raise Pebkac(err, t % (msg, "/" + cvpath, "/" + vn.vpath)) return vn, rem def _get_share_src(self, vrem: str) -> tuple["VFS", str]: src = self.shr_src if not src: return self._get_dbv(vrem) shv, srem = src return shv._get_dbv(vjoin(srem, vrem)) def _get_dbv(self, vrem: str) -> tuple["VFS", str]: dbv = self.dbv if not dbv: return self, vrem vrem = vjoin(self.vpath[len(dbv.vpath) :].lstrip("/"), vrem) return dbv, vrem def casechk(self, rem: str, do_stat: bool) -> bool: ap = self.canonical(rem, False) if do_stat and not bos.path.exists(ap): return True # doesn't exist at all; good to go dp, fn = os.path.split(ap) if not fn: return True # filesystem root try: fns = os.listdir(dp) except: return True # maybe chmod 111; assume ok if fn in fns: return True hit = "<?>" lfn = fn.lower() for zs in fns: if lfn == zs.lower(): hit = zs break if not hit: return True # NFC/NFD or something, can't be helped either way if self.log: t = "returning 404 due to underlying case-insensitive filesystem:\n http-req: %r\n local-fs: %r" self.log("vfs", t % (fn, hit)) return False def _canonical_null(self, rem: str, resolve: bool = True) -> str: return "" def _dcanonical_null(self, rem: str) -> str: return "" def _canonical(self, rem: str, resolve: bool = True) -> str: ap = self.realpath if rem: ap += "/" + rem return absreal(ap) if resolve else ap def _dcanonical(self, rem: str) -> str: ap = self.realpath if rem: ap += "/" + rem ad, fn = os.path.split(ap) return os.path.join(absreal(ad), fn) def _canonical_shr(self, rem: str, resolve: bool = True) -> str: ap = self.realpath if rem: ap += "/" + rem rap = "" if self.shr_files: assert self.shr_src # !rm if rem and rem not in self.shr_files: return "\n\n" if resolve: rap = absreal(ap) vn, rem = self.shr_src chk = absreal(os.path.join(vn.realpath, rem)) if chk != rap: # not the dir itself; assert file allowed ad, fn = os.path.split(rap) if chk != ad or fn not in self.shr_files: return "\n\n" return (rap or absreal(ap)) if resolve else ap def _dcanonical_shr(self, rem: str) -> str: ap = self.realpath if rem: ap += "/" + rem ad, fn = os.path.split(ap) ad = absreal(ad) if self.shr_files: assert self.shr_src # !rm vn, rem = self.shr_src chk = absreal(os.path.join(vn.realpath, rem)) if chk != absreal(ap): # not the dir itself; assert file allowed if ad != chk or fn not in self.shr_files: return "\n\n" return os.path.join(ad, fn) def _ls_nope( self, *a, **ka ) -> tuple[str, list[tuple[str, os.stat_result]], dict[str, "VFS"]]: raise Pebkac(500, "nope.avi") def _ls_shr( self, rem: str, uname: str, scandir: bool, permsets: list[list[bool]], lstat: bool = False, throw: bool = False, ) -> tuple[str, list[tuple[str, os.stat_result]], dict[str, "VFS"]]: vn, rem = self.shr_src # type: ignore abspath, real, _ = vn.ls(rem, "\n", scandir, permsets, lstat, throw) real = [x for x in real if os.path.basename(x[0]) in self.shr_files] return abspath, real, {} def _ls( self, rem: str, uname: str, scandir: bool, permsets: list[list[bool]], lstat: bool = False, throw: bool = False, ) -> tuple[str, list[tuple[str, os.stat_result]], dict[str, "VFS"]]: virt_vis = {} # nodes readable by user abspath = self.canonical(rem) if abspath: real = list(statdir(self.log, scandir, lstat, abspath, throw)) real.sort() else: real = [] if not rem: # no vfs nodes in the list of real inodes real = [x for x in real if x[0] not in self.nodes] dbv = self.dbv or self for name, vn2 in sorted(self.nodes.items()): if vn2.dbv == dbv and self.flags.get("dk"): virt_vis[name] = vn2 continue u_has = vn2.uaxs.get(uname) or [False] * 9 for pset in permsets: ok = True for req, zb in zip(pset, u_has): if req and not zb: ok = False break if ok: virt_vis[name] = vn2 break if ".hist" in abspath: p = abspath.replace("\\", "/") if WINDOWS else abspath if p.endswith("/.hist"): real = [x for x in real if not x[0].startswith("up2k.")] elif "/.hist/th/" in p: real = [x for x in real if not x[0].endswith("dir.txt")] return abspath, real, virt_vis def walk( self, rel: str, rem: str, seen: list[str], uname: str, permsets: list[list[bool]], wantdots: int, scandir: bool, lstat: bool, subvols: bool = True, ) -> Generator[ tuple[ "VFS", str, str, str, list[tuple[str, os.stat_result]], list[tuple[str, os.stat_result]], dict[str, "VFS"], ], None, None, ]: fsroot, vfs_ls, vfs_virt = self.ls(rem, uname, scandir, permsets, lstat=lstat) dbv, vrem = self.get_dbv(rem) if ( seen and (not fsroot.startswith(seen[-1]) or fsroot == seen[-1]) and fsroot in seen ): if self.log: t = "bailing from symlink loop,\n prev: %r\n curr: %r\n from: %r / %r" self.log("vfs.walk", t % (seen[-1], fsroot, self.vpath, rem), 3) return if "xdev" in self.flags or "xvol" in self.flags: rm1 = [] for le in vfs_ls: ap = absreal(os.path.join(fsroot, le[0])) vn2 = self.chk_ap(ap) if not vn2 or not vn2.get("", uname, True, False): rm1.append(le) _ = [vfs_ls.remove(x) for x in rm1] # type: ignore dots_ok = wantdots and (wantdots == 2 or uname in dbv.axs.udot) if not dots_ok: vfs_ls = [x for x in vfs_ls if "/." not in "/" + x[0]] seen = seen[:] + [fsroot] rfiles = [x for x in vfs_ls if not stat.S_ISDIR(x[1].st_mode)] rdirs = [x for x in vfs_ls if stat.S_ISDIR(x[1].st_mode)] # if lstat: ignore folder symlinks since copyparty will never make those # (and we definitely don't want to descend into them) rfiles.sort() rdirs.sort() yield dbv, vrem, rel, fsroot, rfiles, rdirs, vfs_virt for rdir, _ in rdirs: if not dots_ok and rdir.startswith("."): continue wrel = (rel + "/" + rdir).lstrip("/") wrem = (rem + "/" + rdir).lstrip("/") for x in self.walk( wrel, wrem, seen, uname, permsets, wantdots, scandir, lstat, subvols ): yield x if not subvols: return for n, vfs in sorted(vfs_virt.items()): if not dots_ok and n.startswith("."): continue wrel = (rel + "/" + n).lstrip("/") for x in vfs.walk( wrel, "", seen, uname, permsets, wantdots, scandir, lstat ): yield x def zipgen( self, vpath: str, vrem: str, flt: set[str], uname: str, dirs: bool, dots: int, scandir: bool, wrap: bool = True, ) -> Generator[dict[str, Any], None, None]: # if multiselect: add all items to archive root # if single folder: the folder itself is the top-level item folder = "" if flt or not wrap else (vpath.split("/")[-1].lstrip(".") or "top") g = self.walk(folder, vrem, [], uname, [[True, False]], dots, scandir, False) for _, _, vpath, apath, files, rd, vd in g: if flt: files = [x for x in files if x[0] in flt] rm1 = [x for x in rd if x[0] not in flt] _ = [rd.remove(x) for x in rm1] # type: ignore rm2 = [x for x in vd.keys() if x not in flt] _ = [vd.pop(x) for x in rm2] flt = set() # print(repr([vpath, apath, [x[0] for x in files]])) fnames = [n[0] for n in files] vpaths = [vpath + "/" + n for n in fnames] if vpath else fnames apaths = [os.path.join(apath, n) for n in fnames] ret = list(zip(vpaths, apaths, files)) for f in [{"vp": v, "ap": a, "st": n[1]} for v, a, n in ret]: yield f if not dirs: continue ts = int(time.time()) st = os.stat_result((16877, -1, -1, 1, 1000, 1000, 8, ts, ts, ts)) dnames = [n[0] for n in rd] dstats = [n[1] for n in rd] dnames += list(vd.keys()) dstats += [st] * len(vd) vpaths = [vpath + "/" + n for n in dnames] if vpath else dnames apaths = [os.path.join(apath, n) for n in dnames] ret2 = list(zip(vpaths, apaths, dstats)) for d in [{"vp": v, "ap": a, "st": n} for v, a, n in ret2]: yield d def chk_ap(self, ap: str, st: Optional[os.stat_result] = None) -> Optional["VFS"]: aps = ap + os.sep if "xdev" in self.flags and not ANYWIN: if not st: ap2 = ap.replace("\\", "/") if ANYWIN else ap while ap2: try: st = bos.stat(ap2) break except: if "/" not in ap2: raise ap2 = ap2.rsplit("/", 1)[0] assert st vdev = self.dev if not vdev: vdev = self.dev = bos.stat(self.realpath).st_dev if vdev != st.st_dev: if self.log: t = "xdev: %s[%r] => %s[%r]" self.log("vfs", t % (vdev, self.realpath, st.st_dev, ap), 3) return None if "xvol" in self.flags: self_ap = self.realpath + os.sep if aps.startswith(self_ap): vp = aps[len(self_ap) :] if ANYWIN: vp = vp.replace(os.sep, "/") vn2, _ = self._find(vp) if self == vn2: return self all_aps = self.shr_all_aps or self.root.all_aps for vap, vns in all_aps: if aps.startswith(vap): return self if self in vns else vns[0] if self.log: self.log("vfs", "xvol: %r" % (ap,), 3) return None return self def check_landmarks(self) -> bool: if self.dbv: return True vps = self.flags.get("landmark") or [] if not vps: return True failed = "" for vp in vps: if "^=" in vp: vp, zs = vp.split("^=", 1) expect = zs.encode("utf-8") else: expect = b"" if self.log: t = "checking [/%s] landmark [%s]" self.log("vfs", t % (self.vpath, vp), 6) ap = "?" try: ap = self.canonical(vp) with open(ap, "rb") as f: buf = f.read(4096) if not buf.startswith(expect): t = "file [%s] does not start with the expected bytes %s" failed = t % (ap, expect) break except Exception as ex: t = "%r while trying to read [%s] => [%s]" failed = t % (ex, vp, ap) break if not failed: return True if self.log: t = "WARNING: landmark verification failed; %s; will now disable up2k database for volume [/%s]" self.log("vfs", t % (failed, self.vpath), 3) for rm in "e2d e2t e2v".split(): self.flags = {k: v for k, v in self.flags.items() if not k.startswith(rm)} self.flags["d2d"] = True self.flags["d2t"] = True return False if WINDOWS: re_vol = re.compile(r"^([a-zA-Z]:[\\/][^:]*|[^:]*):([^:]*):(.*)$") else: re_vol = re.compile(r"^([^:]*):([^:]*):(.*)$") class AuthSrv(object): def __init__( self, args: argparse.Namespace, log_func: Optional["RootLogger"], warn_anonwrite: bool = True, dargs: Optional[argparse.Namespace] = None, ) -> None: self.ah = PWHash(args) self.args = args self.dargs = dargs or args self.log_func = log_func self.warn_anonwrite = warn_anonwrite self.line_ctr = 0 self.indent = "" self.is_lxc = args.c == ["/z/initcfg"] oh = "X-Content-Type-Options: nosniff\r\n" if self.args.http_vary: oh += "Vary: %s\r\n" % (self.args.http_vary,) self._vf0b = { "oh_g": oh + "\r\n", "oh_f": oh + "\r\n", "cachectl": self.args.cachectl, "tcolor": self.args.tcolor, "du_iwho": self.args.du_iwho, "shr_who": self.args.shr_who if self.args.shr else "no", "emb_all": FN_EMB, "ls_q_m": ("", ""), } self._vf0 = self._vf0b.copy() self._vf0["d2d"] = True # fwd-decl self.vfs = VFS(log_func, "", "", "", AXS(), {}) self.acct: dict[str, str] = {} # uname->pw self.iacct: dict[str, str] = {} # pw->uname self.ases: dict[str, str] = {} # uname->session self.sesa: dict[str, str] = {} # session->uname self.defpw: dict[str, str] = {} self.grps: dict[str, list[str]] = {} self.re_pwd: Optional[re.Pattern] = None self.cfg_files_loaded: list[str] = [] self.badcfg1 = False # all volumes observed since last restart self.idp_vols: dict[str, str] = {} # vpath->abspath # all users/groups observed since last restart self.idp_accs: dict[str, list[str]] = {} # username->groupnames self.idp_usr_gh: dict[str, str] = {} # username->group-header-value (cache) self.hid_cache: dict[str, str] = {} self.mutex = threading.Lock() self.reload() def log(self, msg: str, c: Union[int, str] = 0) -> None: if self.log_func: self.log_func("auth", msg, c) def laggy_iter(self, iterable: Iterable[Any]) -> Generator[Any, None, None]: it = iter(iterable) prev = next(it) for x in it: yield prev, False prev = x yield prev, True def vf0(self): return self._vf0.copy() def vf0b(self): return self._vf0b.copy() def idp_checkin( self, broker: Optional["BrokerCli"], uname: str, gname: str ) -> bool: if self.idp_usr_gh.get(uname) == gname: return False gnames = [x.strip() for x in self.args.idp_gsep.split(gname)] gnames.sort() with self.mutex: self.idp_usr_gh[uname] = gname if self.idp_accs.get(uname) == gnames: return False self.idp_accs[uname] = gnames try: self._update_idp_db(uname, gname) except: self.log("failed to update the --idp-db:\n%s" % (min_ex(),), 3) t = "reinitializing due to new user from IdP: [%r:%r]" self.log(t % (uname, gnames), 3) if not broker: # only true for tests self._reload() return True broker.ask("reload", False, True).get() return True def _update_idp_db(self, uname: str, gname: str) -> None: if not self.args.idp_store: return assert sqlite3 # type: ignore # !rm db = sqlite3.connect(self.args.idp_db) cur = db.cursor() cur.execute("delete from us where un = ?", (uname,)) cur.execute("insert into us values (?,?)", (uname, gname)) db.commit() cur.close() db.close() def _map_volume_idp( self, src: str, dst: str, mount: dict[str, tuple[str, str]], daxs: dict[str, AXS], mflags: dict[str, dict[str, Any]], un_gns: dict[str, list[str]], ) -> list[tuple[str, str, str, str]]: ret: list[tuple[str, str, str, str]] = [] visited = set() src0 = src # abspath dst0 = dst # vpath zsl = [] for ptn, sigil in ((PTN_U_ANY, "${u}"), (PTN_G_ANY, "${g}")): if bool(ptn.search(src)) != bool(ptn.search(dst)): zsl.append(sigil) if zsl: t = "ERROR: if %s is mentioned in a volume definition, it must be included in both the filesystem-path [%s] and the volume-url [/%s]" t = "\n".join([t % (x, src, dst) for x in zsl]) self.log(t, 1) raise Exception(t) un_gn = [(un, gn) for un, gns in un_gns.items() for gn in gns] if not un_gn: # ensure volume creation if there's no users un_gn = [("", "")] for un, gn in un_gn: rejected = False for ptn in [PTN_U_GRP, PTN_G_GRP]: m = ptn.search(dst0) if not m: continue zs = m.group(1) zs = zs.replace(",%+", "\n%+") zs = zs.replace(",%-", "\n%-") for rule in zs.split("\n"): gnc = rule[2:] if ptn == PTN_U_GRP: # is user member of group? hit = gnc in (un_gns.get(un) or []) else: # is it this specific group? hit = gn == gnc if rule.startswith("%+") != hit: rejected = True if rejected: continue if gn == self.args.grp_all: gn = "" # if ap/vp has a user/group placeholder, make sure to keep # track so the same user/group is mapped when setting perms; # otherwise clear un/gn to indicate it's a regular volume src1 = src0.replace("${u}", un or "\n") dst1 = dst0.replace("${u}", un or "\n") src1 = PTN_U_GRP.sub(un or "\n", src1) dst1 = PTN_U_GRP.sub(un or "\n", dst1) if src0 == src1 and dst0 == dst1: un = "" src = src1.replace("${g}", gn or "\n") dst = dst1.replace("${g}", gn or "\n") src = PTN_G_GRP.sub(gn or "\n", src) dst = PTN_G_GRP.sub(gn or "\n", dst) if src == src1 and dst == dst1: gn = "" if "\n" in (src + dst): continue label = "%s\n%s" % (src, dst) if label in visited: continue visited.add(label) src, dst = self._map_volume(src, dst, dst0, mount, daxs, mflags) if src: ret.append((src, dst, un, gn)) if un or gn: self.idp_vols[dst] = src return ret def _map_volume( self, src: str, dst: str, dst0: str, mount: dict[str, tuple[str, str]], daxs: dict[str, AXS], mflags: dict[str, dict[str, Any]], ) -> tuple[str, str]: src = os.path.expandvars(os.path.expanduser(src)) src = absreal(src) dst = dst.strip("/") if dst in mount: t = "multiple filesystem-paths mounted at [/{}]:\n [{}]\n [{}]" self.log(t.format(dst, mount[dst][0], src), c=1) raise Exception(BAD_CFG) if src in mount.values(): t = "filesystem-path [{}] mounted in multiple locations:" t = t.format(src) for v in [k for k, v in mount.items() if v[0] == src] + [dst]: t += "\n /{}".format(v) self.log(t, c=3) raise Exception(BAD_CFG) if not bos.path.exists(src): self.log("warning: filesystem-path did not exist: %r" % (src,), 3) vf = {} if dst.startswith(".") or "/." in dst: vf["unlistcr"] = True vf["unlistcw"] = True mount[dst] = (src, dst0) daxs[dst] = AXS() mflags[dst] = vf return (src, dst) def _e(self, desc: Optional[str] = None) -> None: if not self.args.vc or not self.line_ctr: return if not desc and not self.indent: self.log("") return desc = desc or "" desc = desc.replace("[", "[\033[0m").replace("]", "\033[90m]") self.log(" >>> {}{}".format(self.indent, desc), "90") def _l(self, ln: str, c: int, desc: str) -> None: if not self.args.vc or not self.line_ctr: return if c < 10: c += 30 t = "\033[97m{:4} \033[{}m{}{}" if desc: t += " \033[0;90m# {}\033[0m" desc = desc.replace("[", "[\033[0m").replace("]", "\033[90m]") self.log(t.format(self.line_ctr, c, self.indent, ln, desc)) def _all_un_gn( self, acct: dict[str, str], grps: dict[str, list[str]], ) -> dict[str, list[str]]: self.load_idp_db(bool(self.idp_accs)) ret = {un: gns[:] for un, gns in self.idp_accs.items()} ret.update({zs: [""] for zs in acct if zs not in ret}) grps[self.args.grp_all] = list(ret.keys()) for gn, uns in grps.items(): for un in uns: try: ret[un].append(gn) except: ret[un] = [gn] return ret def _parse_config_file( self, fp: str, cfg_lines: list[str], acct: dict[str, str], grps: dict[str, list[str]], daxs: dict[str, AXS], mflags: dict[str, dict[str, Any]], mount: dict[str, tuple[str, str]], ) -> None: self.line_ctr = 0 expand_config_file(self.log, cfg_lines, fp, "") if self.args.vc: lns = ["{:4}: {}".format(n, s) for n, s in enumerate(cfg_lines, 1)] self.log("expanded config file (unprocessed):\n" + "\n".join(lns)) cfg_lines = upgrade_cfg_fmt(self.log, self.args, cfg_lines, fp) # due to IdP, volumes must be parsed after users and groups; # do volumes in a 2nd pass to allow arbitrary order in config files for npass in range(1, 3): if self.args.vc: self.log("parsing config files; pass %d/%d" % (npass, 2)) self._parse_config_file_2(cfg_lines, acct, grps, daxs, mflags, mount, npass) def _parse_config_file_2( self, cfg_lines: list[str], acct: dict[str, str], grps: dict[str, list[str]], daxs: dict[str, AXS], mflags: dict[str, dict[str, Any]], mount: dict[str, tuple[str, str]], npass: int, ) -> None: self.line_ctr = 0 all_un_gn = self._all_un_gn(acct, grps) cat = "" catg = "[global]" cata = "[accounts]" catgrp = "[groups]" catx = "accs:" catf = "flags:" ap: Optional[str] = None vp: Optional[str] = None vols: list[tuple[str, str, str, str]] = [] for ln in cfg_lines: self.line_ctr += 1 ln = ln.split(" #")[0].strip() if not ln.split("#")[0].strip(): continue if re.match(r"^\[.*\]:$", ln): ln = ln[:-1] subsection = ln in (catx, catf) if ln.startswith("[") or subsection: self._e() if npass > 1 and ap is None and vp is not None: t = "the first line after [/{}] must be a filesystem path to share on that volume" raise Exception(t.format(vp)) cat = ln if not subsection: ap = vp = None self.indent = "" else: self.indent = " " if ln == catg: t = "begin commandline-arguments (anything from --help; dashes are optional)" self._l(ln, 6, t) elif ln == cata: self._l(ln, 5, "begin user-accounts section") elif ln == catgrp: self._l(ln, 5, "begin user-groups section") elif ln.startswith("[/"): vp = ln[1:-1].strip("/") self._l(ln, 2, "define volume at URL [/{}]".format(vp)) elif subsection: if ln == catx: self._l(ln, 5, "volume access config:") else: t = "volume-specific config (anything from --help-flags)" self._l(ln, 6, t) else: raise Exception("invalid section header" + SBADCFG) self.indent = " " if subsection else " " continue if cat == catg: self._l(ln, 6, "") zt = split_cfg_ln(ln) for zs, za in zt.items(): zs = zs.lstrip("-") if "=" in zs: t = "WARNING: found an option named [%s] in your [global] config; did you mean to say [%s: %s] instead?" zs1, zs2 = zs.split("=", 1) self.log(t % (zs, zs1, zs2), 1) if za is True: self._e("└─argument [{}]".format(zs)) else: self._e("└─argument [{}] with value [{}]".format(zs, za)) continue if cat == cata: try: u, p = [zs.strip() for zs in ln.split(":", 1)] if "=" in u and not p: t = "WARNING: found username [%s] in your [accounts] config; did you mean to say [%s: %s] instead?" zs1, zs2 = u.split("=", 1) self.log(t % (u, zs1, zs2), 3) self._l(ln, 5, "account [{}], password [{}]".format(u, p)) acct[u] = p except: t = 'lines inside the [accounts] section must be "username: password"' raise Exception(t + SBADCFG) continue if cat == catgrp: try: gn, zs1 = [zs.strip() for zs in ln.split(":", 1)] uns = [zs.strip() for zs in zs1.split(",")] t = "group [%s] = " % (gn,) t += ", ".join("user [%s]" % (x,) for x in uns) self._l(ln, 5, t) if gn in grps: grps[gn].extend(uns) else: grps[gn] = uns except: t = 'lines inside the [groups] section must be "groupname: user1, user2, user..."' raise Exception(t + SBADCFG) continue if vp is not None and ap is None: if npass != 2: continue ap = ln self._l(ln, 2, "bound to filesystem-path [{}]".format(ap)) vols = self._map_volume_idp(ap, vp, mount, daxs, mflags, all_un_gn) if not vols: ap = vp = None self._l(ln, 2, "└─no users/groups known; was not mapped") elif len(vols) > 1: for vol in vols: self._l(ln, 2, "└─mapping: [%s] => [%s]" % (vol[1], vol[0])) continue if cat == catx: if npass != 2 or not ap: # not stage2, or unmapped ${u}/${g} continue err = "" try: self._l(ln, 5, "volume access config:") sk, sv = ln.split(":") if re.sub("[rwmdgGhaA.]", "", sk) or not sk: err = "invalid accs permissions list; " raise Exception(err) if " " in re.sub(", *", "", sv).strip(): err = "list of users is not comma-separated; " raise Exception(err) sv = sv.replace(" ", "") self._read_vol_str_idp(sk, sv, vols, all_un_gn, daxs, mflags) continue except CfgEx: raise except: err += "accs entries must be 'rwmdgGhaA.: user1, user2, ...'" raise CfgEx(err + SBADCFG) if cat == catf: if npass != 2 or not ap: # not stage2, or unmapped ${u}/${g} continue err = "" try: self._l(ln, 6, "volume-specific config:") zd = split_cfg_ln(ln) fstr = "" for sk, sv in zd.items(): if "=" in sk: t = "WARNING: found a volflag named [%s] in your config; did you mean to say [%s: %s] instead?" zs1, zs2 = sk.split("=", 1) self.log(t % (sk, zs1, zs2), 3) bad = re.sub(r"[a-z0-9_-]", "", sk).lstrip("-") if bad: err = "bad characters [{}] in volflag name [{}]; " err = err.format(bad, sk) raise Exception(err + SBADCFG) if sv is True: fstr += "," + sk else: fstr += ",{}={}".format(sk, sv) assert vp is not None self._read_vol_str_idp( "c", fstr[1:], vols, all_un_gn, daxs, mflags ) fstr = "" if fstr: self._read_vol_str_idp( "c", fstr[1:], vols, all_un_gn, daxs, mflags ) continue except: err += "flags entries (volflags) must be one of the following:\n 'flag1, flag2, ...'\n 'key: value'\n 'flag1, flag2, key: value'" raise Exception(err + SBADCFG) raise Exception("unprocessable line in config" + SBADCFG) self._e() self.line_ctr = 0 def _read_vol_str_idp( self, lvl: str, uname: str, vols: list[tuple[str, str, str, str]], un_gns: dict[str, list[str]], axs: dict[str, AXS], flags: dict[str, dict[str, Any]], ) -> None: if lvl.strip("crwmdgGhaA."): t = "%s,%s" % (lvl, uname) if uname else lvl raise CfgEx("invalid config value (volume or volflag): %s" % (t,)) if lvl == "c": # here, 'uname' is not a username; it is a volflag name... sorry cval: Union[bool, str] = True try: # volflag with arguments, possibly with a preceding list of bools uname, cval = uname.split("=", 1) except: # just one or more bools pass while "," in uname: # one or more bools before the final flag; eat them n1, uname = uname.split(",", 1) for _, vp, _, _ in vols: self._read_volflag(vp, flags[vp], n1, True, False) for _, vp, _, _ in vols: self._read_volflag(vp, flags[vp], uname, cval, False) return if uname == "": uname = "*" unames = [] for un in uname.replace(",", " ").strip().split(): if un.startswith("@"): grp = un[1:] uns = [x[0] for x in un_gns.items() if grp in x[1]] if grp == "${g}": unames.append(un) elif not uns and not self.args.idp_h_grp and grp != self.args.grp_all: t = "group [%s] must be defined with --grp argument (or in a [groups] config section)" raise CfgEx(t % (grp,)) unames.extend(uns) else: unames.append(un) # unames may still contain ${u} and ${g} so now expand those; un_gn = [(un, gn) for un, gns in un_gns.items() for gn in gns] for src, dst, vu, vg in vols: unames2 = set(unames) if "${u}" in unames: if not vu: t = "cannot use ${u} in accs of volume [%s] because the volume url does not contain ${u}" raise CfgEx(t % (src,)) unames2.add(vu) if "@${g}" in unames: if not vg: t = "cannot use @${g} in accs of volume [%s] because the volume url does not contain @${g}" raise CfgEx(t % (src,)) unames2.update([un for un, gn in un_gn if gn == vg]) if "${g}" in unames: t = 'the accs of volume [%s] contains "${g}" but the only supported way of specifying that is "@${g}"' raise CfgEx(t % (src,)) unames2.discard("${u}") unames2.discard("@${g}") self._read_vol_str(lvl, list(unames2), axs[dst]) def _read_vol_str(self, lvl: str, unames: list[str], axs: AXS) -> None: junkset = set() for un in unames: for alias, mapping in [ ("h", "gh"), ("G", "gG"), ("A", "rwmda.A"), ]: expanded = "" for ch in mapping: if ch not in lvl: expanded += ch lvl = lvl.replace(alias, expanded + alias) for ch, al in [ ("r", axs.uread), ("w", axs.uwrite), ("m", axs.umove), ("d", axs.udel), (".", axs.udot), ("a", axs.uadmin), ("A", junkset), ("g", axs.uget), ("G", axs.upget), ("h", axs.uhtml), ]: if ch in lvl: if un == "*": t = "└─add permission [{0}] for [everyone] -- {2}" else: t = "└─add permission [{0}] for user [{1}] -- {2}" desc = permdescs.get(ch, "?") self._e(t.format(ch, un, desc)) al.add(un) def _read_volflag( self, vpath: str, flags: dict[str, Any], name: str, value: Union[str, bool, list[str]], is_list: bool, ) -> None: if name not in flagdescs: name = name.lower() # volflags are snake_case, but a leading dash is the removal operator stripped = name.lstrip("-") zi = len(name) - len(stripped) if zi > 1: t = "WARNING: the config for volume [/%s] specified a volflag with multiple leading hyphens (%s); use one hyphen to remove, or zero hyphens to add a flag. Will now enable flag [%s]" self.log(t % (vpath, name, stripped), 3) name = stripped zi = 0 if stripped not in flagdescs and "-" in stripped: name = ("-" * zi) + stripped.replace("-", "_") desc = flagdescs.get(name.lstrip("-"), "?").replace("\n", " ") if not name: self._e("└─unreadable-line") t = "WARNING: the config for volume [/%s] indicated that a volflag was to be defined, but the volflag name was blank" self.log(t % (vpath,), 3) return if re.match("^-[^-]+$", name): t = "└─unset volflag [{}] ({})" self._e(t.format(name[1:], desc)) flags[name] = True return zs = "ext_th landmark mtp on403 on404 xbu xau xiu xbc xac xbr xar xbd xad xm xban" if name not in zs.split(): if value is True: t = "└─add volflag [{}] = {} ({})" else: t = "└─add volflag [{}] = [{}] ({})" self._e(t.format(name, value, desc)) flags[name] = value return vals = flags.get(name, []) if not value: return elif is_list: vals += value else: vals += [value] flags[name] = vals self._e("volflag [{}] += {} ({})".format(name, vals, desc)) def reload(self, verbosity: int = 9) -> None: with self.mutex: self._reload(verbosity) def _reload(self, verbosity: int = 9) -> None: acct: dict[str, str] = {} # username:password grps: dict[str, list[str]] = {} # groupname:usernames daxs: dict[str, AXS] = {} mflags: dict[str, dict[str, Any]] = {} # vpath:flags mount: dict[str, tuple[str, str]] = {} # dst:src (vp:(ap,vp0)) cfg_files_loaded: list[str] = [] self.idp_vols = {} # yolo self.badcfg1 = False if self.args.a: # list of username:password for x in self.args.a: try: u, p = x.split(":", 1) acct[u] = p except: t = '\n invalid value "{}" for argument -a, must be username:password' raise Exception(t.format(x)) if self.args.grp: # list of groupname:username,username,... for x in self.args.grp: try: # accept both = and : as separator between groupname and usernames, # accept both , and : as separators between usernames zs1, zs2 = x.replace("=", ":").split(":", 1) grps[zs1] = zs2.replace(":", ",").split(",") grps[zs1] = [x.strip() for x in grps[zs1]] except: t = '\n invalid value "{}" for argument --grp, must be groupname:username1,username2,...' raise Exception(t.format(x)) if self.args.v: # list of src:dst:permset:permset:... # permset is <rwmdgGhaA.>[,username][,username] or <c>,<flag>[=args] all_un_gn = self._all_un_gn(acct, grps) for v_str in self.args.v: m = re_vol.match(v_str) if not m: raise Exception("invalid -v argument: [{}]".format(v_str)) src, dst, perms = m.groups() if WINDOWS: src = uncyg(src) vols = self._map_volume_idp(src, dst, mount, daxs, mflags, all_un_gn) for x in perms.split(":"): lvl, uname = x.split(",", 1) if "," in x else [x, ""] self._read_vol_str_idp(lvl, uname, vols, all_un_gn, daxs, mflags) if self.args.c: for cfg_fn in self.args.c: lns: list[str] = [] try: self._parse_config_file( cfg_fn, lns, acct, grps, daxs, mflags, mount ) zs = "#\033[36m cfg files in " zst = [x[len(zs) :] for x in lns if x.startswith(zs)] for zs in list(set(zst)): self.log("discovered config files in " + zs, 6) zs = "#\033[36m opening cfg file" zstt = [x.split(" -> ") for x in lns if x.startswith(zs)] zst = [(max(0, len(x) - 2) * " ") + "└" + x[-1] for x in zstt] t = "loaded {} config files:\n{}" self.log(t.format(len(zst), "\n".join(zst))) cfg_files_loaded = zst except: lns = lns[: self.line_ctr] slns = ["{:4}: {}".format(n, s) for n, s in enumerate(lns, 1)] t = "\033[1;31m\nerror @ line {}, included from {}\033[0m" t = t.format(self.line_ctr, cfg_fn) self.log("\n{0}\n{1}{0}".format(t, "\n".join(slns))) raise derive_args(self.args) self.setup_auth_ord() if self.args.ipu and not self.args.have_idp_hdrs: # syntax (CIDR=UNAME) is verified in load_ipu zsl = [x.split("=", 1)[1] for x in self.args.ipu] zsl = [x for x in zsl if x and x not in acct] if zsl: t = "ERROR: unknown users in ipu: %s" % (zsl,) self.log(t, 1) raise Exception(t) self.setup_pwhash(acct) defpw = acct.copy() self.setup_chpw(acct) # case-insensitive; normalize if WINDOWS: cased = {} for vp, (ap, vp0) in mount.items(): cased[vp] = (absreal(ap), vp0) mount = cased if not mount and not self.args.have_idp_hdrs: # -h says our defaults are CWD at root and read/write for everyone axs = AXS(["*"], ["*"], None, None) ehint = "" if self.is_lxc: t = "Read-access has been disabled due to failsafe: Docker detected, but %s. This failsafe is to prevent unintended access if this is due to accidental loss of config. You can override this safeguard and allow read/write to all of /w/ by adding the following arguments to the docker container: -v .::rw" if len(cfg_files_loaded) == 1: self.log(t % ("no config-file was provided",), 1) t = "it is strongly recommended to add a config-file instead, for example based on https://github.com/9001/copyparty/blob/hovudstraum/docs/examples/docker/basic-docker-compose/copyparty.conf" self.log(t, 3) else: self.log(t % ("the config does not define any volumes",), 1) axs = AXS() ehint = "; please try moving them up one level, into the parent folder:" elif self.args.c: t = "Read-access has been disabled due to failsafe: No volumes were defined by the config-file. This failsafe is to prevent unintended access if this is due to accidental loss of config. You can override this safeguard and allow read/write to the working-directory by adding the following arguments: -v .::rw" self.log(t, 1) axs = AXS() ehint = ":" if ehint: try: files = os.listdir(E.cfg) except: files = [] hits = [ x for x in files if x.lower().endswith(".conf") and not x.startswith(".") ] if hits: t = "Hint: Found some config files in [%s], but these were not automatically loaded because they are in the wrong place%s %s\n" self.log(t % (E.cfg, ehint, ", ".join(hits)), 3) vfs = VFS(self.log_func, absreal("."), "", "", axs, self.vf0b()) if not axs.uread: self.badcfg1 = True elif "" not in mount: # there's volumes but no root; make root inaccessible vfs = VFS(self.log_func, "", "", "", AXS(), self.vf0()) maxdepth = 0 for dst in sorted(mount.keys(), key=lambda x: (x.count("/"), len(x))): depth = dst.count("/") assert maxdepth <= depth # nosec maxdepth = depth src, dst0 = mount[dst] if dst == "": # rootfs was mapped; fully replaces the default CWD vfs vfs = VFS(self.log_func, src, dst, dst0, daxs[dst], mflags[dst]) continue assert vfs # type: ignore zv = vfs.add(src, dst, dst0) zv.axs = daxs[dst] zv.flags = mflags[dst] zv.dbv = None assert vfs # type: ignore vfs.all_vols = {} vfs.all_nodes = {} vfs.all_aps = [] vfs.all_vps = [] vfs.get_all_vols(vfs.all_vols, vfs.all_nodes, vfs.all_aps, vfs.all_vps) for vol in vfs.all_nodes.values(): vol.all_aps.sort(key=lambda x: len(x[0]), reverse=True) vol.all_vps.sort(key=lambda x: len(x[0]), reverse=True) vol.root = vfs zs = "du_iwho emb_all ls_q_m neversymlink" k_ign = set(zs.split()) for vol in vfs.all_vols.values(): unknown_flags = set() for k, v in vol.flags.items(): ks = k.lstrip("-") if ks not in flagdescs and ks not in k_ign: unknown_flags.add(k) if unknown_flags: t = "WARNING: the config for volume [/%s] has unrecognized volflags; will ignore: '%s'" self.log(t % (vol.vpath, "', '".join(unknown_flags)), 3) enshare = self.args.shr shr = enshare[1:-1] shrs = enshare[1:] if enshare: assert sqlite3 # type: ignore # !rm shv = VFS(self.log_func, "", shr, shr, AXS(), self.vf0()) db_path = self.args.shr_db db = sqlite3.connect(db_path) cur = db.cursor() cur2 = db.cursor() now = time.time() for row in cur.execute("select * from sh"): s_k, s_pw, s_vp, s_pr, s_nf, s_un, s_t0, s_t1 = row if s_t1 and s_t1 < now: continue if self.args.shr_v: t = "loading %s share %r by %r => %r" self.log(t % (s_pr, s_k, s_un, s_vp)) if s_pw: # gotta reuse the "account" for all shares with this pw, # so do a light scramble as this appears in the web-ui zb = hashlib.sha512(s_pw.encode("utf-8")).digest() sun = "s_%s" % (ub64enc(zb)[4:16].decode("ascii"),) acct[sun] = s_pw else: sun = "*" s_axs = AXS( [sun] if "r" in s_pr else [], [sun] if "w" in s_pr else [], [sun] if "m" in s_pr else [], [sun] if "d" in s_pr else [], [sun] if "g" in s_pr else [], ) # don't know the abspath yet + wanna ensure the user # still has the privs they granted, so nullmap it vp = "%s/%s" % (shr, s_k) shv.nodes[s_k] = VFS(self.log_func, "", vp, vp, s_axs, shv.flags.copy()) vfs.nodes[shr] = vfs.all_vols[shr] = shv for vol in shv.nodes.values(): vfs.all_vols[vol.vpath] = vfs.all_nodes[vol.vpath] = vol vol.get_dbv = vol._get_share_src vol.ls = vol._ls_nope zss = set(acct) zss.update(self.idp_accs) zss.discard("*") unames = ["*"] + list(sorted(zss)) for perm in "read write move del get pget html admin dot".split(): axs_key = "u" + perm for vp, vol in vfs.all_vols.items(): zx = getattr(vol.axs, axs_key) if "*" in zx and "-@acct" not in zx: for usr in unames: zx.add(usr) for zs in list(zx): if zs.startswith("-"): zx.discard(zs) zs = zs[1:] zx.discard(zs) if zs.startswith("@"): zs = zs[1:] for zs in grps.get(zs) or []: zx.discard(zs) # aread,... = dict[uname, list[volnames] or []] umap: dict[str, list[str]] = {x: [] for x in unames} for usr in unames: for vp, vol in vfs.all_vols.items(): zx = getattr(vol.axs, axs_key) if usr in zx and (not enshare or not vp.startswith(shrs)): umap[usr].append(vp) umap[usr].sort() setattr(vfs, "a" + perm, umap) for vol in vfs.all_nodes.values(): za = vol.axs vol.uaxs = { un: ( un in za.uread, un in za.uwrite, un in za.umove, un in za.udel, un in za.uget, un in za.upget, un in za.uhtml, un in za.uadmin, un in za.udot, ) for un in unames } all_users = {} missing_users = {} associated_users = {} for axs in daxs.values(): for d in [ axs.uread, axs.uwrite, axs.umove, axs.udel, axs.uget, axs.upget, axs.uhtml, axs.uadmin, axs.udot, ]: for usr in d: all_users[usr] = 1 if usr != "*" and usr not in acct and usr not in self.idp_accs: missing_users[usr] = 1 if "*" not in d: associated_users[usr] = 1 if missing_users: zs = ", ".join(k for k in sorted(missing_users)) if self.args.have_idp_hdrs: t = "the following users are unknown, and assumed to come from IdP: " self.log(t + zs, c=6) else: t = "you must -a the following users: " self.log(t + zs, c=1) raise Exception(BAD_CFG) if LEELOO_DALLAS in all_users: raise Exception("sorry, reserved username: " + LEELOO_DALLAS) zsl = [] for usr in list(acct)[:]: zs = acct[usr].strip() if not zs: zs = ub64enc(os.urandom(48)).decode("ascii") zsl.append(usr) acct[usr] = zs if zsl: self.log("generated random passwords for users %r" % (zsl,), 6) seenpwds = {} for usr, pwd in acct.items(): if pwd in seenpwds: t = "accounts [{}] and [{}] have the same password; this is not supported" self.log(t.format(seenpwds[pwd], usr), 1) raise Exception(BAD_CFG) seenpwds[pwd] = usr for usr in acct: if usr not in associated_users: if enshare and usr.startswith("s_"): continue if len(vfs.all_vols) > 1: # user probably familiar enough that the verbose message is not necessary t = "account [%s] is not mentioned in any volume definitions; see --help-accounts" self.log(t % (usr,), 1) else: t = "WARNING: the account [%s] is not mentioned in any volume definitions and thus has the same access-level and privileges that guests have; please see --help-accounts for details. For example, if you intended to give that user full access to the current directory, you could do this: -v .::A,%s" self.log(t % (usr, usr), 1) dropvols = [] errors = False for vol in vfs.all_vols.values(): if ( not vol.realpath or ( "assert_root" not in vol.flags and "nospawn" not in vol.flags and not self.args.vol_or_crash and not self.args.vol_nospawn ) or bos.path.exists(vol.realpath) ): pass elif "assert_root" in vol.flags or self.args.vol_or_crash: t = "ERROR: volume [/%s] root folder %r does not exist on server HDD; will now crash due to volflag 'assert_root'" self.log(t % (vol.vpath, vol.realpath), 1) errors = True else: t = "WARNING: volume [/%s] root folder %r does not exist on server HDD; volume will be unavailable due to volflag 'nospawn'" self.log(t % (vol.vpath, vol.realpath), 3) dropvols.append(vol) if errors: sys.exit(1) for vol in dropvols: vol.axs = AXS() vol.uaxs = {} vfs.all_vols.pop(vol.vpath, None) vfs.all_nodes.pop(vol.vpath, None) for zv in vfs.all_nodes.values(): try: zv.all_aps.remove(vol.realpath) zv.all_vps.remove(vol.vpath) # pointless but might as well: zv.all_vols.pop(vol.vpath) zv.all_nodes.pop(vol.vpath) except: pass zs = next((x for x, y in zv.nodes.items() if y == vol), "") if zs: zv.nodes.pop(zs) vol.realpath = "" promote = [] demote = [] for vol in vfs.all_vols.values(): if not vol.realpath: continue hid = self.hid_cache.get(vol.realpath) if not hid: zb = hashlib.sha512(afsenc(vol.realpath)).digest() hid = base64.b32encode(zb).decode("ascii").lower() self.hid_cache[vol.realpath] = hid vflag = vol.flags.get("hist") if vflag == "-": pass elif vflag: vflag = os.path.expandvars(os.path.expanduser(vflag)) vol.histpath = vol.dbpath = uncyg(vflag) if WINDOWS else vflag elif self.args.hist: for nch in range(len(hid)): hpath = os.path.join(self.args.hist, hid[: nch + 1]) bos.makedirs(hpath) powner = os.path.join(hpath, "owner.txt") try: with open(powner, "rb") as f: owner = f.read().rstrip() except: owner = None me = afsenc(vol.realpath).rstrip() if owner not in [None, me]: continue if owner is None: with open(powner, "wb") as f: f.write(me) vol.histpath = vol.dbpath = hpath break vol.histpath = absreal(vol.histpath) for vol in vfs.all_vols.values(): if not vol.realpath: continue hid = self.hid_cache[vol.realpath] vflag = vol.flags.get("dbpath") if vflag == "-": pass elif vflag: vflag = os.path.expandvars(os.path.expanduser(vflag)) vol.dbpath = uncyg(vflag) if WINDOWS else vflag elif self.args.dbpath: for nch in range(len(hid)): hpath = os.path.join(self.args.dbpath, hid[: nch + 1]) bos.makedirs(hpath) powner = os.path.join(hpath, "owner.txt") try: with open(powner, "rb") as f: owner = f.read().rstrip() except: owner = None me = afsenc(vol.realpath).rstrip() if owner not in [None, me]: continue if owner is None: with open(powner, "wb") as f: f.write(me) vol.dbpath = hpath break vol.dbpath = absreal(vol.dbpath) if vol.dbv: if bos.path.exists(os.path.join(vol.dbpath, "up2k.db")): promote.append(vol) vol.dbv = None else: demote.append(vol) # discard jump-vols for zv in demote: vfs.all_vols.pop(zv.vpath) if promote: ta = [ "\n the following jump-volumes were generated to assist the vfs.\n As they contain a database (probably from v0.11.11 or older),\n they are promoted to full volumes:" ] for vol in promote: ta.append(" /%s (%s) (%s)" % (vol.vpath, vol.realpath, vol.dbpath)) self.log("\n\n".join(ta) + "\n", c=3) rhisttab = {} vfs.histtab = {} for zv in vfs.all_vols.values(): histp = zv.histpath is_shr = shr and zv.vpath.split("/")[0] == shr if histp and not is_shr and histp in rhisttab: zv2 = rhisttab[histp] t = "invalid config; multiple volumes share the same histpath (database+thumbnails location):\n histpath: %s\n volume 1: /%s [%s]\n volume 2: /%s [%s]" t = t % (histp, zv2.vpath, zv2.realpath, zv.vpath, zv.realpath) self.log(t, 1) raise Exception(t) rhisttab[histp] = zv vfs.histtab[zv.realpath] = histp rdbpaths = {} vfs.dbpaths = {} for zv in vfs.all_vols.values(): dbp = zv.dbpath is_shr = shr and zv.vpath.split("/")[0] == shr if dbp and not is_shr and dbp in rdbpaths: zv2 = rdbpaths[dbp] t = "invalid config; multiple volumes share the same dbpath (database location):\n dbpath: %s\n volume 1: /%s [%s]\n volume 2: /%s [%s]" t = t % (dbp, zv2.vpath, zv2.realpath, zv.vpath, zv.realpath) self.log(t, 1) raise Exception(t) rdbpaths[dbp] = zv vfs.dbpaths[zv.realpath] = dbp for vol in vfs.all_vols.values(): use = False for k in ["zipmaxn", "zipmaxs"]: try: zs = vol.flags[k] except: zs = getattr(self.args, k) if zs in ("", "0"): vol.flags[k] = 0 continue zf = unhumanize(zs) vol.flags[k + "_v"] = zf if zf: use = True if use: vol.flags["zipmax"] = True for vol in vfs.all_vols.values(): lim = Lim(self.args, self.log_func) use = False if vol.flags.get("nosub"): use = True lim.nosub = True zs = vol.flags.get("df") or self.args.df or "" if zs not in ("", "0"): use = True try: _ = float(zs) zs = "%sg" % (zs,) except: pass lim.dfl = unhumanize(zs) zs = vol.flags.get("sz") if zs: use = True lim.smin, lim.smax = [unhumanize(x) for x in zs.split("-")] zs = vol.flags.get("rotn") if zs: use = True lim.rotn, lim.rotl = [int(x) for x in zs.split(",")] zs = vol.flags.get("rotf") if zs: use = True lim.set_rotf(zs, vol.flags.get("rotf_tz") or "UTC") zs = vol.flags.get("maxn") if zs: use = True lim.nmax, lim.nwin = [int(x) for x in zs.split(",")] zs = vol.flags.get("maxb") if zs: use = True lim.bmax, lim.bwin = [unhumanize(x) for x in zs.split(",")] zs = vol.flags.get("vmaxb") if zs: use = True lim.vbmax = unhumanize(zs) zs = vol.flags.get("vmaxn") if zs: use = True lim.vnmax = unhumanize(zs) if use: vol.lim = lim if self.args.no_robots: for vol in vfs.all_nodes.values(): # volflag "robots" overrides global "norobots", allowing indexing by search engines for this vol if not vol.flags.get("robots"): vol.flags["norobots"] = True for vol in vfs.all_nodes.values(): if self.args.no_vthumb: vol.flags["dvthumb"] = True if self.args.no_athumb: vol.flags["dathumb"] = True if self.args.no_thumb or vol.flags.get("dthumb", False): vol.flags["dthumb"] = True vol.flags["dvthumb"] = True vol.flags["dathumb"] = True vol.flags["dithumb"] = True have_fk = False for vol in vfs.all_nodes.values(): fk = vol.flags.get("fk") fka = vol.flags.get("fka") if fka and not fk: fk = fka if fk: fk = 8 if fk is True else int(fk) if fk > 72: t = "max filekey-length is 72; volume /%s specified %d (anything higher than 16 is pointless btw)" raise Exception(t % (vol.vpath, fk)) vol.flags["fk"] = fk have_fk = True dk = vol.flags.get("dk") dks = vol.flags.get("dks") dky = vol.flags.get("dky") if dks is not None and dky is not None: t = "WARNING: volume /%s has both dks and dky enabled; this is too yolo and not permitted" raise Exception(t % (vol.vpath,)) if dks and not dk: dk = dks if dky and not dk: dk = dky if dk: vol.flags["dk"] = int(dk) if dk is not True else 8 if have_fk and re.match(r"^[0-9\.]+$", self.args.fk_salt): self.log("filekey salt: {}".format(self.args.fk_salt)) fk_len = len(self.args.fk_salt) if have_fk and fk_len < 14: t = "WARNING: filekeys are enabled, but the salt is only %d chars long; %d or longer is recommended. Either specify a stronger salt using --fk-salt or delete this file and restart copyparty: %s" zs = os.path.join(E.cfg, "fk-salt.txt") self.log(t % (fk_len, 16, zs), 3) for vol in vfs.all_nodes.values(): if "pk" in vol.flags and "gz" not in vol.flags and "xz" not in vol.flags: vol.flags["gz"] = False # def.pk if "scan" in vol.flags: vol.flags["scan"] = int(vol.flags["scan"]) elif self.args.re_maxage: vol.flags["scan"] = self.args.re_maxage self.args.have_unlistc = False all_mte = {} errors = False free_umask = False have_reflink = False for vol in vfs.all_nodes.values(): if os.path.isfile(vol.realpath): vol.flags["is_file"] = True vol.flags["d2d"] = True if (self.args.e2ds and vol.axs.uwrite) or self.args.e2dsa: vol.flags["e2ds"] = True if self.args.e2d or "e2ds" in vol.flags: vol.flags["e2d"] = True for ga, vf in [ ["no_hash", "nohash"], ["no_idx", "noidx"], ["og_ua", "og_ua"], ["srch_excl", "srch_excl"], ]: if vf in vol.flags: ptn = re.compile(vol.flags.pop(vf)) else: ptn = getattr(self.args, ga) if ptn: vol.flags[vf] = ptn for ga, vf in vf_bmap().items(): if getattr(self.args, ga): vol.flags[vf] = True for ve, vd in ( ("nodotsrch", "dotsrch"), ("sb_lg", "no_sb_lg"), ("sb_md", "no_sb_md"), ): if ve in vol.flags: vol.flags.pop(vd, None) for ga, vf in vf_vmap().items(): if vf not in vol.flags: vol.flags[vf] = getattr(self.args, ga) zs = "forget_ip gid nrand tail_who th_qv th_qvx th_spec_p u2abort u2ow uid unp_who ups_who zip_who" for k in zs.split(): if k in vol.flags: vol.flags[k] = int(vol.flags[k]) zs = "aconvt convt tail_fd tail_rate tail_tmax" for k in zs.split(): if k in vol.flags: vol.flags[k] = float(vol.flags[k]) for k in ("mv_re", "rm_re"): try: zs1, zs2 = vol.flags[k + "try"].split("/") vol.flags[k + "_t"] = float(zs1) vol.flags[k + "_r"] = float(zs2) except: t = 'volume "/%s" has invalid %stry [%s]' raise Exception(t % (vol.vpath, k, vol.flags.get(k + "try"))) for k in ("chmod_d", "chmod_f"): is_d = k == "chmod_d" zs = vol.flags.get(k, "") if not zs and is_d: zs = "755" if not zs: vol.flags.pop(k, None) continue if not re.match("^[0-7]{3,4}$", zs): t = "config-option '%s' must be a three- or four-digit octal value such as [0755] or [644] but the value was [%s]" t = t % (k, zs) self.log(t, 1) raise Exception(t) zi = int(zs, 8) vol.flags[k] = zi if (is_d and zi != 0o755) or not is_d: free_umask = True vol.flags.pop("chown", None) if vol.flags["uid"] != -1 or vol.flags["gid"] != -1: vol.flags["chown"] = True vol.flags.pop("fperms", None) if "chown" in vol.flags or vol.flags.get("chmod_f"): vol.flags["fperms"] = True if vol.lim: vol.lim.chmod_d = vol.flags["chmod_d"] vol.lim.chown = "chown" in vol.flags vol.lim.uid = vol.flags["uid"] vol.lim.gid = vol.flags["gid"] vol.flags["du_iwho"] = n_du_who(vol.flags["du_who"]) if not enshare: vol.flags["shr_who"] = self.args.shr_who = "no" if vol.flags.get("og"): self.args.uqe = True if "unlistcr" in vol.flags or "unlistcw" in vol.flags: self.args.have_unlistc = True if "reflink" in vol.flags: have_reflink = True zs = str(vol.flags.get("tcolor", "")).lstrip("#") if len(zs) == 3: # fc5 => ffcc55 vol.flags["tcolor"] = "".join([x * 2 for x in zs]) # volflag syntax currently doesn't allow for ':' in value zs = vol.flags["put_name"] vol.flags["put_name2"] = zs.replace("{now.", "{now:.") if vol.flags.get("neversymlink"): vol.flags["hardlinkonly"] = True # was renamed if vol.flags.get("hardlinkonly"): vol.flags["hardlink"] = True for k1, k2 in IMPLICATIONS: if k1 in vol.flags: vol.flags[k2] = True for k1, k2 in UNPLICATIONS: if k1 in vol.flags: vol.flags[k2] = False dbds = "acid|swal|wal|yolo" vol.flags["dbd"] = dbd = vol.flags.get("dbd") or self.args.dbd if dbd not in dbds.split("|"): t = 'volume "/%s" has invalid dbd [%s]; must be one of [%s]' raise Exception(t % (vol.vpath, dbd, dbds)) # default tag cfgs if unset for k in ("mte", "mth", "exp_md", "exp_lg"): if k not in vol.flags: vol.flags[k] = getattr(self.args, k).copy() else: vol.flags[k] = odfusion(getattr(self.args, k), vol.flags[k]) # append additive args from argv to volflags hooks = "xbu xau xiu xbc xac xbr xar xbd xad xm xban".split() for name in "ext_th mtp on404 on403".split() + hooks: self._read_volflag( vol.vpath, vol.flags, name, getattr(self.args, name), True ) for hn in hooks: cmds = vol.flags.get(hn) if not cmds: continue ncmds = [] for cmd in cmds: hfs = [] ocmd = cmd while "," in cmd[:6]: zs, cmd = cmd.split(",", 1) hfs.append(zs) if "c" in hfs and "f" in hfs: t = "cannot combine flags c and f; removing f from eventhook [{}]" self.log(t.format(ocmd), 1) hfs = [x for x in hfs if x != "f"] ocmd = ",".join(hfs + [cmd]) if "c" not in hfs and "f" not in hfs and hn == "xban": hfs = ["c"] + hfs ocmd = ",".join(hfs + [cmd]) ncmds.append(ocmd) vol.flags[hn] = ncmds ext_th = vol.flags["ext_th_d"] = {} etv = "(?)" try: for etv in vol.flags.get("ext_th") or []: k, v = etv.split("=") ext_th[k] = v except: t = "WARNING: volume [/%s]: invalid value specified for ext-th: %s" self.log(t % (vol.vpath, etv), 3) zsl = [x.strip() for x in vol.flags["rw_edit"].split(",")] zsl = [x for x in zsl if x] vol.flags["rw_edit"] = ",".join(zsl) vol.flags["rw_edit_set"] = set(x for x in zsl if x) emb_all = vol.flags["emb_all"] = set() zsl1 = [x for x in vol.flags["preadmes"].split(",") if x] zsl2 = [x for x in vol.flags["readmes"].split(",") if x] zsl3 = list(set([x.lower() for x in zsl1])) zsl4 = list(set([x.lower() for x in zsl2])) emb_all.update(zsl3) emb_all.update(zsl4) vol.flags["emb_mds"] = [[0, zsl1, zsl3], [1, zsl2, zsl4]] zsl1 = [x for x in vol.flags["prologues"].split(",") if x] zsl2 = [x for x in vol.flags["epilogues"].split(",") if x] zsl3 = list(set([x.lower() for x in zsl1])) zsl4 = list(set([x.lower() for x in zsl2])) emb_all.update(zsl3) emb_all.update(zsl4) vol.flags["emb_lgs"] = [[0, zsl1, zsl3], [1, zsl2, zsl4]] zs = str(vol.flags.get("html_head") or "") if zs and zs[:1] in "%@": vol.flags["html_head_d"] = zs head_s = str(vol.flags.get("html_head_s") or "") else: zs2 = str(vol.flags.get("html_head_s") or "") if zs2 and zs: head_s = "%s\n%s\n" % (zs2.strip(), zs.strip()) else: head_s = zs2 or zs if head_s and not head_s.endswith("\n"): head_s += "\n" zs = "X-Content-Type-Options: nosniff\r\n" if "norobots" in vol.flags: head_s += META_NOBOTS zs += "X-Robots-Tag: noindex, nofollow\r\n" if self.args.http_vary: zs += "Vary: %s\r\n" % (self.args.http_vary,) vol.flags["oh_g"] = zs + "\r\n" if "noscript" in vol.flags: zs += "Content-Security-Policy: script-src 'none';\r\n" vol.flags["oh_f"] = zs + "\r\n" ico_url = vol.flags.get("ufavico") if ico_url: ico_h = "" ico_ext = ico_url.split("?")[0].split(".")[-1].lower() if ico_ext in FAVICON_MIMES: zs = '<link rel="icon" type="%s" href="%s">\n' ico_h = zs % (FAVICON_MIMES[ico_ext], ico_url) elif ico_ext == "ico": zs = '<link rel="shortcut icon" href="%s">\n' ico_h = zs % (ico_url,) if ico_h: vol.flags["ufavico_h"] = ico_h head_s += ico_h if head_s: vol.flags["html_head_s"] = head_s else: vol.flags.pop("html_head_s", None) if not vol.flags.get("html_head_d"): vol.flags.pop("html_head_d", None) vol.check_landmarks() if vol.flags.get("db_xattr"): self.args.have_db_xattr = True zs = str(vol.flags["db_xattr"]) neg = zs.startswith("~~") if neg: zs = zs[2:] zsl = [x.strip() for x in zs.split(",")] zsl = [x for x in zsl if x] if neg: vol.flags["db_xattr_no"] = set(zsl) else: vol.flags["db_xattr_yes"] = zsl # d2d drops all database features for a volume for grp, rm in [["d2d", "e2d"], ["d2t", "e2t"], ["d2d", "e2v"]]: if not vol.flags.get(grp, False): continue vol.flags["d2t"] = True vol.flags = {k: v for k, v in vol.flags.items() if not k.startswith(rm)} # d2ds drops all onboot scans for a volume for grp, rm in [["d2ds", "e2ds"], ["d2ts", "e2ts"]]: if not vol.flags.get(grp, False): continue vol.flags["d2ts"] = True vol.flags = {k: v for k, v in vol.flags.items() if not k.startswith(rm)} # mt* needs e2t so drop those too for grp, rm in [["e2t", "mt"]]: if vol.flags.get(grp, False): continue vol.flags = { k: v for k, v in vol.flags.items() if not k.startswith(rm) or k == "mte" } for grp, rm in [["d2v", "e2v"]]: if not vol.flags.get(grp, False): continue vol.flags = {k: v for k, v in vol.flags.items() if not k.startswith(rm)} ints = ["lifetime"] for k in list(vol.flags): if k in ints: vol.flags[k] = int(vol.flags[k]) if "e2d" not in vol.flags: zs = "lifetime rss" drop = [x for x in zs.split() if x in vol.flags] zs = "xau xiu" drop += [x for x in zs.split() if vol.flags.get(x)] for k in drop: t = 'cannot enable [%s] for volume "/%s" because this requires one of the following: e2d / e2ds / e2dsa (either as volflag or global-option)' self.log(t % (k, vol.vpath), 1) vol.flags.pop(k) zi = vol.flags.get("lifetime") or 0 zi2 = time.time() // (86400 * 365) zi3 = zi2 * 86400 * 365 if zi < 0 or zi > zi3: t = "the lifetime of volume [/%s] (%d) exceeds max value (%d years; %d)" t = t % (vol.vpath, zi, zi2, zi3) self.log(t, 1) raise Exception(t) if ( "dedup" in vol.flags and "reflink" not in vol.flags and vol.flags["apnd_who"] != "no" ): vol.flags["apnd_who"] = "ndd" # verify tags mentioned by -mt[mp] are used by -mte local_mtp = {} local_only_mtp = {} tags = vol.flags.get("mtp", []) + vol.flags.get("mtm", []) tags = [x.split("=")[0] for x in tags] tags = [y for x in tags for y in x.split(",")] for a in tags: local_mtp[a] = True local = True for b in self.args.mtp or []: b = b.split("=")[0] if a == b: local = False if local: local_only_mtp[a] = True local_mte = ODict() for a in vol.flags.get("mte", {}).keys(): local = True all_mte[a] = True local_mte[a] = True for b in self.args.mte.keys(): if not a or not b: continue if a == b: local = False for mtp in local_only_mtp: if mtp not in local_mte: t = 'volume "/{}" defines metadata tag "{}", but doesnt use it in "-mte" (or with "cmte" in its volflags)' self.log(t.format(vol.vpath, mtp), 1) errors = True mte = vol.flags.get("mte") or {} up_m = [x for x in UP_MTE_MAP if x in mte] up_q = [UP_MTE_MAP[x] for x in up_m] zs = "select %s from up where rd=? and fn=?" % (", ".join(up_q),) vol.flags["ls_q_m"] = (zs if up_m else "", up_m) vfs.all_fvols = { zs: vol for zs, vol in vfs.all_vols.items() if "is_file" in vol.flags } for vol in vfs.all_nodes.values(): if not vol.flags.get("is_file"): continue zs = "og opds xlink" for zs in zs.split(): vol.flags.pop(zs, None) for vol in vfs.all_vols.values(): if not vol.realpath or vol.flags.get("is_file"): continue ccs = vol.flags["casechk"][:1].lower() if ccs in ("y", "n"): if ccs == "y": vol.flags["bcasechk"] = True continue try: bos.makedirs(vol.realpath, vf=vol.flags) files = os.listdir(vol.realpath) for fn in files: fn2 = fn.lower() if fn == fn2: fn2 = fn.upper() if fn == fn2 or fn2 in files: continue is_ci = os.path.exists(os.path.join(vol.realpath, fn2)) ccs = "y" if is_ci else "n" break if ccs not in ("y", "n"): ap = os.path.join(vol.realpath, "casechk") open(ap, "wb").close() ccs = "y" if os.path.exists(ap[:-1] + "K") else "n" os.unlink(ap) except Exception as ex: if ANYWIN: zs = "Windows" ccs = "y" elif MACOS: zs = "Macos" ccs = "y" else: zs = "Linux" ccs = "n" t = "unable to determine if filesystem at %r is case-insensitive due to %r; assuming casechk=%s due to %s" self.log(t % (vol.realpath, ex, ccs, zs), 3) vol.flags["casechk"] = ccs if ccs == "y": vol.flags["bcasechk"] = True tags = self.args.mtp or [] tags = [x.split("=")[0] for x in tags] tags = [y for x in tags for y in x.split(",")] for mtp in tags: if mtp not in all_mte: t = 'metadata tag "{}" is defined by "-mtm" or "-mtp", but is not used by "-mte" (or by any "cmte" volflag)' self.log(t.format(mtp), 1) errors = True for vol in vfs.all_vols.values(): re1: Optional[re.Pattern] = vol.flags.get("srch_excl") excl = [re1.pattern] if re1 else [] vpaths = [] vtop = vol.vpath for vp2 in vfs.all_vols.keys(): if vp2.startswith((vtop + "/").lstrip("/")) and vtop != vp2: vpaths.append(re.escape(vp2[len(vtop) :].lstrip("/"))) if vpaths: excl.append("^(%s)/" % ("|".join(vpaths),)) vol.flags["srch_re_dots"] = re.compile("|".join(excl or ["^$"])) excl.extend([r"^\.", r"/\."]) vol.flags["srch_re_nodot"] = re.compile("|".join(excl)) have_daw = False for vol in vfs.all_nodes.values(): daw = vol.flags.get("daw") or self.args.daw if daw: vol.flags["daw"] = True have_daw = True if have_daw and self.args.no_dav: t = 'volume "/{}" has volflag "daw" (webdav write-access), but --no-dav is set' self.log(t, 1) errors = True if self.args.smb and self.ah.on and acct: self.log("--smb can only be used when --ah-alg is none", 1) errors = True for vol in vfs.all_nodes.values(): for k in list(vol.flags.keys()): if re.match("^-[^-]+$", k): vol.flags.pop(k) zs = k[1:] if zs in vol.flags: vol.flags.pop(k[1:]) else: t = "WARNING: the config for volume [/%s] tried to remove volflag [%s] by specifying [%s] but that volflag was not already set" self.log(t % (vol.vpath, zs, k), 3) if vol.flags.get("dots"): for name in vol.axs.uread: vol.axs.udot.add(name) if errors: sys.exit(1) setattr(self.args, "free_umask", free_umask) if free_umask: os.umask(0) vfs.bubble_flags() have_e2d = False have_e2t = False have_dedup = False have_symdup = False unsafe_dedup = [] t = "volumes and permissions:\n" for zv in vfs.all_vols.values(): if not self.warn_anonwrite or verbosity < 5: break if enshare and (zv.vpath == shr or zv.vpath.startswith(shrs)): continue t += '\n\033[36m"/{}" \033[33m{}\033[0m'.format(zv.vpath, zv.realpath) for txt, attr in [ [" read", "uread"], [" write", "uwrite"], [" move", "umove"], ["delete", "udel"], [" dots", "udot"], [" get", "uget"], [" upGet", "upget"], [" html", "uhtml"], ["uadmin", "uadmin"], ]: u = list(sorted(getattr(zv.axs, attr))) if u == ["*"] and acct: u = ["\033[35monly-anonymous\033[0m"] elif "*" in u: u = ["\033[35meverybody\033[0m"] if not u: u = ["\033[36m--none--\033[0m"] u = ", ".join(u) t += "\n| {}: {}".format(txt, u) if "e2d" in zv.flags: have_e2d = True if "e2t" in zv.flags: have_e2t = True if "dedup" in zv.flags: have_dedup = True if "hardlink" not in zv.flags and "reflink" not in zv.flags: have_symdup = True if "e2d" not in zv.flags: unsafe_dedup.append("/" + zv.vpath) t += "\n" if have_symdup and self.args.fika: t = "WARNING: disabling fika due to symlink-based dedup in at least one volume; uploads/deletes will be blocked during filesystem-indexing. Consider --reflink or --hardlink" # self.args.fika = self.args.fika.replace("m", "").replace("d", "") # probably not enough self.args.fika = "" if self.warn_anonwrite and verbosity > 4: if not self.args.no_voldump: self.log(t) if have_e2d or self.args.have_idp_hdrs: t = self.chk_sqlite_threadsafe() if t: self.log("\n\033[{}\033[0m\n".format(t)) if have_e2d: if not have_e2t: t = "hint: enable multimedia indexing (artist/title/...) with argument -e2ts" self.log(t, 6) else: t = "hint: enable searching and upload-undo with argument -e2dsa" self.log(t, 6) if unsafe_dedup: t = "WARNING: symlink-based deduplication is enabled for some volumes, but without indexing. Please enable -e2dsa and/or --hardlink to avoid problems when moving/renaming files. Affected volumes: %s" self.log(t % (", ".join(unsafe_dedup)), 3) elif not have_dedup: t = "hint: enable upload deduplication with --dedup (but see readme for consequences)" self.log(t, 6) zv, _ = vfs.get("/", "*", False, False) zs = zv.realpath.lower() if zs in ("/", "c:\\") or zs.startswith(r"c:\windows"): t = "you are sharing a system directory: {}\n" self.log(t.format(zv.realpath), c=1) try: zv, _ = vfs.get("", "*", False, True, err=999) if self.warn_anonwrite and verbosity > 4 and os.getcwd() == zv.realpath: t = "anyone can write to the current directory: {}\n" self.log(t.format(zv.realpath), c=1) self.warn_anonwrite = False except Pebkac: self.warn_anonwrite = True self.idp_warn = [] self.idp_err = [] for idp_vp in self.idp_vols: idp_vn, _ = vfs.get(idp_vp, "*", False, False) idp_vp0 = idp_vn.vpath0 sigils = set(PTN_SIGIL.findall(idp_vp0)) if len(sigils) > 1: t = '\nWARNING: IdP-volume "/%s" created by "/%s" has multiple IdP placeholders: %s' self.idp_warn.append(t % (idp_vp, idp_vp0, list(sigils))) continue sigil = sigils.pop() par_vp = idp_vp while par_vp: par_vp = vsplit(par_vp)[0] par_vn, _ = vfs.get(par_vp, "*", False, False) if sigil in par_vn.vpath0: continue # parent was spawned for and by same user oth_read = [] oth_write = [] for usr in par_vn.axs.uread: if usr not in idp_vn.axs.uread: oth_read.append(usr) for usr in par_vn.axs.uwrite: if usr not in idp_vn.axs.uwrite: oth_write.append(usr) if "*" in oth_read: taxs = "WORLD-READABLE" elif "*" in oth_write: taxs = "WORLD-WRITABLE" elif oth_read: taxs = "READABLE BY %r" % (oth_read,) elif oth_write: taxs = "WRITABLE BY %r" % (oth_write,) else: break # no sigil; not idp; safe to stop t = '\nWARNING: IdP-volume "/%s" created by "/%s" has parent/grandparent "/%s" and would be %s' self.idp_err.append(t % (idp_vp, idp_vp0, par_vn.vpath, taxs)) if self.idp_warn: t = "WARNING! Some IdP volumes include multiple IdP placeholders; this is too complex to automatically determine if safe or not. To ensure that no users gain unintended access, please use only a single placeholder for each IdP volume." self.log(t + "".join(self.idp_warn), 1) if self.idp_err: t = "WARNING! The following IdP volumes are mounted below another volume where other users can read and/or write files. This is a SECURITY HAZARD!! When copyparty is restarted, it will not know about these IdP volumes yet. These volumes will then be accessible by an unexpected set of permissions UNTIL one of the users associated with their volume sends a request to the server. RECOMMENDATION: You should create a restricted volume where nobody can read/write files, and make sure that all IdP volumes are configured to appear somewhere below that volume." self.log(t + "".join(self.idp_err), 1) if have_reflink: t = "WARNING: Reflink-based dedup was requested, but %s. This will not work; files will be full copies instead." if not sys.platform.startswith("linux"): self.log(t % "your OS is not Linux", 1) self.vfs = vfs self.acct = acct self.defpw = defpw self.grps = grps self.iacct = {v: k for k, v in acct.items()} self.cfg_files_loaded = cfg_files_loaded self.load_sessions() self.re_pwd = None pwds = [re.escape(x) for x in self.iacct.keys()] pwds.extend(list(self.sesa)) if self.args.usernames: pwds.extend([x.split(":", 1)[1] for x in pwds if ":" in x]) if pwds: if self.ah.on: zs = r"(\[H\] %s:.*|[?&]%s=)([^&]+)" zs = zs % (self.args.pw_hdr, self.args.pw_urlp) else: zs = r"(\[H\] %s:.*|=)(" % (self.args.pw_hdr,) zs += "|".join(pwds) + r")([]&; ]|$)" self.re_pwd = re.compile(zs) # to ensure it propagates into tcpsrv with mp on if self.args.mime: for zs in self.args.mime: ext, mime = zs.split("=", 1) MIMES[ext] = mime EXTS.update({v: k for k, v in MIMES.items()}) if enshare: # hide shares from controlpanel vfs.all_vols = { x: y for x, y in vfs.all_vols.items() if x != shr and not x.startswith(shrs) } assert db and cur and cur2 and shv # type: ignore for row in cur.execute("select * from sh"): s_k, s_pw, s_vp, s_pr, s_nf, s_un, s_t0, s_t1 = row shn = shv.nodes.get(s_k, None) if not shn: continue try: s_vfs, s_rem = vfs.get( s_vp, s_un, "r" in s_pr, "w" in s_pr, "m" in s_pr, "d" in s_pr ) except Exception as ex: t = "removing share [%s] by [%s] to [%s] due to %r" self.log(t % (s_k, s_un, s_vp, ex), 3) shv.nodes.pop(s_k) continue fns = [] if s_nf: q = "select vp from sf where k = ?" for (s_fn,) in cur2.execute(q, (s_k,)): fns.append(s_fn) shn.shr_files = set(fns) shn.ls = shn._ls_shr shn.canonical = shn._canonical_shr shn.dcanonical = shn._dcanonical_shr else: shn.ls = shn._ls shn.canonical = shn._canonical shn.dcanonical = shn._dcanonical shn.shr_owner = s_un shn.shr_src = (s_vfs, s_rem) shn.realpath = s_vfs.canonical(s_rem) o_vn, _ = shn._get_share_src("") shn.lim = o_vn.lim shn.flags = o_vn.flags.copy() shn.dbpath = o_vn.dbpath shn.histpath = o_vn.histpath # root.all_aps doesn't include any shares, so make a copy where the # share appears in all abspaths it can provide (for example for chk_ap) ap = shn.realpath if not ap.endswith(os.sep): ap += os.sep shn.shr_all_aps = [(x, y[:]) for x, y in vfs.all_aps] exact = False for ap2, vns in shn.shr_all_aps: if ap == ap2: exact = True if ap2.startswith(ap): try: vp2 = vjoin(s_rem, ap2[len(ap) :]) vn2, _ = s_vfs.get(vp2, "*", False, False) if vn2 == s_vfs or vn2.dbv == s_vfs: vns.append(shn) except: pass if not exact: shn.shr_all_aps.append((ap, [shn])) shn.shr_all_aps.sort(key=lambda x: len(x[0]), reverse=True) if self.args.shr_v: t = "mapped %s share [%s] by [%s] => [%s] => [%s]" self.log(t % (s_pr, s_k, s_un, s_vp, shn.realpath)) # transplant shadowing into shares for vn in shv.nodes.values(): svn, srem = vn.shr_src # type: ignore if srem: continue # free branch, safe ap = svn.canonical(srem) if bos.path.isfile(ap): continue # also fine for zs in svn.nodes.keys(): # hide subvolume vn.nodes[zs] = VFS(self.log_func, "", "", "", AXS(), self.vf0()) cur2.close() cur.close() db.close() self.js_ls = {} self.js_htm = {} for vp, vn in self.vfs.all_nodes.items(): if enshare and vp.startswith(shrs): continue # propagates later in this func vf = vn.flags vn.js_ls = { "idx": "e2d" in vf, "itag": "e2t" in vf, "dlni": "dlni" in vf, "dgrid": "grid" in vf, "dnsort": "nsort" in vf, "dhsortn": vf["hsortn"], "dsort": vf["sort"], "dcrop": vf["crop"], "dth3x": vf["th3x"], "u2ts": vf["u2ts"], "shr_who": vf["shr_who"], "frand": bool(vf.get("rand")), "lifetime": vf.get("lifetime") or 0, "unlist": vf.get("unlist") or "", "sb_lg": "" if "no_sb_lg" in vf else (vf.get("lg_sbf") or "y"), "sb_md": "" if "no_sb_md" in vf else (vf.get("md_sbf") or "y"), "rw_edit": vf["rw_edit"], } if "ufavico_h" in vf: vn.js_ls["ufavico"] = vf["ufavico_h"] js_htm = { "SPINNER": self.args.spinner, "s_name": self.args.bname, "idp_login": self.args.idp_login, "have_up2k_idx": "e2d" in vf, "have_acode": not self.args.no_acode, "have_c2flac": self.args.allow_flac, "have_c2wav": self.args.allow_wav, "have_shr": self.args.shr, "shr_who": vf["shr_who"], "have_zip": not self.args.no_zip, "have_zls": not self.args.no_zls, "have_mv": not self.args.no_mv, "have_del": not self.args.no_del, "have_unpost": int(self.args.unpost), "have_emp": int(self.args.emp), "md_no_br": int(vf.get("md_no_br") or 0), "ext_th": vf.get("ext_th_d") or {}, "sb_lg": vn.js_ls["sb_lg"], "sb_md": vn.js_ls["sb_md"], "sba_md": vf.get("md_sba") or "", "sba_lg": vf.get("lg_sba") or "", "rw_edit": vf["rw_edit"], "txt_ext": self.args.textfiles.replace(",", " "), "def_hcols": list(vf.get("mth") or []), "unlist0": vf.get("unlist") or "", "see_dots": self.args.see_dots, "dqdel": self.args.qdel, "dlni": vn.js_ls["dlni"], "dgrid": vn.js_ls["dgrid"], "dgsel": "gsel" in vf, "dnsort": "nsort" in vf, "dhsortn": vf["hsortn"], "dsort": vf["sort"], "dcrop": vf["crop"], "dth3x": vf["th3x"], "drcm": self.args.rcm, "dvol": self.args.au_vol, "idxh": int(self.args.ih), "dutc": not self.args.localtime, "dfszf": self.args.ui_filesz.strip("-"), "themes": self.args.themes, "turbolvl": self.args.turbo, "nosubtle": self.args.nosubtle, "u2j": self.args.u2j, "u2sz": self.args.u2sz, "u2ts": vf["u2ts"], "u2ow": vf["u2ow"], "frand": bool(vf.get("rand")), "lifetime": vn.js_ls["lifetime"], "u2sort": self.args.u2sort, } zs = "ui_noacci ui_nocpla ui_noctxb ui_nolbar ui_nombar ui_nonav ui_notree ui_norepl ui_nosrvi" for zs in zs.split(): if vf.get(zs): js_htm[zs] = 1 zs = "notooltips" for zs in zs.split(): if getattr(self.args, zs, False): js_htm[zs] = 1 zs = "up_site" for zs in zs.split(): zs2 = getattr(self.args, zs, "") if zs2: js_htm[zs] = zs2 vn.js_htm = json_hesc(json.dumps(js_htm)) vols = list(vfs.all_nodes.values()) if enshare: assert shv # type: ignore # !rm for vol in shv.nodes.values(): if vol.vpath not in vfs.all_nodes: self.log("BUG: /%s not in all_nodes" % (vol.vpath,), 1) vols.append(vol) if shr in vfs.all_nodes: t = "invalid config: a volume is overlapping with the --shr global-option (/%s)" t = t % (shr,) self.log(t, 1) raise Exception(t) for vol in vols: dbv = vol.get_dbv("")[0] vol.js_ls = vol.js_ls or dbv.js_ls or {} vol.js_htm = vol.js_htm or dbv.js_htm or "{}" zs = str(vol.flags.get("tcolor") or self.args.tcolor) vol.flags["tcolor"] = zs.lstrip("#") def setup_auth_ord(self) -> None: ao = [x.strip() for x in self.args.auth_ord.split(",")] if "idp" in ao: zi = ao.index("idp") ao = ao[:zi] + ["idp-hm", "idp-h"] + ao[zi:] zsl = "pw idp-h idp-hm ipu".split() pw, h, hm, ipu = [ao.index(x) if x in ao else 99 for x in zsl] self.args.ao_idp_before_pw = min(h, hm) < pw self.args.ao_h_before_hm = h < hm self.args.ao_ipu_wins = ipu == 0 self.args.ao_have_pw = pw < 99 or not self.args.have_idp_hdrs def load_idp_db(self, quiet=False) -> None: # mutex me level = self.args.idp_store if level < 2 or not self.args.have_idp_hdrs: return assert sqlite3 # type: ignore # !rm db = sqlite3.connect(self.args.idp_db) cur = db.cursor() from_cache = cur.execute("select un, gs from us").fetchall() cur.close() db.close() old_accs = self.idp_accs.copy() self.idp_accs.clear() self.idp_usr_gh.clear() gsep = self.args.idp_gsep groupless = (None, [""]) n = [] for uname, gname in from_cache: if level < 3: if uname in self.idp_accs: continue if old_accs.get(uname) in groupless: gname = "" gnames = [x.strip() for x in gsep.split(gname)] gnames.sort() self.idp_accs[uname] = gnames n.append(uname) if n and not quiet: t = ", ".join(n[:9]) if len(n) > 9: t += "..." self.log("found %d IdP users in db (%s)" % (len(n), t)) def load_sessions(self, quiet=False) -> None: # mutex me if self.args.no_ses: self.ases = {} self.sesa = {} return assert sqlite3 # type: ignore # !rm ases = {} blen = (self.args.ses_len // 4) * 4 # 3 bytes in 4 chars blen = (blen * 3) // 4 # bytes needed for ses_len chars db = sqlite3.connect(self.args.ses_db) cur = db.cursor() for uname, sid in cur.execute("select un, si from us"): if uname in self.acct: ases[uname] = sid n = [] q = "insert into us values (?,?,?)" accs = list(self.acct) if self.args.have_idp_hdrs and self.args.idp_cookie: accs.extend(self.idp_accs.keys()) for uname in accs: if uname not in ases: sid = ub64enc(os.urandom(blen)).decode("ascii") cur.execute(q, (uname, sid, int(time.time()))) ases[uname] = sid n.append(uname) if n: db.commit() cur.close() db.close() self.ases = ases self.sesa = {v: k for k, v in ases.items()} if n and not quiet: t = ", ".join(n[:3]) if len(n) > 3: t += "..." self.log("added %d new sessions (%s)" % (len(n), t)) def forget_session(self, broker: Optional["BrokerCli"], uname: str) -> None: with self.mutex: self._forget_session(uname) if broker: broker.ask("_reload_sessions").get() def _forget_session(self, uname: str) -> None: if self.args.no_ses: return assert sqlite3 # type: ignore # !rm db = sqlite3.connect(self.args.ses_db) cur = db.cursor() cur.execute("delete from us where un = ?", (uname,)) db.commit() cur.close() db.close() self.sesa.pop(self.ases.get(uname, ""), "") self.ases.pop(uname, "") def chpw(self, broker: Optional["BrokerCli"], uname, pw) -> tuple[bool, str]: if not self.args.chpw: return False, "feature disabled in server config" if uname == "*" or uname not in self.defpw: return False, "not logged in" if uname in self.args.chpw_no: return False, "not allowed for this account" if len(pw) < self.args.chpw_len: t = "minimum password length: %d characters" return False, t % (self.args.chpw_len,) if self.args.usernames: pw = "%s:%s" % (uname, pw) hpw = self.ah.hash(pw) if self.ah.on else pw if hpw == self.acct[uname]: return False, "that's already your password my dude" if hpw in self.iacct or hpw in self.sesa: return False, "password is taken" with self.mutex: ap = self.args.chpw_db if not bos.path.exists(ap): pwdb = {} else: jtxt = read_utf8(self.log, ap, True) pwdb = json.loads(jtxt) if jtxt.strip() else {} pwdb = [x for x in pwdb if x[0] != uname] pwdb.append((uname, self.defpw[uname], hpw)) with open(ap, "w", encoding="utf-8") as f: json.dump(pwdb, f, separators=(",\n", ": ")) self.log("reinitializing due to password-change for user [%s]" % (uname,)) if not broker: # only true for tests self._reload() return True, "new password OK" broker.ask("reload", False, False).get() return True, "new password OK" def setup_chpw(self, acct: dict[str, str]) -> None: ap = self.args.chpw_db if not self.args.chpw or not bos.path.exists(ap): return jtxt = read_utf8(self.log, ap, True) pwdb = json.loads(jtxt) if jtxt.strip() else {} useen = set() urst = set() uok = set() for usr, orig, mod in pwdb: useen.add(usr) if usr not in acct: # previous user, no longer known continue if acct[usr] != orig: urst.add(usr) continue uok.add(usr) acct[usr] = mod if not self.args.chpw_v: return for usr in acct: if usr not in useen: urst.add(usr) for zs in uok: urst.discard(zs) if self.args.chpw_v == 1 or (self.args.chpw_v == 2 and not urst): t = "chpw: %d changed, %d unchanged" self.log(t % (len(uok), len(urst))) return elif self.args.chpw_v == 2: t = "chpw: %d changed" % (len(uok),) if urst: t += ", \033[0munchanged:\033[35m %s" % (", ".join(list(urst))) self.log(t, 6) return msg = "" if uok: t = "\033[0mchanged: \033[32m%s" msg += t % (", ".join(list(uok)),) if urst: t = "%s\033[0munchanged: \033[35m%s" msg += t % ( ", " if msg else "", ", ".join(list(urst)), ) self.log("chpw: " + msg, 6) def setup_pwhash(self, acct: dict[str, str]) -> None: if self.args.usernames: for uname, pw in list(acct.items())[:]: if pw.startswith("+") and len(pw) == 33: continue acct[uname] = "%s:%s" % (uname, pw) self.ah = PWHash(self.args) if not self.ah.on: if self.args.ah_cli or self.args.ah_gen: t = "\n BAD CONFIG:\n cannot --ah-cli or --ah-gen without --ah-alg" raise Exception(t) return if self.args.ah_cli: self.ah.cli() sys.exit() elif self.args.ah_gen == "-": self.ah.stdin() sys.exit() elif self.args.ah_gen: print(self.ah.hash(self.args.ah_gen)) sys.exit() if not acct: return changed = False for uname, pw in list(acct.items())[:]: if pw.startswith("+") and len(pw) == 33: continue changed = True hpw = self.ah.hash(pw) acct[uname] = hpw t = "hashed password for account {}: {}" self.log(t.format(uname, hpw), 3) if not changed: return lns = [] for uname, pw in acct.items(): lns.append(" {}: {}".format(uname, pw)) t = "please use the following hashed passwords in your config:\n{}" self.log(t.format("\n".join(lns)), 3) def chk_sqlite_threadsafe(self) -> str: v = SQLITE_VER[-1:] if v == "1": # threadsafe (linux, windows) return "" if v == "2": # module safe, connections unsafe (macos) return "33m your sqlite3 was compiled with reduced thread-safety;\n database features (-e2d, -e2t) SHOULD be fine\n but MAY cause database-corruption and crashes" if v == "0": # everything unsafe return "31m your sqlite3 was compiled WITHOUT thread-safety!\n database features (-e2d, -e2t) will PROBABLY cause crashes!" return "36m cannot verify sqlite3 thread-safety; strange but probably fine" def dbg_ls(self) -> None: users = self.args.ls vol = "*" flags: Sequence[str] = [] try: users, vol = users.split(",", 1) except: pass try: vol, zf = vol.split(",", 1) flags = zf.split(",") except: pass if users == "**": users = list(self.acct.keys()) + ["*"] else: users = [users] for u in users: if u not in self.acct and u != "*": raise Exception("user not found: " + u) if vol == "*": vols = ["/" + x for x in self.vfs.all_vols] else: vols = [vol] for zs in vols: if not zs.startswith("/"): raise Exception("volumes must start with /") if zs[1:] not in self.vfs.all_vols: raise Exception("volume not found: " + zs) self.log(str({"users": users, "vols": vols, "flags": flags})) t = "/{}: read({}) write({}) move({}) del({}) dots({}) get({}) upGet({}) html({}) uadmin({})" for k, zv in self.vfs.all_vols.items(): vc = zv.axs vs = [ k, vc.uread, vc.uwrite, vc.umove, vc.udel, vc.udot, vc.uget, vc.upget, vc.uhtml, vc.uadmin, ] self.log(t.format(*vs)) flag_v = "v" in flags flag_ln = "ln" in flags flag_p = "p" in flags flag_r = "r" in flags bads = [] for v in vols: v = v[1:] vtop = "/{}/".format(v) if v else "/" for u in users: self.log("checking /{} as {}".format(v, u)) try: vn, _ = self.vfs.get(v, u, True, False, False, False, False) except: continue atop = vn.realpath safeabs = atop + os.sep g = vn.walk( vn.vpath, "", [], u, [[True, False]], 1, not self.args.no_scandir, False, False, ) for _, _, vpath, apath, files1, dirs, _ in g: fnames = [n[0] for n in files1] zsl = [vpath + "/" + n for n in fnames] if vpath else fnames vpaths = [vtop + x for x in zsl] apaths = [os.path.join(apath, n) for n in fnames] files = [(vpath + "/", apath + os.sep)] + list( [(zs1, zs2) for zs1, zs2 in zip(vpaths, apaths)] ) if flag_ln: files = [x for x in files if not x[1].startswith(safeabs)] if files: dirs[:] = [] # stop recursion bads.append(files[0][0]) if not files: continue elif flag_v: ta = [""] + [ '# user "{}", vpath "{}"\n{}'.format(u, vp, ap) for vp, ap in files ] else: ta = ["user {}, vol {}: {} =>".format(u, vtop, files[0][0])] ta += [x[1] for x in files] self.log("\n".join(ta)) if bads: self.log("\n ".join(["found symlinks leaving volume:"] + bads)) if bads and flag_p: raise Exception( "\033[31m\n [--ls] found a safety issue and prevented startup:\n found symlinks leaving volume, and strict is set\n\033[0m" ) if not flag_r: sys.exit(0) def cgen(self) -> None: ret = [ "## WARNING:", "## there will probably be mistakes in", "## commandline-args (and maybe volflags)", "", ] csv = set("i p th_covers zm_on zm_off zs_on zs_off".split()) zs = "c ihead ohead mtm mtp on403 on404 xac xad xar xau xiu xban xbc xbd xbr xbu xm" lst = set(zs.split()) askip = set("a v c vc cgen exp_lg exp_md theme".split()) t = "exp_lg exp_md ext_th_d mv_re_r mv_re_t rm_re_r rm_re_t srch_re_dots srch_re_nodot" fskip = set(t.split()) # keymap from argv to vflag amap = vf_bmap() amap.update(vf_vmap()) amap.update(vf_cmap()) vmap = {v: k for k, v in amap.items()} args = {k: v for k, v in vars(self.args).items()} pops = [] for k1, k2 in IMPLICATIONS: if args.get(k1): pops.append(k2) for pop in pops: args.pop(pop, None) if args: ret.append("[global]") for k, v in args.items(): if k in askip: continue try: v = v.pattern if k in ("idp_gsep", "tftp_lsf"): v = v[1:-1] # close enough except: pass skip = False for k2, defstr in (("mte", DEF_MTE), ("mth", DEF_MTH)): if k != k2: continue s1 = list(sorted(list(v))) s2 = list(sorted(defstr.split(","))) if s1 == s2: skip = True break v = ",".join(s1) if skip: continue if k in csv: v = ", ".join([str(za) for za in v]) try: v2 = getattr(self.dargs, k) if k == "tcolor" and len(v2) == 3: v2 = "".join([x * 2 for x in v2]) if v == v2 or v.replace(", ", ",") == v2: continue except: continue dk = " " + k.replace("_", "-") if k in lst: for ve in v: ret.append("{}: {}".format(dk, ve)) else: if v is True: ret.append(dk) elif v not in (False, None, ""): ret.append("{}: {}".format(dk, v)) ret.append("") if self.acct: ret.append("[accounts]") for u, p in self.acct.items(): ret.append(" {}: {}".format(u, p)) ret.append("") if self.grps: ret.append("[groups]") for gn, uns in self.grps.items(): ret.append(" %s: %s" % (gn, ", ".join(uns))) ret.append("") for vol in self.vfs.all_vols.values(): ret.append("[/{}]".format(vol.vpath)) ret.append(" " + vol.realpath) ret.append(" accs:") perms = { "r": "uread", "w": "uwrite", "m": "umove", "d": "udel", ".": "udot", "g": "uget", "G": "upget", "h": "uhtml", "a": "uadmin", } users = {} for pkey in perms.values(): for uname in getattr(vol.axs, pkey): try: users[uname] += 1 except: users[uname] = 1 lusers = [(v, k) for k, v in users.items()] vperms = {} for _, uname in sorted(lusers): pstr = "" for pchar, pkey in perms.items(): if uname in getattr(vol.axs, pkey): pstr += pchar if "g" in pstr and "G" in pstr: pstr = pstr.replace("g", "") pstr = pstr.replace("rwmd.a", "A") try: vperms[pstr].append(uname) except: vperms[pstr] = [uname] for pstr, uname in vperms.items(): ret.append(" {}: {}".format(pstr, ", ".join(uname))) trues = [] vals = [] for k, v in sorted(vol.flags.items()): if k in fskip: continue try: v = v.pattern except: pass try: ak = vmap[k] v2 = getattr(self.args, ak) try: v2 = v2.pattern except: pass if v2 is v: continue except: pass skip = False for k2, defstr in (("mte", DEF_MTE), ("mth", DEF_MTH)): if k != k2: continue s1 = list(sorted(list(v))) s2 = list(sorted(defstr.split(","))) if s1 == s2: skip = True break v = ",".join(s1) if skip: continue if k in lst: for ve in v: vals.append("{}: {}".format(k, ve)) elif v is True: trues.append(k) elif v is not False: vals.append("{}: {}".format(k, v)) pops = [] for k1, k2 in IMPLICATIONS: if k1 in trues: pops.append(k2) trues = [x for x in trues if x not in pops] if trues: vals.append(", ".join(trues)) if vals: ret.append(" flags:") for zs in vals: ret.append(" " + zs) ret.append("") self.log("generated config:\n\n" + "\n".join(ret)) def derive_args(args: argparse.Namespace) -> None: args.have_idp_hdrs = bool(args.idp_h_usr or args.idp_hm_usr) args.have_ipu_or_ipr = bool(args.ipu or args.ipr) def n_du_who(s: str) -> int: if s == "all": return 9 if s == "auth": return 7 if s == "w": return 5 if s == "rw": return 4 if s == "a": return 3 return 0 def n_ver_who(s: str) -> int: if s == "all": return 9 if s == "auth": return 6 if s == "a": return 3 return 0 def split_cfg_ln(ln: str) -> dict[str, Any]: # "a, b, c: 3" => {a:true, b:true, c:3} ret = {} while True: ln = ln.strip() if not ln: break ofs_sep = ln.find(",") + 1 ofs_var = ln.find(":") + 1 if not ofs_sep and not ofs_var: ret[ln] = True break if ofs_sep and (ofs_sep < ofs_var or not ofs_var): k, ln = ln.split(",", 1) ret[k.strip()] = True else: k, ln = ln.split(":", 1) ret[k.strip()] = ln.strip() break return ret def expand_config_file( log: Optional["NamedLogger"], ret: list[str], fp: str, ipath: str ) -> None: fp = absreal(fp) if len(ipath.split(" -> ")) > 64: raise Exception("hit max depth of 64 includes") if os.path.isdir(fp): names = list(sorted(os.listdir(fp))) cnames = [ x for x in names if x.lower().endswith(".conf") and not x.startswith(".") ] if not cnames: t = "warning: tried to read config-files from folder '%s' but it does not contain any " if names: t += ".conf files; the following files/subfolders were ignored: %s" t = t % (fp, ", ".join(names[:8])) else: t += "files at all" t = t % (fp,) if log: log(t, 3) ret.append("#\033[33m %s\033[0m" % (t,)) else: zs = "#\033[36m cfg files in %s => %s\033[0m" % (fp, cnames) ret.append(zs) for fn in cnames: fp2 = os.path.join(fp, fn) if fp2 in ipath: continue expand_config_file(log, ret, fp2, ipath) return if not os.path.exists(fp): t = "warning: tried to read config from '%s' but the file/folder does not exist" t = t % (fp,) if log: log(t, 3) ret.append("#\033[31m %s\033[0m" % (t,)) return ipath += " -> " + fp ret.append("#\033[36m opening cfg file{}\033[0m".format(ipath)) cfg_lines = read_utf8(log, fp, True).replace("\t", " ").split("\n") if True: # diff-golf for oln in [x.rstrip() for x in cfg_lines]: ln = oln.split(" #")[0].strip() if ln.startswith("% "): pad = " " * len(oln.split("%")[0]) fp2 = ln[1:].strip() fp2 = os.path.join(os.path.dirname(fp), fp2) ofs = len(ret) expand_config_file(log, ret, fp2, ipath) for n in range(ofs, len(ret)): ret[n] = pad + ret[n] continue ret.append(oln) ret.append("#\033[36m closed{}\033[0m".format(ipath)) zsl = [] for ln in ret: zs = ln.split(" #")[0] if " #" in zs and zs.split("#")[0].strip(): zsl.append(ln) if zsl and "no-cfg-cmt-warn" not in "\n".join(ret): t = "\033[33mWARNING: there is less than two spaces before the # in the following config lines, so instead of assuming that this is a comment, the whole line will become part of the config value:\n\n>>> %s\n\nif you are familiar with this and would like to mute this warning, specify the global-option no-cfg-cmt-warn\n\033[0m" t = t % ("\n>>> ".join(zsl),) if log: log(t) else: print(t, file=sys.stderr) def upgrade_cfg_fmt( log: Optional["NamedLogger"], args: argparse.Namespace, orig: list[str], cfg_fp: str ) -> list[str]: zst = [x.split("#")[0].strip() for x in orig] zst = [x for x in zst if x] if ( "[global]" in zst or "[accounts]" in zst or "accs:" in zst or "flags:" in zst or [x for x in zst if x.startswith("[/")] or len(zst) == len([x for x in zst if x.startswith("%")]) ): return orig zst = [x for x in orig if "#\033[36m opening cfg file" not in x] incl = len(zst) != len(orig) - 1 t = "upgrading config file [{}] from v1 to v2" if not args.vc: t += ". Run with argument '--vc' to see the converted config if you want to upgrade" if incl: t += ". Please don't include v1 configs from v2 files or vice versa! Upgrade all of them at the same time." if log: log(t.format(cfg_fp), 3) ret = [] vp = "" ap = "" cat = "" catg = "[global]" cata = "[accounts]" catx = " accs:" catf = " flags:" for ln in orig: sn = ln.strip() if not sn: cat = vp = ap = "" if not sn.split("#")[0]: ret.append(ln) elif sn.startswith("-") and cat in ("", catg): if cat != catg: cat = catg ret.append(cat) sn = sn.lstrip("-") zst = sn.split(" ", 1) if len(zst) > 1: sn = "{}: {}".format(zst[0], zst[1].strip()) ret.append(" " + sn) elif sn.startswith("u ") and cat in ("", catg, cata): if cat != cata: cat = cata ret.append(cat) s1, s2 = sn[1:].split(":", 1) ret.append(" {}: {}".format(s1.strip(), s2.strip())) elif not ap: ap = sn elif not vp: vp = "/" + sn.strip("/") cat = "[{}]".format(vp) ret.append(cat) ret.append(" " + ap) elif sn.startswith("c "): if cat != catf: cat = catf ret.append(cat) sn = sn[1:].strip() if "=" in sn: zst = sn.split("=", 1) sn = zst[0].replace(",", ", ") sn += ": " + zst[1] else: sn = sn.replace(",", ", ") ret.append(" " + sn) elif sn[:1] in "rwmdgGhaA.": if cat != catx: cat = catx ret.append(cat) zst = sn.split(" ") zst = [x for x in zst if x] if len(zst) == 1: zst.append("*") ret.append(" {}: {}".format(zst[0], ", ".join(zst[1:]))) else: t = "did not understand line {} in the config" t1 = t n = 0 for ln in orig: n += 1 t += "\n{:4} {}".format(n, ln) if log: log(t, 1) else: print("\033[31m" + t) raise Exception(t1) if args.vc and log: t = "new config syntax (copy/paste this to upgrade your config):\n" t += "\n# ======================[ begin upgraded config ]======================\n\n" for ln in ret: t += ln + "\n" t += "\n# ======================[ end of upgraded config ]======================\n" log(t) return ret
--- +++ @@ -401,6 +401,7 @@ class VFS(object): + """single level in the virtual fs""" def __init__( self, @@ -499,6 +500,7 @@ v.get_all_vols(vols, nodes, aps, vps) def add(self, src: str, dst: str, dst0: str) -> "VFS": + """get existing, or add new path to the vfs""" assert src == "/" or not src.endswith("/") # nosec assert not dst.endswith("/") # nosec @@ -559,6 +561,7 @@ n.bubble_flags() def _find(self, vpath: str) -> tuple["VFS", str]: + """return [vfs,remainder]""" if not vpath: return self, "" @@ -576,6 +579,7 @@ def can_access( self, vpath: str, uname: str ) -> tuple[bool, bool, bool, bool, bool, bool, bool, bool, bool]: + """can Read,Write,Move,Delete,Get,Upget,Html,Admin,Dot""" # NOTE: only used by get_perms, which is only used by hooks; the lowest of fruits if vpath: vn, _ = self._find(undot(vpath)) @@ -602,6 +606,7 @@ will_get: bool = False, err: int = 403, ) -> tuple["VFS", str]: + """returns [vfsnode,fs_remainder] if user has the requested permissions""" if relchk(vpath): if self.log: self.log("vfs", "invalid relpath %r @%s" % (vpath, uname)) @@ -678,6 +683,7 @@ return "" def _canonical(self, rem: str, resolve: bool = True) -> str: + """returns the canonical path (fully-resolved absolute fs path)""" ap = self.realpath if rem: ap += "/" + rem @@ -685,6 +691,7 @@ return absreal(ap) if resolve else ap def _dcanonical(self, rem: str) -> str: + """resolves until the final component (filename)""" ap = self.realpath if rem: ap += "/" + rem @@ -693,6 +700,7 @@ return os.path.join(absreal(ad), fn) def _canonical_shr(self, rem: str, resolve: bool = True) -> str: + """returns the canonical path (fully-resolved absolute fs path)""" ap = self.realpath if rem: ap += "/" + rem @@ -715,6 +723,7 @@ return (rap or absreal(ap)) if resolve else ap def _dcanonical_shr(self, rem: str) -> str: + """resolves until the final component (filename)""" ap = self.realpath if rem: ap += "/" + rem @@ -746,6 +755,7 @@ lstat: bool = False, throw: bool = False, ) -> tuple[str, list[tuple[str, os.stat_result]], dict[str, "VFS"]]: + """replaces _ls for certain shares (single-file, or file selection)""" vn, rem = self.shr_src # type: ignore abspath, real, _ = vn.ls(rem, "\n", scandir, permsets, lstat, throw) real = [x for x in real if os.path.basename(x[0]) in self.shr_files] @@ -760,6 +770,7 @@ lstat: bool = False, throw: bool = False, ) -> tuple[str, list[tuple[str, os.stat_result]], dict[str, "VFS"]]: + """return user-readable [fsdir,real,virt] items at vpath""" virt_vis = {} # nodes readable by user abspath = self.canonical(rem) if abspath: @@ -822,6 +833,14 @@ None, None, ]: + """ + recursively yields from ./rem; + rel is a unix-style user-defined vpath (not vfs-related) + + NOTE: don't invoke this function from a dbv; subvols are only + descended into if rem is blank due to the _ls `if not rem:` + which intention is to prevent unintended access to subvols + """ fsroot, vfs_ls, vfs_virt = self.ls(rem, uname, scandir, permsets, lstat=lstat) dbv, vrem = self.get_dbv(rem) @@ -1041,6 +1060,7 @@ class AuthSrv(object): + """verifies users against given paths""" def __init__( self, @@ -1102,6 +1122,7 @@ self.log_func("auth", msg, c) def laggy_iter(self, iterable: Iterable[Any]) -> Generator[Any, None, None]: + """returns [value,isFinalValue]""" it = iter(iterable) prev = next(it) for x in it: @@ -1323,6 +1344,12 @@ acct: dict[str, str], grps: dict[str, list[str]], ) -> dict[str, list[str]]: + """ + generate list of all confirmed pairs of username/groupname seen since last restart; + in case of conflicting group memberships then it is selected as follows: + * any non-zero value from IdP group header + * otherwise take --grps / [groups] + """ self.load_idp_db(bool(self.idp_accs)) ret = {un: gns[:] for un, gns in self.idp_accs.items()} ret.update({zs: [""] for zs in acct if zs not in ret}) @@ -1730,6 +1757,12 @@ self._e("volflag [{}] += {} ({})".format(name, vals, desc)) def reload(self, verbosity: int = 9) -> None: + """ + construct a flat list of mountpoints and usernames + first from the commandline arguments + then supplementing with config files + before finally building the VFS + """ with self.mutex: self._reload(verbosity) @@ -3931,6 +3964,7 @@ def expand_config_file( log: Optional["NamedLogger"], ret: list[str], fp: str, ipath: str ) -> None: + """expand all % file includes""" fp = absreal(fp) if len(ipath.split(" -> ")) > 64: raise Exception("hit max depth of 64 includes") @@ -4013,6 +4047,7 @@ def upgrade_cfg_fmt( log: Optional["NamedLogger"], args: argparse.Namespace, orig: list[str], cfg_fp: str ) -> list[str]: + """convert from v1 to v2 format""" zst = [x.split("#")[0].strip() for x in orig] zst = [x for x in zst if x] if ( @@ -4114,4 +4149,4 @@ t += "\n# ======================[ end of upgraded config ]======================\n" log(t) - return ret+ return ret
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/authsrv.py
Create docstrings for each class method
# coding: utf-8 # This code is released under the Python license and the BSD 2-clause license import codecs import platform import sys PY3 = sys.version_info > (3,) WINDOWS = platform.system() == "Windows" FS_ERRORS = "surrogateescape" if True: # pylint: disable=using-constant-test from typing import Any if PY3: _unichr = chr bytes_chr = lambda code: bytes((code,)) else: _unichr = unichr bytes_chr = chr def surrogateescape_handler(exc: Any) -> tuple[str, int]: mystring = exc.object[exc.start : exc.end] try: if isinstance(exc, UnicodeDecodeError): # mystring is a byte-string in this case decoded = replace_surrogate_decode(mystring) elif isinstance(exc, UnicodeEncodeError): # In the case of u'\udcc3'.encode('ascii', # 'this_surrogateescape_handler'), both Python 2.x and 3.x raise an # exception anyway after this function is called, even though I think # it's doing what it should. It seems that the strict encoder is called # to encode the unicode string that this function returns ... decoded = replace_surrogate_encode(mystring) else: raise exc except NotASurrogateError: raise exc return (decoded, exc.end) class NotASurrogateError(Exception): pass def replace_surrogate_encode(mystring: str) -> str: decoded = [] for ch in mystring: code = ord(ch) # The following magic comes from Py3.3's Python/codecs.c file: if not 0xD800 <= code <= 0xDCFF: # Not a surrogate. Fail with the original exception. raise NotASurrogateError # mybytes = [0xe0 | (code >> 12), # 0x80 | ((code >> 6) & 0x3f), # 0x80 | (code & 0x3f)] # Is this a good idea? if 0xDC00 <= code <= 0xDC7F: decoded.append(_unichr(code - 0xDC00)) elif code <= 0xDCFF: decoded.append(_unichr(code - 0xDC00)) else: raise NotASurrogateError return str().join(decoded) def replace_surrogate_decode(mybytes: bytes) -> str: decoded = [] for ch in mybytes: # We may be parsing newbytes (in which case ch is an int) or a native # str on Py2 if isinstance(ch, int): code = ch else: code = ord(ch) if 0x80 <= code <= 0xFF: decoded.append(_unichr(0xDC00 + code)) elif code <= 0x7F: decoded.append(_unichr(code)) else: raise NotASurrogateError return str().join(decoded) def encodefilename(fn: str) -> bytes: if FS_ENCODING == "ascii": # ASCII encoder of Python 2 expects that the error handler returns a # Unicode string encodable to ASCII, whereas our surrogateescape error # handler has to return bytes in 0x80-0xFF range. encoded = [] for index, ch in enumerate(fn): code = ord(ch) if code < 128: ch = bytes_chr(code) elif 0xDC80 <= code <= 0xDCFF: ch = bytes_chr(code - 0xDC00) else: raise UnicodeEncodeError( FS_ENCODING, fn, index, index + 1, "ordinal not in range(128)" ) encoded.append(ch) return bytes().join(encoded) elif FS_ENCODING == "utf-8": # UTF-8 encoder of Python 2 encodes surrogates, so U+DC80-U+DCFF # doesn't go through our error handler encoded = [] for index, ch in enumerate(fn): code = ord(ch) if 0xD800 <= code <= 0xDFFF: if 0xDC80 <= code <= 0xDCFF: ch = bytes_chr(code - 0xDC00) encoded.append(ch) else: raise UnicodeEncodeError( FS_ENCODING, fn, index, index + 1, "surrogates not allowed" ) else: ch_utf8 = ch.encode("utf-8") encoded.append(ch_utf8) return bytes().join(encoded) else: return fn.encode(FS_ENCODING, FS_ERRORS) def decodefilename(fn: bytes) -> str: return fn.decode(FS_ENCODING, FS_ERRORS) FS_ENCODING = sys.getfilesystemencoding() if WINDOWS and not PY3: # py2 thinks win* is mbcs, probably a bug? anyways this works FS_ENCODING = "utf-8" # normalize the filesystem encoding name. # For example, we expect "utf-8", not "UTF8". FS_ENCODING = codecs.lookup(FS_ENCODING).name def register_surrogateescape() -> None: if PY3: return try: codecs.lookup_error(FS_ERRORS) except LookupError: codecs.register_error(FS_ERRORS, surrogateescape_handler)
--- +++ @@ -1,5 +1,14 @@ # coding: utf-8 +""" +This is Victor Stinner's pure-Python implementation of PEP 383: the "surrogateescape" error +handler of Python 3. + +Scissored from the python-future module to avoid 4.4MB of additional dependencies: +https://github.com/PythonCharmers/python-future/blob/e12549c42ed3a38ece45b9d88c75f5f3ee4d658d/src/future/utils/surrogateescape.py + +Original source: misc/python/surrogateescape.py in https://bitbucket.org/haypo/misc +""" # This code is released under the Python license and the BSD 2-clause license @@ -24,6 +33,12 @@ def surrogateescape_handler(exc: Any) -> tuple[str, int]: + """ + Pure Python implementation of the PEP 383: the "surrogateescape" error + handler of Python 3. Undecodable bytes will be replaced by a Unicode + character U+DCxx on decoding, and these are translated into the + original bytes on encoding. + """ mystring = exc.object[exc.start : exc.end] try: @@ -49,6 +64,10 @@ def replace_surrogate_encode(mystring: str) -> str: + """ + Returns a (unicode) string, not the more logical bytes, because the codecs + register_error functionality expects this. + """ decoded = [] for ch in mystring: code = ord(ch) @@ -71,6 +90,9 @@ def replace_surrogate_decode(mybytes: bytes) -> str: + """ + Returns a (unicode) string + """ decoded = [] for ch in mybytes: # We may be parsing newbytes (in which case ch is an int) or a native @@ -146,9 +168,12 @@ def register_surrogateescape() -> None: + """ + Registers the surrogateescape error handler on Python 2 (only) + """ if PY3: return try: codecs.lookup_error(FS_ERRORS) except LookupError: - codecs.register_error(FS_ERRORS, surrogateescape_handler)+ codecs.register_error(FS_ERRORS, surrogateescape_handler)
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/stolen/surrogateescape.py
Generate consistent documentation across files
# coding: utf-8 from __future__ import print_function, unicode_literals import argparse import atexit import errno import json import logging import os import re import shlex import signal import socket import string import sys import threading import time from datetime import datetime # from inspect import currentframe # print(currentframe().f_lineno) if True: # pylint: disable=using-constant-test from types import FrameType import typing from typing import Any, Optional, Union from .__init__ import ANYWIN, EXE, MACOS, PY2, TYPE_CHECKING, E, EnvParams, unicode from .__version__ import S_VERSION, VERSION from .authsrv import BAD_CFG, AuthSrv, derive_args, n_du_who, n_ver_who from .bos import bos from .cert import ensure_cert from .fsutil import ramdisk_chk from .mtag import HAVE_FFMPEG, HAVE_FFPROBE, HAVE_MUTAGEN from .pwhash import HAVE_ARGON2 from .tcpsrv import TcpSrv from .th_srv import ( H_PIL_AVIF, H_PIL_HEIF, H_PIL_WEBP, HAVE_FFMPEG, HAVE_FFPROBE, HAVE_PIL, HAVE_RAW, HAVE_VIPS, ThumbSrv, ) from .up2k import Up2k from .util import ( DEF_EXP, DEF_MTE, DEF_MTH, FFMPEG_URL, HAVE_PSUTIL, HAVE_SQLITE3, HAVE_ZMQ, RE_ANSI, URL_BUG, UTC, VERSIONS, Daemon, Garda, HLog, HMaccas, ODict, alltrace, build_netmap, expat_ver, gzip, html_escape, load_ipr, load_ipu, lock_file, min_ex, mp, odfusion, pybin, read_utf8, start_log_thrs, start_stackmon, termsize, ub64enc, umktrans, ) if HAVE_SQLITE3: import sqlite3 if TYPE_CHECKING: try: from .mdns import MDNS from .ssdp import SSDPd except: pass if PY2: range = xrange # type: ignore if PY2: from urllib2 import Request, urlopen else: from urllib.request import Request, urlopen VER_IDP_DB = 1 VER_SESSION_DB = 1 VER_SHARES_DB = 2 class SvcHub(object): def __init__( self, args: argparse.Namespace, dargs: argparse.Namespace, argv: list[str], printed: str, ) -> None: self.args = args self.dargs = dargs self.argv = argv self.E: EnvParams = args.E self.no_ansi = args.no_ansi self.flo = args.flo self.tz = UTC if args.log_utc else None self.logf: Optional[typing.TextIO] = None self.logf_base_fn = "" self.is_dut = False # running in unittest; always False self.stop_req = False self.stopping = False self.stopped = False self.reload_req = False self.reload_mutex = threading.Lock() self.stop_cond = threading.Condition() self.nsigs = 3 self.retcode = 0 self.httpsrv_up = 0 self.qr_tsz = None self.log_mutex = threading.Lock() self.cday = 0 self.cmon = 0 self.tstack = 0.0 self.iphash = HMaccas(os.path.join(self.E.cfg, "iphash"), 8) if args.sss or args.s >= 3: args.ss = True args.no_dav = True args.no_logues = True args.no_readme = True args.lo = args.lo or "cpp-%Y-%m%d-%H%M%S.txt.xz" args.ls = args.ls or "**,*,ln,p,r" if args.ss or args.s >= 2: args.s = True args.unpost = 0 args.no_del = True args.no_mv = True args.reflink = True args.dav_auth = True args.vague_403 = True args.nih = True if args.s: args.dotpart = True args.no_thumb = True args.no_mtag_ff = True args.no_robots = True args.force_js = True if not self._process_config(): raise Exception(BAD_CFG) # for non-http clients (ftp, tftp) self.bans: dict[str, int] = {} self.gpwd = Garda(self.args.ban_pw) self.gpwc = Garda(self.args.ban_pwc) self.g404 = Garda(self.args.ban_404) self.g403 = Garda(self.args.ban_403) self.g422 = Garda(self.args.ban_422, False) self.gmal = Garda(self.args.ban_422) self.gurl = Garda(self.args.ban_url) self.log_div = 10 ** (6 - args.log_tdec) self.log_efmt = "%02d:%02d:%02d.%0{}d".format(args.log_tdec) self.log_dfmt = "%04d-%04d-%06d.%0{}d".format(args.log_tdec) self.log = self._log_disabled if args.q else self._log_enabled if args.lo: self._setup_logfile(printed) lg = logging.getLogger() lh = HLog(self.log) lg.handlers = [lh] lg.setLevel(logging.DEBUG) self._check_env() if args.stackmon: start_stackmon(args.stackmon, 0) if args.log_thrs: start_log_thrs(self.log, args.log_thrs, 0) if not args.use_fpool and args.j != 1: args.no_fpool = True t = "multithreading enabled with -j {}, so disabling fpool -- this can reduce upload performance on some filesystems, and make some antivirus-softwares " c = 0 if ANYWIN: t += "(especially Microsoft Defender) stress your CPU and HDD severely during big uploads" c = 3 else: t += "consume more resources (CPU/HDD) than normal" self.log("root", t.format(args.j), c) if not args.no_fpool and args.j != 1: t = "WARNING: ignoring --use-fpool because multithreading (-j{}) is enabled" self.log("root", t.format(args.j), c=3) args.no_fpool = True args.p_nodav = [int(x.strip()) for x in args.p_nodav.split(",") if x] if args.dav_port and args.dav_port not in args.p: args.p.append(args.dav_port) for name, arg in ( ("iobuf", "iobuf"), ("s-rd-sz", "s_rd_sz"), ("s-wr-sz", "s_wr_sz"), ): zi = getattr(args, arg) if zi < 32768: t = "WARNING: expect very poor performance because you specified a very low value (%d) for --%s" self.log("root", t % (zi, name), 3) zi = 2 zi2 = 2 ** (zi - 1).bit_length() if zi != zi2: zi3 = 2 ** ((zi - 1).bit_length() - 1) t = "WARNING: expect poor performance because --%s is not a power-of-two; consider using %d or %d instead of %d" self.log("root", t % (name, zi2, zi3, zi), 3) if args.s_rd_sz > args.iobuf: t = "WARNING: --s-rd-sz (%d) is larger than --iobuf (%d); this may lead to reduced performance" self.log("root", t % (args.s_rd_sz, args.iobuf), 3) zs = "" if args.th_ram_max < 0.22: zs = "generate thumbnails" elif args.th_ram_max < 1: zs = "generate audio waveforms or spectrograms" if zs: t = "WARNING: --th-ram-max is very small (%.2f GiB); will not be able to %s" self.log("root", t % (args.th_ram_max, zs), 3) if args.chpw and args.have_idp_hdrs and "pw" not in args.auth_ord.split(","): t = "ERROR: user-changeable passwords is not compatible with your current configuration. Choose one of these options to fix it:\n option1: disable --chpw\n option2: remove all use of IdP features; --idp-*\n option3: change --auth-ord to something like pw,idp,ipu" self.log("root", t, 1) raise Exception(t) noch = set() for zs in args.chpw_no or []: zsl = [x.strip() for x in zs.split(",")] noch.update([x for x in zsl if x]) args.chpw_no = noch if args.ipu: iu, nm = load_ipu(self.log, args.ipu, True) setattr(args, "ipu_iu", iu) setattr(args, "ipu_nm", nm) if args.ipr: ipr = load_ipr(self.log, args.ipr, True) setattr(args, "ipr_u", ipr) for zs in "ah_salt fk_salt dk_salt".split(): if getattr(args, "show_%s" % (zs,)): self.log("root", "effective %s is %s" % (zs, getattr(args, zs))) if args.ah_cli or args.ah_gen: args.idp_store = 0 args.no_ses = True args.shr = "" if args.idp_store and args.have_idp_hdrs: self.setup_db("idp") if not self.args.no_ses: self.setup_db("ses") args.shr1 = "" if args.shr: self.setup_share_db() bri = "zy"[args.theme % 2 :][:1] ch = "abcdefghijklmnopqrstuvwx"[int(args.theme / 2)] args.theme = "{0}{1} {0} {1}".format(ch, bri) if args.no_stack: args.stack_who = "no" if args.nid: args.du_who = "no" args.du_iwho = n_du_who(args.du_who) if args.ver and args.ver_who == "no": args.ver_who = "all" args.ver_iwho = n_ver_who(args.ver_who) if args.nih: args.vname = "" args.doctitle = args.doctitle.replace(" @ --name", "") else: args.vname = args.name args.doctitle = args.doctitle.replace("--name", args.vname) args.bname = args.bname.replace("--name", args.vname) or args.vname for zs in "shr_site up_site".split(): if getattr(args, zs) == "--site": setattr(args, zs, args.site) if args.log_fk: args.log_fk = re.compile(args.log_fk) # initiate all services to manage self.asrv = AuthSrv(self.args, self.log, dargs=self.dargs) ramdisk_chk(self.asrv) if args.cgen: self.asrv.cgen() if args.exit == "cfg": sys.exit(0) if args.ls: self.asrv.dbg_ls() if not ANYWIN: self._setlimits() self.log("root", "max clients: {}".format(self.args.nc)) self.tcpsrv = TcpSrv(self) if not self.tcpsrv.srv and self.args.ign_ebind_all: self.args.no_fastboot = True self.up2k = Up2k(self) self._feature_test() decs = {k.strip(): 1 for k in self.args.th_dec.split(",")} if not HAVE_VIPS: decs.pop("vips", None) if not HAVE_PIL: decs.pop("pil", None) if not HAVE_RAW: decs.pop("raw", None) if not HAVE_FFMPEG or not HAVE_FFPROBE: decs.pop("ff", None) # compressed formats; "s3z=s3m.zip, s3gz=s3m.gz, ..." zlss = [x.strip().lower().split("=", 1) for x in args.au_unpk.split(",")] args.au_unpk = {x[0]: x[1] for x in zlss} self.args.th_dec = list(decs.keys()) self.thumbsrv = None want_ff = False if not args.no_thumb: t = ", ".join(self.args.th_dec) or "(None available)" self.log("thumb", "decoder preference: {}".format(t)) if self.args.th_dec: self.thumbsrv = ThumbSrv(self) else: want_ff = True msg = "need either Pillow, pyvips, or FFmpeg to create thumbnails; for example:\n{0}{1} -m pip install --user Pillow\n{0}{1} -m pip install --user pyvips\n{0}apt install ffmpeg" msg = msg.format(" " * 37, os.path.basename(pybin)) if EXE: msg = "copyparty.exe cannot use Pillow or pyvips; need ffprobe.exe and ffmpeg.exe to create thumbnails" self.log("thumb", msg, c=3) if not args.no_acode and args.no_thumb: msg = "setting --no-acode because --no-thumb (sorry)" self.log("thumb", msg, c=6) args.no_acode = True if not args.no_acode and (not HAVE_FFMPEG or not HAVE_FFPROBE): msg = "setting --no-acode because either FFmpeg or FFprobe is not available" self.log("thumb", msg, c=6) args.no_acode = True want_ff = True if want_ff and ANYWIN: self.log("thumb", "download FFmpeg to fix it:\033[0m " + FFMPEG_URL, 3) if not args.no_acode: if not re.match("^(0|[qv][0-9]|[0-9]{2,3}k)$", args.q_mp3.lower()): t = "invalid mp3 transcoding quality [%s] specified; only supports [0] to disable, a CBR value such as [192k], or a CQ/CRF value such as [v2]" raise Exception(t % (args.q_mp3,)) else: zss = set(args.th_r_ffa.split(",") + args.th_r_ffv.split(",")) args.au_unpk = { k: v for k, v in args.au_unpk.items() if v.split(".")[0] not in zss } args.th_poke = min(args.th_poke, args.th_maxage, args.ac_maxage) zms = "" if not args.https_only: zms += "d" if not args.http_only: zms += "D" if args.sftp: from .sftpd import Sftpd self.sftpd: Optional[Sftpd] = None if args.ftp or args.ftps: from .ftpd import Ftpd self.ftpd: Optional[Ftpd] = None zms += "f" if args.ftp else "F" if args.tftp: from .tftpd import Tftpd self.tftpd: Optional[Tftpd] = None if args.sftp or args.ftp or args.ftps or args.tftp: Daemon(self.start_ftpd, "start_tftpd") if args.smb: # impacket.dcerpc is noisy about listen timeouts sto = socket.getdefaulttimeout() socket.setdefaulttimeout(None) from .smbd import SMB self.smbd = SMB(self) socket.setdefaulttimeout(sto) self.smbd.start() zms += "s" if not args.zms: args.zms = zms self.zc_ngen = 0 self.mdns: Optional["MDNS"] = None self.ssdp: Optional["SSDPd"] = None # decide which worker impl to use if self.check_mp_enable(): from .broker_mp import BrokerMp as Broker else: from .broker_thr import BrokerThr as Broker # type: ignore self.broker = Broker(self) # create netmaps early to avoid firewall gaps, # but the mutex blocks multiprocessing startup for zs in "ipu_nm ftp_ipa_nm tftp_ipa_nm".split(): try: getattr(args, zs).mutex = threading.Lock() except: pass if args.ipr: for nm in args.ipr_u.values(): nm.mutex = threading.Lock() def _db_onfail_ses(self) -> None: self.args.no_ses = True def _db_onfail_idp(self) -> None: self.args.idp_store = 0 def setup_db(self, which: str) -> None: if which == "ses": native_ver = VER_SESSION_DB db_path = self.args.ses_db desc = "sessions-db" pathopt = "ses-db" sanchk_q = "select count(*) from us" createfun = self._create_session_db failfun = self._db_onfail_ses elif which == "idp": native_ver = VER_IDP_DB db_path = self.args.idp_db desc = "idp-db" pathopt = "idp-db" sanchk_q = "select count(*) from us" createfun = self._create_idp_db failfun = self._db_onfail_idp else: raise Exception("unknown cachetype") if not db_path.endswith(".db"): zs = "config option --%s (the %s) was configured to [%s] which is invalid; must be a filepath ending with .db" self.log("root", zs % (pathopt, desc, db_path), 1) raise Exception(BAD_CFG) if not HAVE_SQLITE3: failfun() if which == "ses": zs = "disabling sessions, will use plaintext passwords in cookies" elif which == "idp": zs = "disabling idp-db, will be unable to remember IdP-volumes after a restart" self.log("root", "WARNING: sqlite3 not available; %s" % (zs,), 3) return assert sqlite3 # type: ignore # !rm db_lock = db_path + ".lock" try: create = not os.path.getsize(db_path) except: create = True zs = "creating new" if create else "opening" self.log("root", "%s %s %s" % (zs, desc, db_path)) for tries in range(2): sver = 0 try: db = sqlite3.connect(db_path) cur = db.cursor() try: zs = "select v from kv where k='sver'" sver = cur.execute(zs).fetchall()[0][0] if sver > native_ver: zs = "this version of copyparty only understands %s v%d and older; the db is v%d" raise Exception(zs % (desc, native_ver, sver)) cur.execute(sanchk_q).fetchone() except: if sver: raise sver = createfun(cur) err = self._verify_db( cur, which, pathopt, db_path, desc, sver, native_ver ) if err: tries = 99 self.args.no_ses = True self.log("root", err, 3) break except Exception as ex: if tries or sver > native_ver: raise t = "%s is unusable; deleting and recreating: %r" self.log("root", t % (desc, ex), 3) try: cur.close() # type: ignore except: pass try: db.close() # type: ignore except: pass try: os.unlink(db_lock) except: pass os.unlink(db_path) def _create_session_db(self, cur: "sqlite3.Cursor") -> int: sch = [ r"create table kv (k text, v int)", r"create table us (un text, si text, t0 int)", # username, session-id, creation-time r"create index us_un on us(un)", r"create index us_si on us(si)", r"create index us_t0 on us(t0)", r"insert into kv values ('sver', 1)", ] for cmd in sch: cur.execute(cmd) self.log("root", "created new sessions-db") return 1 def _create_idp_db(self, cur: "sqlite3.Cursor") -> int: sch = [ r"create table kv (k text, v int)", r"create table us (un text, gs text)", # username, groups r"create index us_un on us(un)", r"insert into kv values ('sver', 1)", ] for cmd in sch: cur.execute(cmd) self.log("root", "created new idp-db") return 1 def _verify_db( self, cur: "sqlite3.Cursor", which: str, pathopt: str, db_path: str, desc: str, sver: int, native_ver: int, ) -> str: # ensure writable (maybe owned by other user) db = cur.connection try: zil = cur.execute("select v from kv where k='pid'").fetchall() if len(zil) > 1: raise Exception() owner = zil[0][0] except: owner = 0 if which == "ses": cons = "Will now disable sessions and instead use plaintext passwords in cookies." elif which == "idp": cons = "Each IdP-volume will not become available until its associated user sends their first request." else: raise Exception() if not lock_file(db_path + ".lock"): t = "the %s [%s] is already in use by another copyparty instance (pid:%d). This is not supported; please provide another database with --%s or give this copyparty-instance its entirely separate config-folder by setting another path in the XDG_CONFIG_HOME env-var. You can also disable this safeguard by setting env-var PRTY_NO_DB_LOCK=1. %s" return t % (desc, db_path, owner, pathopt, cons) vars = (("pid", os.getpid()), ("ts", int(time.time() * 1000))) if owner: # wear-estimate: 2 cells; offsets 0x10, 0x50, 0x19720 for k, v in vars: cur.execute("update kv set v=? where k=?", (v, k)) else: # wear-estimate: 3~4 cells; offsets 0x10, 0x50, 0x19180, 0x19710, 0x36000, 0x360b0, 0x36b90 for k, v in vars: cur.execute("insert into kv values(?, ?)", (k, v)) if sver < native_ver: cur.execute("delete from kv where k='sver'") cur.execute("insert into kv values('sver',?)", (native_ver,)) db.commit() cur.close() db.close() return "" def setup_share_db(self) -> None: al = self.args if not HAVE_SQLITE3: self.log("root", "sqlite3 not available; disabling --shr", 1) al.shr = "" return assert sqlite3 # type: ignore # !rm al.shr = al.shr.strip("/") if "/" in al.shr or not al.shr: t = "config error: --shr must be the name of a virtual toplevel directory to put shares inside" self.log("root", t, 1) raise Exception(t) al.shr = "/%s/" % (al.shr,) al.shr1 = al.shr[1:] # policy: # the shares-db is important, so panic if something is wrong db_path = self.args.shr_db db_lock = db_path + ".lock" try: create = not os.path.getsize(db_path) except: create = True zs = "creating new" if create else "opening" self.log("root", "%s shares-db %s" % (zs, db_path)) sver = 0 try: db = sqlite3.connect(db_path) cur = db.cursor() if not create: zs = "select v from kv where k='sver'" sver = cur.execute(zs).fetchall()[0][0] if sver > VER_SHARES_DB: zs = "this version of copyparty only understands shares-db v%d and older; the db is v%d" raise Exception(zs % (VER_SHARES_DB, sver)) cur.execute("select count(*) from sh").fetchone() except Exception as ex: t = "could not open shares-db; will now panic...\nthe following database must be repaired or deleted before you can launch copyparty:\n%s\n\nERROR: %s\n\nadditional details:\n%s\n" self.log("root", t % (db_path, ex, min_ex()), 1) raise try: zil = cur.execute("select v from kv where k='pid'").fetchall() if len(zil) > 1: raise Exception() owner = zil[0][0] except: owner = 0 if not lock_file(db_lock): t = "the shares-db [%s] is already in use by another copyparty instance (pid:%d). This is not supported; please provide another database with --shr-db or give this copyparty-instance its entirely separate config-folder by setting another path in the XDG_CONFIG_HOME env-var. You can also disable this safeguard by setting env-var PRTY_NO_DB_LOCK=1. Will now panic." t = t % (db_path, owner) self.log("root", t, 1) raise Exception(t) sch1 = [ r"create table kv (k text, v int)", r"create table sh (k text, pw text, vp text, pr text, st int, un text, t0 int, t1 int)", # sharekey, password, src, perms, numFiles, owner, created, expires ] sch2 = [ r"create table sf (k text, vp text)", r"create index sf_k on sf(k)", r"create index sh_k on sh(k)", r"create index sh_t1 on sh(t1)", r"insert into kv values ('sver', 2)", ] assert db # type: ignore # !rm assert cur # type: ignore # !rm if not sver: sver = VER_SHARES_DB for cmd in sch1 + sch2: cur.execute(cmd) self.log("root", "created new shares-db") if sver == 1: for cmd in sch2: cur.execute(cmd) cur.execute("update sh set st = 0") self.log("root", "shares-db schema upgrade ok") if sver < VER_SHARES_DB: cur.execute("delete from kv where k='sver'") cur.execute("insert into kv values('sver',?)", (VER_SHARES_DB,)) vars = (("pid", os.getpid()), ("ts", int(time.time() * 1000))) if owner: # wear-estimate: same as sessions-db for k, v in vars: cur.execute("update kv set v=? where k=?", (v, k)) else: for k, v in vars: cur.execute("insert into kv values(?, ?)", (k, v)) db.commit() cur.close() db.close() def start_ftpd(self) -> None: time.sleep(30) if hasattr(self, "sftpd") and not self.sftpd: self.restart_sftpd() if hasattr(self, "ftpd") and not self.ftpd: self.restart_ftpd() if hasattr(self, "tftpd") and not self.tftpd: self.restart_tftpd() def restart_sftpd(self) -> None: if not hasattr(self, "sftpd"): return from .sftpd import Sftpd if self.sftpd: return # todo self.sftpd = Sftpd(self) self.sftpd.run() self.log("root", "started SFTPd") def restart_ftpd(self) -> None: if not hasattr(self, "ftpd"): return from .ftpd import Ftpd if self.ftpd: return # todo if not os.path.exists(self.args.cert): ensure_cert(self.log, self.args) self.ftpd = Ftpd(self) self.log("root", "started FTPd") def restart_tftpd(self) -> None: if not hasattr(self, "tftpd"): return from .tftpd import Tftpd if self.tftpd: return # todo self.tftpd = Tftpd(self) def thr_httpsrv_up(self) -> None: time.sleep(1 if self.args.ign_ebind_all else 5) expected = self.broker.num_workers * self.tcpsrv.nsrv failed = expected - self.httpsrv_up if not failed: return if self.args.ign_ebind_all: if not self.tcpsrv.srv: for _ in range(self.broker.num_workers): self.broker.say("cb_httpsrv_up") return if self.args.ign_ebind and self.tcpsrv.srv: return t = "{}/{} workers failed to start" t = t.format(failed, expected) self.log("root", t, 1) self.retcode = 1 self.sigterm() def sigterm(self) -> None: self.signal_handler(signal.SIGTERM, None) def sticky_qr(self) -> None: self._sticky_qr() def _unsticky_qr(self, flush=True) -> None: print("\033[s\033[J\033[r\033[u", file=sys.stderr, end="") if flush: sys.stderr.flush() def _sticky_qr(self, force: bool = False) -> None: sz = termsize() if self.qr_tsz == sz: if not force: return else: force = False if self.qr_tsz: self._unsticky_qr(False) else: atexit.register(self._unsticky_qr) tw, th = self.qr_tsz = sz zs1, qr = self.tcpsrv.qr.split("\n", 1) url, colr = zs1.split(" ", 1) nl = len(qr.split("\n")) # numlines lp = 3 if nl * 2 + 4 < tw else 0 # leftpad lp0 = lp if self.args.qr_pin == 2: url = "" else: while lp and (nl + lp) * 2 + len(url) + 1 > tw: lp -= 1 if (nl + lp) * 2 + len(url) + 1 > tw: qr = url + "\n" + qr url = "" nl += 1 lp = lp0 sh = 1 + th - nl if lp: zs = " " * lp qr = zs + qr.replace("\n", "\n" + zs) if url: url = "%s\033[%d;%dH%s\033[0m" % (colr, sh + 1, (nl + lp) * 2, url) qr = colr + qr t = "%s\033[%dA" % ("\n" * nl, nl) t = "%s\033[s\033[1;%dr\033[%dH%s%s\033[u" % (t, sh - 1, sh, qr, url) if not force: self.log("qr", "sticky-qrcode %sx%s,%s" % (tw, th, sh), 6) self.pr(t, file=sys.stderr, end="") def _qr_thr(self): qr = self.tcpsrv.qr w8 = self.args.qr_wait if w8: time.sleep(w8) self.log("qr-code", qr) if self.args.qr_stdout: self.pr(self.tcpsrv.qr) if self.args.qr_stderr: self.pr(self.tcpsrv.qr, file=sys.stderr) w8 = self.args.qr_every msg = "%s\033[%dA" % (qr, len(qr.split("\n"))) while w8: time.sleep(w8) if self.stopping: break if self.args.qr_pin: self._sticky_qr(True) else: self.log("qr-code", msg) w8 = self.args.qr_winch while w8: time.sleep(w8) if self.stopping: break self._sticky_qr() def cb_httpsrv_up(self) -> None: self.httpsrv_up += 1 if self.httpsrv_up != self.broker.num_workers: return ar = self.args for _ in range(10 if ar.sftp or ar.ftp or ar.ftps else 0): time.sleep(0.03) if self.ftpd if ar.ftp or ar.ftps else ar.sftp: break if self.tcpsrv.qr: if self.args.qr_pin: self.sticky_qr() if self.args.qr_wait or self.args.qr_every or self.args.qr_winch: Daemon(self._qr_thr, "qr") else: if not self.args.qr_pin: self.log("qr-code", self.tcpsrv.qr) if self.args.qr_stdout: self.pr(self.tcpsrv.qr) if self.args.qr_stderr: self.pr(self.tcpsrv.qr, file=sys.stderr) else: self.log("root", "workers OK\n") self.after_httpsrv_up() def after_httpsrv_up(self) -> None: self.up2k.init_vols() Daemon(self.sd_notify, "sd-notify") def _feature_test(self) -> None: fok = [] fng = [] t_ff = "transcode audio, create spectrograms, video thumbnails" to_check = [ (HAVE_SQLITE3, "sqlite", "sessions and file/media indexing"), (HAVE_PIL, "pillow", "image thumbnails (plenty fast)"), (HAVE_VIPS, "vips", "image thumbnails (faster, eats more ram)"), (H_PIL_WEBP, "pillow-webp", "create thumbnails as webp files"), (HAVE_FFMPEG, "ffmpeg", t_ff + ", good-but-slow image thumbnails"), (HAVE_FFPROBE, "ffprobe", t_ff + ", read audio/media tags"), (HAVE_MUTAGEN, "mutagen", "read audio tags (ffprobe is better but slower)"), (HAVE_ARGON2, "argon2", "secure password hashing (advanced users only)"), (HAVE_ZMQ, "pyzmq", "send zeromq messages from event-hooks"), (H_PIL_HEIF, "pillow-heif", "read .heif pics with pillow (rarely useful)"), (H_PIL_AVIF, "pillow-avif", "read .avif pics with pillow (rarely useful)"), (HAVE_RAW, "rawpy", "read RAW images"), ] if ANYWIN: to_check += [ (HAVE_PSUTIL, "psutil", "improved plugin cleanup (rarely useful)") ] verbose = self.args.deps if verbose: self.log("dependencies", "") for have, feat, what in to_check: lst = fok if have else fng lst.append((feat, what)) if verbose: zi = 2 if have else 5 sgot = "found" if have else "missing" t = "%7s: %s \033[36m(%s)" self.log("dependencies", t % (sgot, feat, what), zi) if verbose: self.log("dependencies", "") return sok = ", ".join(x[0] for x in fok) sng = ", ".join(x[0] for x in fng) t = "" if sok: t += "OK: \033[32m" + sok if sng: if t: t += ", " t += "\033[0mNG: \033[35m" + sng t += "\033[0m, see --deps (this is fine btw)" self.log("optional-dependencies", t, 6) def _check_env(self) -> None: al = self.args if self.args.no_bauth: t = "WARNING: --no-bauth disables support for the Android app; you may want to use --bauth-last instead" self.log("root", t, 3) if self.args.bauth_last: self.log("root", "WARNING: ignoring --bauth-last due to --no-bauth", 3) have_tcp = False for zs in al.i: if not zs.startswith(("unix:", "fd:")): have_tcp = True if not have_tcp: zb = False zs = "z zm zm4 zm6 zmv zmvv zs zsv zv" for zs in zs.split(): if getattr(al, zs, False): setattr(al, zs, False) zb = True if zb: t = "not listening on any ip-addresses (only unix-sockets and/or FDs); cannot enable zeroconf/mdns/ssdp as requested" self.log("root", t, 3) if not self.args.no_dav: from .dxml import DXML_OK if not DXML_OK: if not self.args.no_dav: self.args.no_dav = True t = "WARNING:\nDisabling WebDAV support because dxml selftest failed. Please report this bug;\n%s\n...and include the following information in the bug-report:\n%s | expat %s\n" self.log("root", t % (URL_BUG, VERSIONS, expat_ver()), 1) if ( not E.scfg and not al.unsafe_state and not os.environ.get("PRTY_UNSAFE_STATE") ): t = "because runtime config is currently being stored in an untrusted emergency-fallback location. Please fix your environment so either XDG_CONFIG_HOME or ~/.config can be used instead, or disable this safeguard with --unsafe-state or env-var PRTY_UNSAFE_STATE=1." if not al.no_ses: al.no_ses = True t2 = "A consequence of this misconfiguration is that passwords will now be sent in the HTTP-header of every request!" self.log("root", "WARNING:\nWill disable sessions %s %s" % (t, t2), 1) if al.idp_store == 1: al.idp_store = 0 self.log("root", "WARNING:\nDisabling --idp-store %s" % (t,), 3) if al.idp_store: t2 = "ERROR: Cannot enable --idp-store %s" % (t,) self.log("root", t2, 1) raise Exception(t2) if al.shr: t2 = "ERROR: Cannot enable shares %s" % (t,) self.log("root", t2, 1) raise Exception(t2) def _process_config(self) -> bool: al = self.args al.zm_on = al.zm_on or al.z_on al.zs_on = al.zs_on or al.z_on al.zm_off = al.zm_off or al.z_off al.zs_off = al.zs_off or al.z_off ns = "zm_on zm_off zs_on zs_off acao acam" for n in ns.split(" "): vs = getattr(al, n).split(",") vs = [x.strip() for x in vs] vs = [x for x in vs if x] setattr(al, n, vs) ns = "acao acam" for n in ns.split(" "): vs = getattr(al, n) vd = {zs: 1 for zs in vs} setattr(al, n, vd) ns = "acao" for n in ns.split(" "): vs = getattr(al, n) vs = [x.lower() for x in vs] setattr(al, n, vs) ns = "ihead ohead" for n in ns.split(" "): vs = getattr(al, n) or [] vs = [x.lower() for x in vs] setattr(al, n, vs) R = al.rp_loc if "//" in R or ":" in R: t = "found URL in --rp-loc; it should be just the location, for example /foo/bar" raise Exception(t) al.R = R = R.strip("/") al.SR = "/" + R if R else "" al.RS = R + "/" if R else "" al.SRS = "/" + R + "/" if R else "/" if al.rsp_jtr: al.rsp_slp = 0.000001 zsl = al.th_covers.split(",") zsl = [x.strip() for x in zsl] zsl = [x for x in zsl if x] al.th_covers = zsl al.th_coversd = zsl + ["." + x for x in zsl] al.th_covers_set = set(al.th_covers) al.th_coversd_set = set(al.th_coversd) for k in "c".split(" "): vl = getattr(al, k) if not vl: continue vl = [os.path.expandvars(os.path.expanduser(x)) for x in vl] setattr(al, k, vl) for k in "lo hist dbpath ssl_log".split(" "): vs = getattr(al, k) if vs: vs = os.path.expandvars(os.path.expanduser(vs)) setattr(al, k, vs) for k in "idp_adm stats_u".split(" "): vs = getattr(al, k) vsa = [x.strip() for x in vs.split(",")] vsa = [x.lower() for x in vsa if x] setattr(al, k + "_set", set(vsa)) for k in "smsg".split(" "): vs = getattr(al, k) vsa = [x.strip() for x in vs.split(",")] vsa = [x.upper() for x in vsa if x] setattr(al, k + "_set", set(vsa)) zs = "dav_ua1 sus_urls nonsus_urls ua_nodav ua_nodoc ua_nozip" for k in zs.split(" "): vs = getattr(al, k) if not vs or vs == "no": setattr(al, k, None) else: setattr(al, k, re.compile(vs)) for k in "tftp_lsf".split(" "): vs = getattr(al, k) if not vs or vs == "no": setattr(al, k, None) else: setattr(al, k, re.compile("^" + vs + "$")) if al.banmsg.startswith("@"): with open(al.banmsg[1:], "rb") as f: al.banmsg_b = f.read() else: al.banmsg_b = al.banmsg.encode("utf-8") + b"\n" if not al.sus_urls: al.ban_url = "no" elif al.ban_url == "no": al.sus_urls = None zs = "fika idp_h_grp idp_h_key pw_hdr pw_urlp xf_host xf_proto xf_proto_fb xff_hdr" for k in zs.split(" "): setattr(al, k, str(getattr(al, k)).lower().strip()) al.idp_h_usr = [x.lower() for x in al.idp_h_usr or []] al.idp_hm_usr_p = {} for zs0 in al.idp_hm_usr or []: try: sep = zs0[:1] hn, zs1, zs2 = zs0[1:].split(sep) hn = hn.lower() if hn in al.idp_hm_usr_p: al.idp_hm_usr_p[hn][zs1] = zs2 else: al.idp_hm_usr_p[hn] = {zs1: zs2} except: raise Exception("invalid --idp-hm-usr [%s]" % (zs0,)) zs1 = "" zs2 = "" zs = al.idp_chsub while zs: if zs[:1] != "|": raise Exception("invalid --idp-chsub; expected another | but got " + zs) zs1 += zs[1:2] zs2 += zs[2:3] zs = zs[3:] al.idp_chsub_tr = umktrans(zs1, zs2) al.sftp_ipa_nm = build_netmap(al.sftp_ipa or al.ipa or al.ipar, True) al.ftp_ipa_nm = build_netmap(al.ftp_ipa or al.ipa or al.ipar, True) al.tftp_ipa_nm = build_netmap(al.tftp_ipa or al.ipa or al.ipar, True) al.sftp_key2u = { "%s %s" % (x[1], x[2]): x[0] for x in [x.split(" ") for x in al.sftp_key or []] } mte = ODict.fromkeys(DEF_MTE.split(","), True) al.mte = odfusion(mte, al.mte) mth = ODict.fromkeys(DEF_MTH.split(","), True) al.mth = odfusion(mth, al.mth) exp = ODict.fromkeys(DEF_EXP.split(" "), True) al.exp_md = odfusion(exp, al.exp_md.replace(" ", ",")) al.exp_lg = odfusion(exp, al.exp_lg.replace(" ", ",")) for k in ["no_hash", "no_idx", "og_ua", "srch_excl"]: ptn = getattr(self.args, k) if ptn: setattr(self.args, k, re.compile(ptn)) for k in ["idp_gsep"]: ptn = getattr(self.args, k) if "]" in ptn: ptn = "]" + ptn.replace("]", "") if "[" in ptn: ptn = ptn.replace("[", "") + "[" if "-" in ptn: ptn = ptn.replace("-", "") + "-" ptn = ptn.replace("\\", "\\\\").replace("^", "\\^") setattr(self.args, k, re.compile("[%s]" % (ptn,))) try: zf1, zf2 = self.args.rm_retry.split("/") self.args.rm_re_t = float(zf1) self.args.rm_re_r = float(zf2) except: raise Exception("invalid --rm-retry [%s]" % (self.args.rm_retry,)) try: zf1, zf2 = self.args.mv_retry.split("/") self.args.mv_re_t = float(zf1) self.args.mv_re_r = float(zf2) except: raise Exception("invalid --mv-retry [%s]" % (self.args.mv_retry,)) if self.args.vc_url: zi = max(1, int(self.args.vc_age)) if zi < 3 and "api.copyparty.eu" in self.args.vc_url: zi = 3 self.log("root", "vc-age too low for copyparty.eu; will use 3 hours") self.args.vc_age = zi al.js_utc = "false" if al.localtime else "true" al.tcolor = al.tcolor.lstrip("#") if len(al.tcolor) == 3: # fc5 => ffcc55 al.tcolor = "".join([x * 2 for x in al.tcolor]) if self.args.name_url: zs = html_escape(self.args.name_url, True, True) zs = '<a href="%s">%s</a>' % (zs, self.args.name) else: zs = self.args.name self.args.name_html = zs zs = al.u2sz zsl = [x.strip() for x in zs.split(",")] if len(zsl) not in (1, 3): t = "invalid --u2sz; must be either one number, or a comma-separated list of three numbers (min,default,max)" raise Exception(t) if len(zsl) < 3: zsl = ["1", zs, zs] zi2 = 1 for zs in zsl: zi = int(zs) # arbitrary constraint (anything above 2 GiB is probably unintended) if zi < 1 or zi > 2047: raise Exception("invalid --u2sz; minimum is 1, max is 2047") if zi < zi2: raise Exception("invalid --u2sz; values must be equal or ascending") zi2 = zi al.u2sz = ",".join(zsl) derive_args(al) return True def _ipa2re(self, txt) -> Optional[re.Pattern]: if txt in ("any", "0", ""): return None zs = txt.replace(" ", "").replace(".", "\\.").replace(",", "|") return re.compile("^(?:" + zs + ")") def _setlimits(self) -> None: try: import resource soft, hard = [ int(x) if x > 0 else 1024 * 1024 for x in list(resource.getrlimit(resource.RLIMIT_NOFILE)) ] except: self.log("root", "failed to read rlimits from os", 6) return if not soft or not hard: t = "got bogus rlimits from os ({}, {})" self.log("root", t.format(soft, hard), 6) return want = self.args.nc * 4 new_soft = min(hard, want) if new_soft < soft: return # t = "requesting rlimit_nofile({}), have {}" # self.log("root", t.format(new_soft, soft), 6) try: import resource resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft, hard)) soft = new_soft except: t = "rlimit denied; max open files: {}" self.log("root", t.format(soft), 3) return if soft < want: t = "max open files: {} (wanted {} for -nc {})" self.log("root", t.format(soft, want, self.args.nc), 3) self.args.nc = min(self.args.nc, soft // 2) def _logname(self) -> str: dt = datetime.now(self.tz) fn = str(self.args.lo) for fs in "YmdHMS": fs = "%" + fs if fs in fn: fn = fn.replace(fs, dt.strftime(fs)) return fn def _setup_logfile(self, printed: str) -> None: base_fn = fn = sel_fn = self._logname() do_xz = fn.lower().endswith(".xz") if fn != self.args.lo: ctr = 0 # yup this is a race; if started sufficiently concurrently, two # copyparties can grab the same logfile (considered and ignored) while os.path.exists(sel_fn): ctr += 1 sel_fn = "{}.{}".format(fn, ctr) fn = sel_fn try: bos.makedirs(os.path.dirname(fn)) except: pass try: if do_xz: import lzma lh = lzma.open(fn, "wt", encoding="utf-8", errors="replace", preset=0) self.args.no_logflush = True else: lh = open(fn, "wt", encoding="utf-8", errors="replace") except: import codecs lh = codecs.open(fn, "w", encoding="utf-8", errors="replace") if getattr(self.args, "free_umask", False): os.fchmod(lh.fileno(), 0o644) argv = [pybin] + self.argv if hasattr(shlex, "quote"): argv = [shlex.quote(x) for x in argv] else: argv = ['"{}"'.format(x) for x in argv] msg = "[+] opened logfile [{}]\n".format(fn) printed += msg t = "t0: {:.3f}\nargv: {}\n\n{}" lh.write(t.format(self.E.t0, " ".join(argv), printed)) self.logf = lh self.logf_base_fn = base_fn print(msg, end="") def run(self) -> None: self.tcpsrv.run() if getattr(self.args, "z_chk", 0) and ( getattr(self.args, "zm", False) or getattr(self.args, "zs", False) ): Daemon(self.tcpsrv.netmon, "netmon") Daemon(self.thr_httpsrv_up, "sig-hsrv-up2") if self.args.vc_url: Daemon(self.check_ver, "ver-chk") sigs = [signal.SIGINT, signal.SIGTERM] if not ANYWIN: sigs.append(signal.SIGUSR1) for sig in sigs: signal.signal(sig, self.signal_handler) # macos hangs after shutdown on sigterm with while-sleep, # windows cannot ^c stop_cond (and win10 does the macos thing but winxp is fine??) # linux is fine with both, # never lucky if ANYWIN: # msys-python probably fine but >msys-python Daemon(self.stop_thr, "svchub-sig") try: while not self.stop_req: time.sleep(1) except: pass self.shutdown() # cant join; eats signals on win10 while not self.stopped: time.sleep(0.1) else: self.stop_thr() def start_zeroconf(self) -> None: self.zc_ngen += 1 if getattr(self.args, "zm", False): try: from .mdns import MDNS if self.mdns: self.mdns.stop(True) self.mdns = MDNS(self, self.zc_ngen) Daemon(self.mdns.run, "mdns") except: self.log("root", "mdns startup failed;\n" + min_ex(), 3) if getattr(self.args, "zs", False): try: from .ssdp import SSDPd if self.ssdp: self.ssdp.stop() self.ssdp = SSDPd(self, self.zc_ngen) Daemon(self.ssdp.run, "ssdp") except: self.log("root", "ssdp startup failed;\n" + min_ex(), 3) def reload(self, rescan_all_vols: bool, up2k: bool) -> str: t = "users, volumes, and volflags have been reloaded" with self.reload_mutex: self.log("root", "reloading config") self.asrv.reload(9 if up2k else 4) ramdisk_chk(self.asrv) if up2k: self.up2k.reload(rescan_all_vols) t += "; volumes are now reinitializing" else: self.log("root", "reload done") t += "\n\nchanges to global options (if any) require a restart of copyparty to take effect" self.broker.reload() return t def _reload_sessions(self) -> None: with self.asrv.mutex: self.asrv.load_sessions(True) self.broker.reload_sessions() def stop_thr(self) -> None: while not self.stop_req: with self.stop_cond: self.stop_cond.wait(9001) if self.reload_req: self.reload_req = False self.reload(True, True) self.shutdown() def kill9(self, delay: float = 0.0) -> None: if delay > 0.01: time.sleep(delay) print("component stuck; issuing sigkill") time.sleep(0.1) if ANYWIN: os.system("taskkill /f /pid {}".format(os.getpid())) else: os.kill(os.getpid(), signal.SIGKILL) def signal_handler(self, sig: int, frame: Optional[FrameType]) -> None: if self.stopping: if self.nsigs <= 0: try: threading.Thread(target=self.pr, args=("OMBO BREAKER",)).start() time.sleep(0.1) except: pass self.kill9() else: self.nsigs -= 1 return if not ANYWIN and sig == signal.SIGUSR1: self.reload_req = True else: self.stop_req = True with self.stop_cond: self.stop_cond.notify_all() def shutdown(self) -> None: if self.stopping: return # start_log_thrs(print, 0.1, 1) self.stopping = True self.stop_req = True with self.stop_cond: self.stop_cond.notify_all() ret = 1 try: self.pr("OPYTHAT") tasks = [] slp = 0.0 if self.mdns: tasks.append(Daemon(self.mdns.stop, "mdns")) slp = time.time() + 0.5 if self.ssdp: tasks.append(Daemon(self.ssdp.stop, "ssdp")) slp = time.time() + 0.5 self.broker.shutdown() self.tcpsrv.shutdown() self.up2k.shutdown() if hasattr(self, "smbd"): slp = max(slp, time.time() + 0.5) tasks.append(Daemon(self.smbd.stop, "smbd")) if self.thumbsrv: self.thumbsrv.shutdown() for n in range(200): # 10s time.sleep(0.05) if self.thumbsrv.stopped(): break if n == 3: self.log("root", "waiting for thumbsrv (10sec)...") if hasattr(self, "smbd"): zf = max(time.time() - slp, 0) Daemon(self.kill9, a=(zf + 0.5,)) while time.time() < slp: if not next((x for x in tasks if x.is_alive), None): break time.sleep(0.05) self.log("root", "nailed it") ret = self.retcode except: self.pr("\033[31m[ error during shutdown ]\n{}\033[0m".format(min_ex())) raise finally: if self.args.wintitle: print("\033]0;\033\\", file=sys.stderr, end="") sys.stderr.flush() self.pr("\033[0m", end="") if self.logf: self.logf.close() self.stopped = True sys.exit(ret) def _log_disabled(self, src: str, msg: str, c: Union[int, str] = 0) -> None: if not self.logf: return with self.log_mutex: dt = datetime.now(self.tz) ts = self.log_dfmt % ( dt.year, dt.month * 100 + dt.day, (dt.hour * 100 + dt.minute) * 100 + dt.second, dt.microsecond // self.log_div, ) if self.flo == 1: fmt = "@%s [%-21s] %s\n" if not c: if "\033" in msg: msg += "\033[0m" elif isinstance(c, int): msg = "\033[3%sm%s\033[0m" % (c, msg) elif "\033" not in c: msg = "\033[%sm%s\033[0m" % (c, msg) else: msg = "%s%s\033[0m" % (c, msg) if "\033" in src: src += "\033[0m" else: if not c: fmt = "@%s LOG [%-21s] %s\n" elif c == 1: fmt = "@%s CRIT [%-21s] %s\n" elif c == 3: fmt = "@%s WARN [%-21s] %s\n" elif c == 6: fmt = "@%s BTW [%-21s] %s\n" else: fmt = "@%s LOG [%-21s] %s\n" if "\033" in src: src = RE_ANSI.sub("", src) if "\033" in msg: msg = RE_ANSI.sub("", msg) self.logf.write(fmt % (ts, src, msg)) if not self.args.no_logflush: self.logf.flush() if dt.day != self.cday or dt.month != self.cmon: self._set_next_day(dt) def _set_next_day(self, dt: datetime) -> None: if self.cday and self.logf and self.logf_base_fn != self._logname(): self.logf.close() self._setup_logfile("") self.cday = dt.day self.cmon = dt.month def _log_enabled(self, src: str, msg: str, c: Union[int, str] = 0) -> None: with self.log_mutex: dt = datetime.now(self.tz) if dt.day != self.cday or dt.month != self.cmon: if self.args.log_date: zs = dt.strftime(self.args.log_date) self.log_efmt = "%s %s" % (zs, self.log_efmt.split(" ")[-1]) zs = "{}\n" if self.no_ansi else "\033[36m{}\033[0m\n" zs = zs.format(dt.strftime("%Y-%m-%d")) print(zs, end="") self._set_next_day(dt) if self.logf: self.logf.write(zs) if self.no_ansi: if not c: fmt = "%s %-21s LOG: %s\n" elif c == 1: fmt = "%s %-21s CRIT: %s\n" elif c == 3: fmt = "%s %-21s WARN: %s\n" elif c == 6: fmt = "%s %-21s BTW: %s\n" else: fmt = "%s %-21s LOG: %s\n" if "\033" in msg: msg = RE_ANSI.sub("", msg) if "\033" in src: src = RE_ANSI.sub("", src) else: fmt = "\033[36m%s \033[33m%-21s \033[0m%s\n" if not c: pass elif isinstance(c, int): msg = "\033[3%sm%s\033[0m" % (c, msg) elif "\033" not in c: msg = "\033[%sm%s\033[0m" % (c, msg) else: msg = "%s%s\033[0m" % (c, msg) ts = self.log_efmt % ( dt.hour, dt.minute, dt.second, dt.microsecond // self.log_div, ) msg = fmt % (ts, src, msg) try: print(msg, end="") except UnicodeEncodeError: try: print(msg.encode("utf-8", "replace").decode(), end="") except: print(msg.encode("ascii", "replace").decode(), end="") except OSError as ex: if ex.errno != errno.EPIPE: raise if self.logf: self.logf.write(msg) if not self.args.no_logflush: self.logf.flush() def pr(self, *a: Any, **ka: Any) -> None: try: with self.log_mutex: print(*a, **ka) except OSError as ex: if ex.errno != errno.EPIPE: raise def check_mp_support(self) -> str: if MACOS and not os.environ.get("PRTY_FORCE_MP"): return "multiprocessing is wonky on mac osx;" elif sys.version_info < (3, 3): return "need python 3.3 or newer for multiprocessing;" try: x: mp.Queue[tuple[str, str]] = mp.Queue(1) x.put(("foo", "bar")) if x.get()[0] != "foo": raise Exception() except: return "multiprocessing is not supported on your platform;" return "" def check_mp_enable(self) -> bool: if self.args.j == 1: return False try: if mp.cpu_count() <= 1 and not os.environ.get("PRTY_FORCE_MP"): raise Exception() except: self.log("svchub", "only one CPU detected; multiprocessing disabled") return False try: # support vscode debugger (bonus: same behavior as on windows) mp.set_start_method("spawn", True) except AttributeError: # py2.7 probably, anyways dontcare pass err = self.check_mp_support() if not err: return True else: self.log("svchub", err) self.log("svchub", "cannot efficiently use multiple CPU cores") return False def sd_notify(self) -> None: try: zb = os.environ.get("NOTIFY_SOCKET") if not zb: return addr = unicode(zb) if addr.startswith("@"): addr = "\0" + addr[1:] t = "".join(x for x in addr if x in string.printable) self.log("sd_notify", t) sck = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sck.connect(addr) sck.sendall(b"READY=1") except: self.log("sd_notify", min_ex()) def log_stacks(self) -> None: td = time.time() - self.tstack if td < 300: self.log("stacks", "cooldown {}".format(td)) return self.tstack = time.time() zs = "{}\n{}".format(VERSIONS, alltrace()) zb = zs.encode("utf-8", "replace") zb = gzip.compress(zb) zs = ub64enc(zb).decode("ascii") self.log("stacks", zs) def check_ver(self) -> None: next_chk = 0 # self.args.vc_age = 2 / 60 fpath = os.path.join(self.E.cfg, "vuln_advisory.json") while not self.stopping: now = time.time() if now < next_chk: time.sleep(min(999, next_chk - now)) continue age = 0 jtxt = "" src = "[cache] " try: mtime = os.path.getmtime(fpath) age = time.time() - mtime if age < self.args.vc_age * 3600 - 69: zs, jtxt = read_utf8(None, fpath, True).split("\n", 1) if zs != self.args.vc_url: jtxt = "" except Exception as e: t = "will download advisory because cache-file %r could not be read: %s" self.log("ver-chk", t % (fpath, e), 6) if not jtxt: src = "" age = 0 try: req = Request(self.args.vc_url) with urlopen(req, timeout=30) as f: jtxt = f.read().decode("utf-8") try: with open(fpath, "wb") as f: zs = self.args.vc_url + "\n" + jtxt f.write(zs.encode("utf-8")) except Exception as e: t = "failed to write advisory to cache; %s" self.log("ver-chk", t % (e,), 3) except Exception as e: t = "failed to fetch vulnerability advisory; %s" self.log("ver-chk", t % (e,), 1) next_chk = time.time() + 699 if not jtxt: continue try: advisories = json.loads(jtxt) for adv in advisories: if adv.get("state") == "closed": continue vuln = {} for x in adv["vulnerabilities"]: if x["package"]["name"].lower() == "copyparty": vuln = x break if not vuln: continue sver = vuln["patched_versions"].strip(".v") tver = tuple([int(x) for x in sver.split(".")]) if VERSION < tver: zs = json.dumps(adv, indent=2) t = "your version (%s) has a vulnerability! please upgrade:\n%s" self.log("ver-chk", t % (S_VERSION, zs), 1) self.broker.say("httpsrv.set_bad_ver") if self.args.vc_exit: self.sigterm() return else: t = "%sok; v%s and newer is safe" self.log("ver-chk", t % (src, sver), 2) next_chk = time.time() + self.args.vc_age * 3600 - age except Exception as e: t = "failed to process vulnerability advisory; %s" self.log("ver-chk", t % (min_ex()), 1) try: os.unlink(fpath) except: pass
--- +++ @@ -110,6 +110,15 @@ class SvcHub(object): + """ + Hosts all services which cannot be parallelized due to reliance on monolithic resources. + Creates a Broker which does most of the heavy stuff; hosted services can use this to perform work: + hub.broker.<say|ask>(destination, args_list). + + Either BrokerThr (plain threads) or BrokerMP (multiprocessing) is used depending on configuration. + Nothing is returned synchronously; if you want any value returned from the call, + put() can return a queue (if want_reply=True) which has a blocking get() with the response. + """ def __init__( self, @@ -477,6 +486,9 @@ self.args.idp_store = 0 def setup_db(self, which: str) -> None: + """ + the "non-mission-critical" databases; if something looks broken then just nuke it + """ if which == "ses": native_ver = VER_SESSION_DB db_path = self.args.ses_db @@ -1638,6 +1650,7 @@ self.cmon = dt.month def _log_enabled(self, src: str, msg: str, c: Union[int, str] = 0) -> None: + """handles logging from all components""" with self.log_mutex: dt = datetime.now(self.tz) if dt.day != self.cday or dt.month != self.cmon: @@ -1861,4 +1874,4 @@ try: os.unlink(fpath) except: - pass+ pass
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/svchub.py
Add docstrings to improve code quality
# coding: utf-8 from __future__ import print_function, unicode_literals import calendar import stat import time from .authsrv import AuthSrv from .bos import bos from .sutil import StreamArc, errdesc from .util import VPTL_WIN, min_ex, sanitize_to, spack, sunpack, yieldfile, zlib if True: # pylint: disable=using-constant-test from typing import Any, Generator, Optional from .util import NamedLogger def dostime2unix(buf: bytes) -> int: t, d = sunpack(b"<HH", buf) ts = (t & 0x1F) * 2 tm = (t >> 5) & 0x3F th = t >> 11 dd = d & 0x1F dm = (d >> 5) & 0xF dy = (d >> 9) + 1980 tt = (dy, dm, dd, th, tm, ts) tf = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}" iso = tf.format(*tt) dt = time.strptime(iso, "%Y-%m-%d %H:%M:%S") return int(calendar.timegm(dt)) def unixtime2dos(ts: int) -> bytes: dy, dm, dd, th, tm, ts, _, _, _ = time.gmtime(ts + 1) bd = ((dy - 1980) << 9) + (dm << 5) + dd bt = (th << 11) + (tm << 5) + ts // 2 try: return spack(b"<HH", bt, bd) except: return b"\x00\x00\x21\x00" def gen_fdesc(sz: int, crc32: int, z64: bool) -> bytes: ret = b"\x50\x4b\x07\x08" fmt = b"<LQQ" if z64 else b"<LLL" ret += spack(fmt, crc32, sz, sz) return ret def gen_hdr( h_pos: Optional[int], z64: bool, fn: str, sz: int, lastmod: int, utf8: bool, icrc32: int, pre_crc: bool, ) -> bytes: # appnote 4.5 / zip 3.0 (2008) / unzip 6.0 (2009) says to add z64 # extinfo for values which exceed H, but that becomes an off-by-one # (can't tell if it was clamped or exactly maxval), make it obvious z64v = [sz, sz] if z64 else [] if h_pos and h_pos >= 0xFFFFFFFF: # central, also consider ptr to original header z64v.append(h_pos) # confusingly this doesn't bump if h_pos req_ver = b"\x2d\x00" if z64 else b"\x0a\x00" if icrc32: crc32 = spack(b"<L", icrc32) else: crc32 = b"\x00" * 4 if h_pos is None: # 4b magic, 2b min-ver ret = b"\x50\x4b\x03\x04" + req_ver else: # 4b magic, 2b spec-ver (1b compat, 1b os (00 dos, 03 unix)), 2b min-ver ret = b"\x50\x4b\x01\x02\x1e\x03" + req_ver ret += b"\x00" if pre_crc else b"\x08" # streaming ret += b"\x08" if utf8 else b"\x00" # appnote 6.3.2 (2007) # 2b compression, 4b time, 4b crc ret += b"\x00\x00" + unixtime2dos(lastmod) + crc32 # spec says to put zeros when !crc if bit3 (streaming) # however infozip does actual sz and it even works on winxp # (same reasoning for z64 extradata later) vsz = 0xFFFFFFFF if z64 else sz ret += spack(b"<LL", vsz, vsz) # windows support (the "?" replace below too) fn = sanitize_to(fn, VPTL_WIN) bfn = fn.encode("utf-8" if utf8 else "cp437", "replace").replace(b"?", b"_") # add ntfs (0x24) and/or unix (0x10) extrafields for utc, add z64 if requested z64_len = len(z64v) * 8 + 4 if z64v else 0 ret += spack(b"<HH", len(bfn), 0x10 + z64_len) if h_pos is not None: # 2b comment, 2b diskno ret += b"\x00" * 4 # 2b internal.attr, 4b external.attr # infozip-macos: 0100 0000 a481 (spec-ver 1e03) file:644 # infozip-macos: 0100 0100 0080 (spec-ver 1e03) file:000 # win10-zip: 0000 2000 0000 (spec-ver xx00) FILE_ATTRIBUTE_ARCHIVE ret += b"\x00\x00\x00\x00\xa4\x81" # unx # ret += b"\x00\x00\x20\x00\x00\x00" # fat # 4b local-header-ofs ret += spack(b"<L", min(h_pos, 0xFFFFFFFF)) ret += bfn # ntfs: type 0a, size 20, rsvd, attr1, len 18, mtime, atime, ctime # b"\xa3\x2f\x82\x41\x55\x68\xd8\x01" 1652616838.798941100 ~5.861518 132970904387989411 ~58615181 # nt = int((lastmod + 11644473600) * 10000000) # ret += spack(b"<HHLHHQQQ", 0xA, 0x20, 0, 1, 0x18, nt, nt, nt) # unix: type 0d, size 0c, atime, mtime, uid, gid ret += spack(b"<HHLLHH", 0xD, 0xC, int(lastmod), int(lastmod), 1000, 1000) if z64v: ret += spack(b"<HH" + b"Q" * len(z64v), 1, len(z64v) * 8, *z64v) return ret def gen_ecdr( items: list[tuple[str, int, int, int, int]], cdir_pos: int, cdir_end: int ) -> tuple[bytes, bool]: ret = b"\x50\x4b\x05\x06" # 2b ndisk, 2b disk0 ret += b"\x00" * 4 cdir_sz = cdir_end - cdir_pos nitems = min(0xFFFF, len(items)) csz = min(0xFFFFFFFF, cdir_sz) cpos = min(0xFFFFFFFF, cdir_pos) need_64 = nitems == 0xFFFF or 0xFFFFFFFF in [csz, cpos] # 2b tnfiles, 2b dnfiles, 4b dir sz, 4b dir pos ret += spack(b"<HHLL", nitems, nitems, csz, cpos) # 2b comment length ret += b"\x00\x00" return ret, need_64 def gen_ecdr64( items: list[tuple[str, int, int, int, int]], cdir_pos: int, cdir_end: int ) -> bytes: ret = b"\x50\x4b\x06\x06" # 8b own length from hereon ret += b"\x2c" + b"\x00" * 7 # 2b spec-ver, 2b min-ver ret += b"\x1e\x03\x2d\x00" # 4b ndisk, 4b disk0 ret += b"\x00" * 8 # 8b tnfiles, 8b dnfiles, 8b dir sz, 8b dir pos cdir_sz = cdir_end - cdir_pos ret += spack(b"<QQQQ", len(items), len(items), cdir_sz, cdir_pos) return ret def gen_ecdr64_loc(ecdr64_pos: int) -> bytes: ret = b"\x50\x4b\x06\x07" # 4b cdisk, 8b start of ecdr64, 4b ndisks ret += spack(b"<LQL", 0, ecdr64_pos, 1) return ret class StreamZip(StreamArc): def __init__( self, log: "NamedLogger", asrv: AuthSrv, fgen: Generator[dict[str, Any], None, None], utf8: bool = False, pre_crc: bool = False, **kwargs: Any ) -> None: super(StreamZip, self).__init__(log, asrv, fgen) self.utf8 = utf8 self.pre_crc = pre_crc self.pos = 0 self.items: list[tuple[str, int, int, int, int]] = [] def _ct(self, buf: bytes) -> bytes: self.pos += len(buf) return buf def ser(self, f: dict[str, Any]) -> Generator[bytes, None, None]: name = f["vp"] src = f["ap"] st = f["st"] if stat.S_ISDIR(st.st_mode): return sz = st.st_size ts = st.st_mtime h_pos = self.pos crc = 0 if self.pre_crc: for buf in yieldfile(src, self.args.iobuf): crc = zlib.crc32(buf, crc) crc &= 0xFFFFFFFF # some unzip-programs expect a 64bit data-descriptor # even if the only 32bit-exceeding value is the offset, # so force that by placeholdering the filesize too z64 = h_pos >= 0xFFFFFFFF or sz >= 0xFFFFFFFF buf = gen_hdr(None, z64, name, sz, ts, self.utf8, crc, self.pre_crc) yield self._ct(buf) for buf in yieldfile(src, self.args.iobuf): if not self.pre_crc: crc = zlib.crc32(buf, crc) yield self._ct(buf) crc &= 0xFFFFFFFF self.items.append((name, sz, ts, crc, h_pos)) if z64 or not self.pre_crc: buf = gen_fdesc(sz, crc, z64) yield self._ct(buf) def gen(self) -> Generator[bytes, None, None]: errf: dict[str, Any] = {} errors = [] mbuf = b"" try: for f in self.fgen: if "err" in f: errors.append((f["vp"], f["err"])) continue try: for x in self.ser(f): mbuf += x if len(mbuf) >= 16384: yield mbuf mbuf = b"" except GeneratorExit: raise except: ex = min_ex(5, True).replace("\n", "\n-- ") errors.append((f["vp"], ex)) if mbuf: yield mbuf mbuf = b"" if errors: errf, txt = errdesc(self.asrv.vfs, errors) self.log("\n".join(([repr(errf)] + txt[1:]))) for x in self.ser(errf): yield x cdir_pos = self.pos for name, sz, ts, crc, h_pos in self.items: z64 = h_pos >= 0xFFFFFFFF or sz >= 0xFFFFFFFF buf = gen_hdr(h_pos, z64, name, sz, ts, self.utf8, crc, self.pre_crc) mbuf += self._ct(buf) if len(mbuf) >= 16384: yield mbuf mbuf = b"" cdir_end = self.pos _, need_64 = gen_ecdr(self.items, cdir_pos, cdir_end) if need_64: ecdir64_pos = self.pos buf = gen_ecdr64(self.items, cdir_pos, cdir_end) mbuf += self._ct(buf) buf = gen_ecdr64_loc(ecdir64_pos) mbuf += self._ct(buf) ecdr, _ = gen_ecdr(self.items, cdir_pos, cdir_end) yield mbuf + self._ct(ecdr) finally: if errf: bos.unlink(errf["ap"])
--- +++ @@ -62,6 +62,11 @@ icrc32: int, pre_crc: bool, ) -> bytes: + """ + does regular file headers + and the central directory meme if h_pos is set + (h_pos = absolute position of the regular header) + """ # appnote 4.5 / zip 3.0 (2008) / unzip 6.0 (2009) says to add z64 # extinfo for values which exceed H, but that becomes an off-by-one @@ -139,6 +144,10 @@ def gen_ecdr( items: list[tuple[str, int, int, int, int]], cdir_pos: int, cdir_end: int ) -> tuple[bytes, bool]: + """ + summary of all file headers, + usually the zipfile footer unless something clamps + """ ret = b"\x50\x4b\x05\x06" @@ -165,6 +174,10 @@ def gen_ecdr64( items: list[tuple[str, int, int, int, int]], cdir_pos: int, cdir_end: int ) -> bytes: + """ + z64 end of central directory + added when numfiles or a headerptr clamps + """ ret = b"\x50\x4b\x06\x06" @@ -185,6 +198,11 @@ def gen_ecdr64_loc(ecdr64_pos: int) -> bytes: + """ + z64 end of central directory locator + points to ecdr64 + why + """ ret = b"\x50\x4b\x06\x07" @@ -312,4 +330,4 @@ yield mbuf + self._ct(ecdr) finally: if errf: - bos.unlink(errf["ap"])+ bos.unlink(errf["ap"])
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/szip.py
Improve my code by adding docstrings
# coding: utf-8 from __future__ import print_function, unicode_literals import errno import hashlib import json import math import os import re import shutil import stat import subprocess as sp import sys import tempfile import threading import time import traceback from copy import deepcopy from queue import Queue from .__init__ import ANYWIN, MACOS, PY2, TYPE_CHECKING, WINDOWS, E from .authsrv import LEELOO_DALLAS, SEESLOG, VFS, AuthSrv from .bos import bos from .cfg import vf_bmap, vf_cmap, vf_vmap from .fsutil import Fstab from .mtag import MParser, MTag from .util import ( E_FS_CRIT, E_FS_MEH, HAVE_FICLONE, HAVE_SQLITE3, SYMTIME, VF_CAREFUL, Daemon, MTHash, Pebkac, ProgressPrinter, absreal, alltrace, atomic_move, db_ex_chk, dir_is_empty, djoin, fsenc, gen_filekey, gen_filekey_dbg, gzip, hidedir, humansize, min_ex, pathmod, quotep, rand_name, ren_open, rmdirs, rmdirs_up, runhook, runihook, s2hms, s3dec, s3enc, sanitize_fn, set_ap_perms, set_fperms, sfsenc, spack, statdir, trystat_shutil_copy2, ub64enc, unhumanize, vjoin, vsplit, w8b64dec, w8b64enc, wunlink, ) try: from pathlib import Path except: pass if HAVE_SQLITE3: import sqlite3 DB_VER = 6 if True: # pylint: disable=using-constant-test from typing import Any, Optional, Pattern, Union if TYPE_CHECKING: from .svchub import SvcHub USE_FICLONE = HAVE_FICLONE and sys.version_info < (3, 14) if USE_FICLONE: import fcntl zsg = "avif,avifs,bmp,gif,heic,heics,heif,heifs,ico,j2p,j2k,jp2,jpeg,jpg,jpx,png,tga,tif,tiff,webp" ICV_EXTS = set(zsg.split(",")) zsg = "3gp,asf,av1,avc,avi,flv,m4v,mjpeg,mjpg,mkv,mov,mp4,mpeg,mpeg2,mpegts,mpg,mpg2,mts,nut,ogm,ogv,rm,vob,webm,wmv" VCV_EXTS = set(zsg.split(",")) zsg = "aif,aiff,alac,ape,flac,m4a,m4b,m4r,mp3,oga,ogg,opus,tak,tta,wav,wma,wv,cbz,epub" ACV_EXTS = set(zsg.split(",")) zsg = "nohash noidx xdev xvol" VF_AFFECTS_INDEXING = set(zsg.split(" ")) SBUSY = "cannot receive uploads right now;\nserver busy with %s.\nPlease wait; the client will retry..." HINT_HISTPATH = "you could try moving the database to another location (preferably an SSD or NVME drive) using either the --hist argument (global option for all volumes), or the hist volflag (just for this volume), or, if you want to keep the thumbnails in the current location and only move the database itself, then use --dbpath or volflag dbpath" NULLSTAT = os.stat_result((0, -1, -1, 0, 0, 0, 0, 0, 0, 0)) class Dbw(object): def __init__(self, c: "sqlite3.Cursor", n: int, nf: int, t: float) -> None: self.c = c self.n = n self.nf = nf self.t = t class Mpqe(object): def __init__( self, mtp: dict[str, MParser], entags: set[str], vf: dict[str, Any], w: str, abspath: str, oth_tags: dict[str, Any], ): # mtp empty = mtag self.mtp = mtp self.entags = entags self.vf = vf self.w = w self.abspath = abspath self.oth_tags = oth_tags class Up2k(object): def __init__(self, hub: "SvcHub") -> None: self.hub = hub self.asrv: AuthSrv = hub.asrv self.args = hub.args self.log_func = hub.log self.vfs = self.asrv.vfs self.acct = self.asrv.acct self.iacct = self.asrv.iacct self.grps = self.asrv.grps self.salt = self.args.warksalt self.r_hash = re.compile("^[0-9a-zA-Z_-]{44}$") self.abrt_key = "" self.gid = 0 self.gt0 = 0 self.gt1 = 0 self.stop = False self.fika = "" self.mutex = threading.Lock() self.reload_mutex = threading.Lock() self.reload_flag = 0 self.reloading = False self.blocked: Optional[str] = None self.pp: Optional[ProgressPrinter] = None self.rescan_cond = threading.Condition() self.need_rescan: set[str] = set() self.db_act = 0.0 self.reg_mutex = threading.Lock() self.registry: dict[str, dict[str, dict[str, Any]]] = {} self.flags: dict[str, dict[str, Any]] = {} self.droppable: dict[str, list[str]] = {} self.volnfiles: dict["sqlite3.Cursor", int] = {} self.volsize: dict["sqlite3.Cursor", int] = {} self.volstate: dict[str, str] = {} self.vol_act: dict[str, float] = {} self.busy_aps: dict[str, int] = {} self.dupesched: dict[str, list[tuple[str, str, float]]] = {} self.snap_prev: dict[str, Optional[tuple[int, float]]] = {} self.mtag: Optional[MTag] = None self.entags: dict[str, set[str]] = {} self.mtp_parsers: dict[str, dict[str, MParser]] = {} self.pending_tags: list[tuple[set[str], str, str, dict[str, Any]]] = [] self.hashq: Queue[ tuple[str, str, dict[str, Any], str, str, str, float, str, bool] ] = Queue() self.tagq: Queue[tuple[str, str, str, str, int, str, float]] = Queue() self.tag_event = threading.Condition() self.hashq_mutex = threading.Lock() self.n_hashq = 0 self.n_tagq = 0 self.mpool_used = False self.xiu_ptn = re.compile(r"(?:^|,)i([0-9]+)") self.xiu_busy = False # currently running hook self.xiu_asleep = True # needs rescan_cond poke to schedule self self.fx_backlog: list[tuple[str, dict[str, str], str]] = [] self.cur: dict[str, "sqlite3.Cursor"] = {} self.mem_cur = None self.sqlite_ver = None self.no_expr_idx = False self.timeout = int(max(self.args.srch_time, 50) * 1.2) + 1 self.spools: set[tempfile.SpooledTemporaryFile[bytes]] = set() if HAVE_SQLITE3: # mojibake detector assert sqlite3 # type: ignore # !rm self.mem_cur = self._orz(":memory:") self.mem_cur.execute(r"create table a (b text)") self.sqlite_ver = tuple([int(x) for x in sqlite3.sqlite_version.split(".")]) if self.sqlite_ver < (3, 9): self.no_expr_idx = True else: t = "could not initialize sqlite3, will use in-memory registry only" self.log(t, 3) self.fstab = Fstab(self.log_func, self.args, True) self.gen_fk = self._gen_fk if self.args.log_fk else gen_filekey if self.args.hash_mt < 2: self.mth: Optional[MTHash] = None else: self.mth = MTHash(self.args.hash_mt) if self.args.no_fastboot: self.deferred_init() def init_vols(self) -> None: if self.args.no_fastboot: return Daemon(self.deferred_init, "up2k-deferred-init") def unpp(self) -> None: self.gt1 = time.time() if self.pp: self.pp.end = True self.pp = None def reload(self, rescan_all_vols: bool) -> None: n = 2 if rescan_all_vols else 1 with self.reload_mutex: if self.reload_flag < n: self.reload_flag = n with self.rescan_cond: self.rescan_cond.notify_all() def _reload_thr(self) -> None: while self.pp: time.sleep(0.1) while True: with self.reload_mutex: if not self.reload_flag: break rav = self.reload_flag == 2 self.reload_flag = 0 gt1 = self.gt1 with self.mutex: self._reload(rav) while gt1 == self.gt1 or self.pp: time.sleep(0.1) self.reloading = False def _reload(self, rescan_all_vols: bool) -> None: self.log("reload #{} scheduled".format(self.gid + 1)) all_vols = self.asrv.vfs.all_vols with self.reg_mutex: scan_vols = [ k for k, v in all_vols.items() if v.realpath not in self.registry ] if rescan_all_vols: scan_vols = list(all_vols.keys()) self._rescan(all_vols, scan_vols, True, False) def deferred_init(self) -> None: all_vols = self.asrv.vfs.all_vols have_e2d = self.init_indexes(all_vols, [], False) if self.stop: # up-mt consistency not guaranteed if init is interrupted; # drop caches for a full scan on next boot with self.mutex, self.reg_mutex: self._drop_caches() self.unpp() return if not self.pp and self.args.exit == "idx": return self.hub.sigterm() if self.hub.is_dut: return Daemon(self._snapshot, "up2k-snapshot") if have_e2d: Daemon(self._hasher, "up2k-hasher") Daemon(self._sched_rescan, "up2k-rescan") if self.mtag: for n in range(max(1, self.args.mtag_mt)): Daemon(self._tagger, "tagger-{}".format(n)) def log(self, msg: str, c: Union[int, str] = 0) -> None: if self.pp: msg += "\033[K" self.log_func("up2k", msg, c) def _gen_fk(self, alg: int, salt: str, fspath: str, fsize: int, inode: int) -> str: return gen_filekey_dbg( alg, salt, fspath, fsize, inode, self.log, self.args.log_fk ) def _block(self, why: str) -> None: self.blocked = why self.log("uploads temporarily blocked due to " + why, 3) def _unblock(self) -> None: if self.blocked is not None: self.blocked = None if not self.stop: self.log("uploads are now possible", 2) def get_state(self, get_q: bool, uname: str) -> str: mtpq: Union[int, str] = 0 ups = [] up_en = not self.args.no_up_list q = "select count(w) from mt where k = 't:mtp'" got_lock = False if PY2 else self.mutex.acquire(timeout=0.5) if got_lock: try: for cur in self.cur.values() if get_q else []: try: mtpq += cur.execute(q).fetchone()[0] except: pass if uname and up_en: ups = self._active_uploads(uname) finally: self.mutex.release() else: mtpq = "(?)" if up_en: ups = [(1, 0, 0, time.time(), "cannot show list (server too busy)")] if PY2: ups = [] ups.sort(reverse=True) ret = { "volstate": self.volstate, "scanning": bool(self.pp), "hashq": self.n_hashq, "tagq": self.n_tagq, "mtpq": mtpq, "ups": ups, "dbwu": "{:.2f}".format(self.db_act), "dbwt": "{:.2f}".format( min(1000 * 24 * 60 * 60 - 1, time.time() - self.db_act) ), } return json.dumps(ret, separators=(",\n", ": ")) def _active_uploads(self, uname: str) -> list[tuple[float, int, int, str]]: ret = [] for vtop in self.vfs.aread.get(uname) or []: vfs = self.vfs.all_vols.get(vtop) if not vfs: # dbv only continue ptop = vfs.realpath tab = self.registry.get(ptop) if not tab: continue for job in tab.values(): ineed = len(job["need"]) ihash = len(job["hash"]) if ineed == ihash or not ineed: continue poke = job["poke"] zt = ( ineed / ihash, job["size"], int(job.get("t0c", poke)), int(poke), djoin(vtop, job["prel"], job["name"]), ) ret.append(zt) return ret def find_job_by_ap(self, ptop: str, ap: str) -> str: try: if ANYWIN: ap = ap.replace("\\", "/") vp = ap[len(ptop) :].strip("/") dn, fn = vsplit(vp) with self.reg_mutex: tab2 = self.registry[ptop] for job in tab2.values(): if job["prel"] == dn and job["name"] == fn: return json.dumps(job, separators=(",\n", ": ")) except: pass return "{}" def get_unfinished_by_user(self, uname, ip) -> dict[str, Any]: # returns dict due to ExceptionalQueue if PY2 or not self.reg_mutex.acquire(timeout=2): return {"timeout": 1} ret: list[tuple[int, str, int, int, int]] = [] userset = set([(uname or "\n"), "*"]) e_d = {} n = 1000 try: for ptop, tab2 in self.registry.items(): cfg = self.flags.get(ptop, e_d).get("u2abort", 1) if not cfg: continue addr = (ip or "\n") if cfg in (1, 2) else "" user = userset if cfg in (1, 3) else None for job in tab2.values(): if ( "done" in job or (user and job["user"] not in user) or (addr and addr != job["addr"]) ): continue zt5 = ( int(job["t0"]), djoin(job["vtop"], job["prel"], job["name"]), job["size"], len(job["need"]), len(job["hash"]), ) ret.append(zt5) n -= 1 if not n: break finally: self.reg_mutex.release() if ANYWIN: ret = [(x[0], x[1].replace("\\", "/"), x[2], x[3], x[4]) for x in ret] ret.sort(reverse=True) ret2 = [ { "at": at, "vp": "/" + quotep(vp), "pd": 100 - ((nn * 100) // (nh or 1)), "sz": sz, } for (at, vp, sz, nn, nh) in ret ] return {"f": ret2} def get_unfinished(self) -> str: if PY2 or not self.reg_mutex.acquire(timeout=0.5): return "" ret: dict[str, tuple[int, int]] = {} try: for ptop, tab2 in self.registry.items(): nbytes = 0 nfiles = 0 for job in tab2.values(): if "done" in job: continue nfiles += 1 try: # close enough on average nbytes += len(job["need"]) * job["size"] // len(job["hash"]) except: pass ret[ptop] = (nbytes, nfiles) finally: self.reg_mutex.release() return json.dumps(ret, separators=(",\n", ": ")) def get_volsize(self, ptop: str) -> tuple[int, int]: with self.reg_mutex: return self._get_volsize(ptop) def get_volsizes(self, ptops: list[str]) -> list[tuple[int, int]]: ret = [] with self.reg_mutex: for ptop in ptops: ret.append(self._get_volsize(ptop)) return ret def _get_volsize(self, ptop: str) -> tuple[int, int]: if "e2ds" not in self.flags.get(ptop, {}): return (0, 0) cur = self.cur[ptop] nbytes = self.volsize[cur] nfiles = self.volnfiles[cur] for j in list(self.registry.get(ptop, {}).values()): nbytes += j["size"] nfiles += 1 return (nbytes, nfiles) def rescan( self, all_vols: dict[str, VFS], scan_vols: list[str], wait: bool, fscan: bool ) -> str: with self.mutex: return self._rescan(all_vols, scan_vols, wait, fscan) def _rescan( self, all_vols: dict[str, VFS], scan_vols: list[str], wait: bool, fscan: bool ) -> str: if not wait and self.pp: return "cannot initiate; scan is already in progress" self.gid += 1 Daemon( self.init_indexes, "up2k-rescan-{}".format(scan_vols[0] if scan_vols else "all"), (all_vols, scan_vols, fscan, self.gid), ) return "" def _sched_rescan(self) -> None: volage = {} cooldown = timeout = time.time() + 3.0 while not self.stop: now = time.time() timeout = max(timeout, cooldown) wait = timeout - time.time() # self.log("SR in {:.2f}".format(wait), 5) with self.rescan_cond: self.rescan_cond.wait(wait) if self.stop: return with self.reload_mutex: if self.reload_flag and not self.reloading: self.reloading = True zs = "up2k-reload-%d" % (self.gid,) Daemon(self._reload_thr, zs) now = time.time() if now < cooldown: # self.log("SR: cd - now = {:.2f}".format(cooldown - now), 5) timeout = cooldown # wakeup means stuff to do, forget timeout continue if self.pp: # self.log("SR: pp; cd := 1", 5) cooldown = now + 1 continue cooldown = now + 3 # self.log("SR", 5) if self.args.no_lifetime and not self.args.shr: timeout = now + 9001 else: # important; not deferred by db_act timeout = self._check_lifetimes() timeout = min(self._check_forget_ip(), timeout) try: if self.args.shr: timeout = min(self._check_shares(), timeout) except Exception as ex: timeout = min(timeout, now + 60) t = "could not check for expiring shares: %r" self.log(t % (ex,), 1) try: timeout = min(timeout, now + self._check_xiu()) except Exception as ex: if "closed cursor" in str(ex): self.log("sched_rescan: lost db") return raise with self.mutex: for vp, vol in sorted(self.vfs.all_vols.items()): maxage = vol.flags.get("scan") if not maxage: continue if vp not in volage: volage[vp] = now deadline = volage[vp] + maxage if deadline <= now: self.need_rescan.add(vp) timeout = min(timeout, deadline) if self.db_act > now - self.args.db_act and self.need_rescan: # recent db activity; defer volume rescan act_timeout = self.db_act + self.args.db_act if self.need_rescan: timeout = now if timeout < act_timeout: timeout = act_timeout t = "volume rescan deferred {:.1f} sec, due to database activity" self.log(t.format(timeout - now)) continue with self.mutex: vols = list(sorted(self.need_rescan)) self.need_rescan.clear() if vols: cooldown = now + 10 err = self.rescan(self.vfs.all_vols, vols, False, False) if err: for v in vols: self.need_rescan.add(v) continue for v in vols: volage[v] = now def _check_forget_ip(self) -> float: now = time.time() timeout = now + 9001 for vp, vol in sorted(self.vfs.all_vols.items()): maxage = vol.flags["forget_ip"] if not maxage: continue cur = self.cur.get(vol.realpath) if not cur: continue cutoff = now - maxage * 60 for _ in range(2): q = "select ip, at from up where ip > '' order by +at limit 1" with self.mutex: hits = cur.execute(q).fetchall() if not hits: break remains = hits[0][1] - cutoff if remains > 0: timeout = min(timeout, now + remains) break q = "update up set ip = '' where ip > '' and at <= %d" cur.execute(q % (cutoff,)) zi = cur.rowcount cur.connection.commit() t = "forget-ip(%d) removed %d IPs from db [/%s]" self.log(t % (maxage, zi, vol.vpath)) timeout = min(timeout, now + 900) return timeout def _check_lifetimes(self) -> float: now = time.time() timeout = now + 9001 for vp, vol in sorted(self.vfs.all_vols.items()): lifetime = vol.flags.get("lifetime") if not lifetime: continue cur = self.cur.get(vol.realpath) if not cur: continue nrm = 0 deadline = time.time() - lifetime timeout = min(timeout, now + lifetime) q = "select rd, fn from up where at > 0 and at < ? limit 100" while True: with self.mutex: hits = cur.execute(q, (deadline,)).fetchall() if not hits: break for rd, fn in hits: if rd.startswith("//") or fn.startswith("//"): rd, fn = s3dec(rd, fn) fvp = ("%s/%s" % (rd, fn)).strip("/") if vp: fvp = "%s/%s" % (vp, fvp) self._handle_rm(LEELOO_DALLAS, "", fvp, [], True, False) nrm += 1 if nrm: self.log("%d files graduated in /%s" % (nrm, vp)) if timeout < 10: continue q = "select at from up where at > 0 order by at limit 1" with self.mutex: hits = cur.execute(q).fetchone() if hits: timeout = min(timeout, now + lifetime - (now - hits[0])) return timeout def _check_shares(self) -> float: assert sqlite3 # type: ignore # !rm now = time.time() timeout = now + 9001 maxage = self.args.shr_rt * 60 low = now - maxage vn = self.vfs.nodes.get(self.args.shr.strip("/")) active = vn and vn.nodes db = sqlite3.connect(self.args.shr_db, timeout=2) cur = db.cursor() q = "select k from sh where t1 and t1 <= ?" rm = [x[0] for x in cur.execute(q, (now,))] if active else [] if rm: assert vn and vn.nodes # type: ignore # self.log("chk_shr: %d" % (len(rm),)) zss = set(rm) rm = [zs for zs in vn.nodes if zs in zss] reload = bool(rm) if reload: self.log("disabling expired shares %s" % (rm,)) rm = [x[0] for x in cur.execute(q, (low,))] if rm: self.log("forgetting expired shares %s" % (rm,)) cur.executemany("delete from sh where k=?", [(x,) for x in rm]) cur.executemany("delete from sf where k=?", [(x,) for x in rm]) db.commit() if reload: Daemon(self.hub.reload, "sharedrop", (False, False)) q = "select min(t1) from sh where t1 > ?" (earliest,) = cur.execute(q, (1,)).fetchone() if earliest: # deadline for revoking regular access timeout = min(timeout, earliest + maxage) (earliest,) = cur.execute(q, (now - 2,)).fetchone() if earliest: # deadline for revival; drop entirely timeout = min(timeout, earliest) cur.close() db.close() if self.args.shr_v: self.log("next shr_chk = %d (%d)" % (timeout, timeout - time.time())) return timeout def _check_xiu(self) -> float: if self.xiu_busy: return 2 ret = 9001 for _, vol in sorted(self.vfs.all_vols.items()): rp = vol.realpath cur = self.cur.get(rp) if not cur: continue with self.mutex: q = "select distinct c from iu" cds = cur.execute(q).fetchall() if not cds: continue run_cds: list[int] = [] for cd in sorted([x[0] for x in cds]): delta = cd - (time.time() - self.vol_act[rp]) if delta > 0: ret = min(ret, delta) break run_cds.append(cd) if run_cds: self.xiu_busy = True Daemon(self._run_xius, "xiu", (vol, run_cds)) return 2 return ret def _run_xius(self, vol: VFS, cds: list[int]): for cd in cds: self._run_xiu(vol, cd) self.xiu_busy = False self.xiu_asleep = True def _run_xiu(self, vol: VFS, cd: int): rp = vol.realpath cur = self.cur[rp] # t0 = time.time() with self.mutex: q = "select w,rd,fn from iu where c={} limit 80386" wrfs = cur.execute(q.format(cd)).fetchall() if not wrfs: return # dont wanna rebox so use format instead of prepared q = "delete from iu where w=? and +rd=? and +fn=? and +c={}" cur.executemany(q.format(cd), wrfs) cur.connection.commit() q = "select * from up where substr(w,1,16)=? and +rd=? and +fn=?" ups = [] for wrf in wrfs: up = cur.execute(q, wrf).fetchone() if up: ups.append(up) # t1 = time.time() # self.log("mapped {} warks in {:.3f} sec".format(len(wrfs), t1 - t0)) # "mapped 10989 warks in 0.126 sec" cmds = self.flags[rp]["xiu"] for cmd in cmds: m = self.xiu_ptn.search(cmd) ccd = int(m.group(1)) if m else 5 if ccd != cd: continue self.log("xiu: %d# %r" % (len(wrfs), cmd)) runihook(self.log, self.args.hook_v, cmd, vol, ups) def _vis_job_progress(self, job: dict[str, Any]) -> str: perc = 100 - (len(job["need"]) * 100.0 / (len(job["hash"]) or 1)) path = djoin(job["ptop"], job["prel"], job["name"]) return "{:5.1f}% {}".format(perc, path) def _vis_reg_progress(self, reg: dict[str, dict[str, Any]]) -> list[str]: ret = [] for _, job in reg.items(): if job["need"]: ret.append(self._vis_job_progress(job)) return ret def _expr_idx_filter(self, flags: dict[str, Any]) -> tuple[bool, dict[str, Any]]: if not self.no_expr_idx: return False, flags ret = {k: v for k, v in flags.items() if not k.startswith("e2t")} if len(ret) == len(flags): return False, flags return True, ret def init_indexes( self, all_vols: dict[str, VFS], scan_vols: list[str], fscan: bool, gid: int = 0 ) -> bool: if not gid: with self.mutex: gid = self.gid self.gt0 = time.time() nspin = 0 while True: nspin += 1 if nspin > 1: time.sleep(0.1) with self.mutex: if gid != self.gid: return False if self.pp: continue self.pp = ProgressPrinter(self.log, self.args) if not self.hub.is_dut: self.pp.start() break if gid: self.log("reload #%d running" % (gid,)) self.vfs = self.asrv.vfs self.acct = self.asrv.acct self.iacct = self.asrv.iacct self.grps = self.asrv.grps have_e2d = self.args.have_idp_hdrs or self.args.chpw or self.args.shr vols = list(all_vols.values()) t0 = time.time() if self.no_expr_idx: modified = False for vol in vols: m, f = self._expr_idx_filter(vol.flags) if m: vol.flags = f modified = True if modified: msg = "disabling -e2t because your sqlite belongs in a museum" self.log(msg, c=3) live_vols = [] with self.mutex, self.reg_mutex: # only need to protect register_vpath but all in one go feels right for vol in vols: if bos.path.isfile(vol.realpath): self.volstate[vol.vpath] = "online (just-a-file)" t = "NOTE: volume [/%s] is a file, not a folder" self.log(t % (vol.vpath,)) continue try: # mkdir gonna happen at snap anyways; bos.makedirs(vol.realpath, vf=vol.flags) dir_is_empty(self.log_func, not self.args.no_scandir, vol.realpath) except Exception as ex: self.volstate[vol.vpath] = "OFFLINE (cannot access folder)" self.log("cannot access %s: %r" % (vol.realpath, ex), c=1) continue if scan_vols and vol.vpath not in scan_vols: continue if not self.register_vpath(vol.realpath, vol.flags): # self.log("db not enable for {}".format(m, vol.realpath)) continue live_vols.append(vol) if vol.vpath not in self.volstate: self.volstate[vol.vpath] = "OFFLINE (pending initialization)" vols = live_vols need_vac = {} need_mtag = False for vol in vols: if "e2t" in vol.flags: need_mtag = True if need_mtag and not self.mtag: self.mtag = MTag(self.log_func, self.args) if not self.mtag.usable: self.mtag = None # e2ds(a) volumes first if next((zv for zv in vols if "e2ds" in zv.flags), None): self._block("indexing") if self.args.re_dhash or [zv for zv in vols if "e2tsr" in zv.flags]: self.args.re_dhash = False with self.mutex, self.reg_mutex: self._drop_caches() for vol in vols: if self.stop or gid != self.gid: break en = set(vol.flags.get("mte", {})) self.entags[vol.realpath] = en if "e2d" in vol.flags: have_e2d = True if "e2ds" in vol.flags or fscan: self.volstate[vol.vpath] = "busy (hashing files)" _, vac = self._build_file_index(vol, list(all_vols.values())) if vac: need_vac[vol] = True if "e2v" in vol.flags: t = "online (integrity-check pending)" elif "e2ts" in vol.flags: t = "online (tags pending)" else: t = "online, idle" self.volstate[vol.vpath] = t self._unblock() # file contents verification for vol in vols: if self.stop: break if "e2v" not in vol.flags: continue t = "online (verifying integrity)" self.volstate[vol.vpath] = t self.log("{} [{}]".format(t, vol.realpath)) nmod = self._verify_integrity(vol) if nmod: self.log("modified {} entries in the db".format(nmod), 3) need_vac[vol] = True if "e2ts" in vol.flags: t = "online (tags pending)" else: t = "online, idle" self.volstate[vol.vpath] = t # open the rest + do any e2ts(a) needed_mutagen = False for vol in vols: if self.stop: break if "e2ts" not in vol.flags: continue t = "online (reading tags)" self.volstate[vol.vpath] = t self.log("{} [{}]".format(t, vol.realpath)) nadd, nrm, success = self._build_tags_index(vol) if not success: needed_mutagen = True if nadd or nrm: need_vac[vol] = True self.volstate[vol.vpath] = "online (mtp soon)" for vol in need_vac: with self.mutex, self.reg_mutex: reg = self.register_vpath(vol.realpath, vol.flags) assert reg # !rm cur, _ = reg with self.mutex: cur.connection.commit() cur.execute("vacuum") if self.stop: return False for vol in all_vols.values(): if vol.flags["dbd"] == "acid": continue with self.mutex, self.reg_mutex: reg = self.register_vpath(vol.realpath, vol.flags) try: assert reg # !rm cur, db_path = reg if bos.path.getsize(db_path + "-wal") < 1024 * 1024 * 5: continue except: continue try: with self.mutex: cur.execute("pragma wal_checkpoint(truncate)") try: cur.execute("commit") # absolutely necessary! for some reason except: pass cur.connection.commit() # this one maybe not except Exception as ex: self.log("checkpoint failed: {}".format(ex), 3) if self.stop: return False self.pp.end = True msg = "{} volumes in {:.2f} sec" self.log(msg.format(len(vols), time.time() - t0)) if needed_mutagen: msg = "could not read tags because no backends are available (Mutagen or FFprobe)" self.log(msg, c=1) t = "online (running mtp)" if self.mtag else "online, idle" for vol in vols: self.volstate[vol.vpath] = t if self.mtag: Daemon(self._run_all_mtp, "up2k-mtp-scan", (gid,)) else: self.unpp() return have_e2d def register_vpath( self, ptop: str, flags: dict[str, Any] ) -> Optional[tuple["sqlite3.Cursor", str]]: histpath = self.vfs.dbpaths.get(ptop) if not histpath: self.log("no dbpath for %r" % (ptop,)) return None db_path = os.path.join(histpath, "up2k.db") if ptop in self.registry: try: return self.cur[ptop], db_path except: return None vpath = "?" for k, v in self.vfs.all_vols.items(): if v.realpath == ptop: vpath = k _, flags = self._expr_idx_filter(flags) n4g = bool(flags.get("noforget")) ft = "\033[0;32m{}{:.0}" ff = "\033[0;35m{}{:.0}" fv = "\033[0;36m{}:\033[90m{}" zs = "bcasechk du_iwho emb_all emb_lgs emb_mds ext_th_d html_head html_head_d html_head_s ls_q_m put_name2 mv_re_r mv_re_t rm_re_r rm_re_t oh_f oh_g rw_edit_set srch_re_dots srch_re_nodot zipmax zipmaxn_v zipmaxs_v" fx = set(zs.split()) fd = vf_bmap() fd.update(vf_cmap()) fd.update(vf_vmap()) fd = {v: k for k, v in fd.items()} fl = { k: v for k, v in flags.items() if k not in fd or ( v != getattr(self.args, fd[k]) and str(v) != str(getattr(self.args, fd[k])) ) } for k1, k2 in vf_cmap().items(): if k1 not in fl or k1 in fx: continue if str(fl[k1]) == str(getattr(self.args, k2)): del fl[k1] else: fl[k1] = ",".join(x for x in fl[k1]) if fl["chmod_d"] == int(self.args.chmod_d, 8): fl.pop("chmod_d") try: if fl["chmod_f"] == int(self.args.chmod_f or "-1", 8): fl.pop("chmod_f") except: pass for k in ("chmod_f", "chmod_d"): try: fl[k] = "%o" % (fl[k]) except: pass a = [ (ft if v is True else ff if v is False else fv).format(k, str(v)) for k, v in fl.items() if k not in fx ] if not a: a = ["\033[90mall-default"] if a: zs = " ".join(sorted(a)) zs = zs.replace("90mre.compile(", "90m(") # nohash self.log("/{} {}".format(vpath + ("/" if vpath else ""), zs), "35") reg = {} drp = None emptylist = [] dotpart = "." if self.args.dotpart else "" snap = os.path.join(histpath, "up2k.snap") if bos.path.exists(snap): with gzip.GzipFile(snap, "rb") as f: j = f.read().decode("utf-8") reg2 = json.loads(j) try: drp = reg2["droppable"] reg2 = reg2["registry"] except: pass reg = reg2 # diff-golf if reg2 and "dwrk" not in reg2[next(iter(reg2))]: for job in reg2.values(): job["dwrk"] = job["wark"] rm = [] for k, job in reg2.items(): job["ptop"] = ptop is_done = "done" in job if is_done: job["need"] = job["hash"] = emptylist else: if "need" not in job: job["need"] = [] if "hash" not in job: job["hash"] = [] if is_done: fp = djoin(ptop, job["prel"], job["name"]) else: fp = djoin(ptop, job["prel"], dotpart + job["name"] + ".PARTIAL") if bos.path.exists(fp): if is_done: continue job["poke"] = time.time() job["busy"] = {} else: self.log("ign deleted file in snap: %r" % (fp,)) if not n4g: rm.append(k) for x in rm: del reg2[x] # optimize pre-1.15.4 entries if next((x for x in reg.values() if "done" in x and "poke" in x), None): zsl = "host tnam busy sprs poke t0c".split() for job in reg.values(): if "done" in job: for k in zsl: job.pop(k, None) if drp is None: drp = [k for k, v in reg.items() if not v["need"]] else: drp = [x for x in drp if x in reg] t = "loaded snap {} |{}| ({})".format(snap, len(reg.keys()), len(drp or [])) ta = [t] + self._vis_reg_progress(reg) self.log("\n".join(ta)) self.flags[ptop] = flags self.vol_act[ptop] = 0.0 self.registry[ptop] = reg self.droppable[ptop] = drp or [] self.regdrop(ptop, "") if not HAVE_SQLITE3 or "e2d" not in flags or "d2d" in flags: return None try: if bos.makedirs(histpath): hidedir(histpath) except Exception as ex: t = "failed to initialize volume '/%s': %s" self.log(t % (vpath, ex), 1) return None try: cur = self._open_db_wd(db_path) # speeds measured uploading 520 small files on a WD20SPZX (SMR 2.5" 5400rpm 4kb) dbd = flags["dbd"] if dbd == "acid": # 217.5s; python-defaults zs = "delete" sync = "full" elif dbd == "swal": # 88.0s; still 99.9% safe (can lose a bit of on OS crash) zs = "wal" sync = "full" elif dbd == "yolo": # 2.7s; may lose entire db on OS crash zs = "wal" sync = "off" else: # 4.1s; corruption-safe but more likely to lose wal zs = "wal" sync = "normal" try: amode = cur.execute("pragma journal_mode=" + zs).fetchone()[0] if amode.lower() != zs.lower(): t = "sqlite failed to set journal_mode {}; got {}" raise Exception(t.format(zs, amode)) except Exception as ex: if sync != "off": sync = "full" t = "reverting to sync={} because {}" self.log(t.format(sync, ex)) cur.execute("pragma synchronous=" + sync) cur.connection.commit() self._verify_db_cache(cur, vpath) self.cur[ptop] = cur self.volsize[cur] = 0 self.volnfiles[cur] = 0 return cur, db_path except: msg = "ERROR: cannot use database at [%s]:\n%s\n\033[33mhint: %s\n" self.log(msg % (db_path, traceback.format_exc(), HINT_HISTPATH), 1) return None def _verify_db_cache(self, cur: "sqlite3.Cursor", vpath: str) -> None: # check if list of intersecting volumes changed since last use; drop caches if so prefix = (vpath + "/").lstrip("/") vps = [x for x in self.vfs.all_vols if x.startswith(prefix)] vps.sort() seed = [x[len(prefix) :] for x in vps] # also consider volflags which affect indexing for vp in vps: vf = self.vfs.all_vols[vp].flags vf = {k: v for k, v in vf.items() if k in VF_AFFECTS_INDEXING} seed.append(str(sorted(vf.items()))) zb = hashlib.sha1("\n".join(seed).encode("utf-8", "replace")).digest() vcfg = ub64enc(zb[:18]).decode("ascii") c = cur.execute("select v from kv where k = 'volcfg'") try: (oldcfg,) = c.fetchone() except: oldcfg = "" if oldcfg != vcfg: cur.execute("delete from kv where k = 'volcfg'") cur.execute("delete from dh") cur.execute("delete from cv") cur.execute("insert into kv values ('volcfg',?)", (vcfg,)) cur.connection.commit() def _build_file_index(self, vol: VFS, all_vols: list[VFS]) -> tuple[bool, bool]: do_vac = False top = vol.realpath rei = vol.flags.get("noidx") reh = vol.flags.get("nohash") n4g = bool(vol.flags.get("noforget")) ffat = "fat32" in vol.flags cst = bos.stat(top) dev = cst.st_dev if vol.flags.get("xdev") else 0 with self.mutex: with self.reg_mutex: reg = self.register_vpath(top, vol.flags) assert reg and self.pp # !rm cur, db_path = reg db = Dbw(cur, 0, 0, time.time()) self.pp.n = next(db.c.execute("select count(w) from up"))[0] excl = [ vol.realpath + "/" + d.vpath[len(vol.vpath) :].lstrip("/") for d in all_vols if d != vol and (d.vpath.startswith(vol.vpath + "/") or not vol.vpath) ] excl += [absreal(x) for x in excl] excl += list(self.vfs.histtab.values()) excl += list(self.vfs.dbpaths.values()) if WINDOWS: excl = [x.replace("/", "\\") for x in excl] else: # ~/.wine/dosdevices/z:/ and such excl.extend(("/dev", "/proc", "/run", "/sys")) excl = list({k: 1 for k in excl}) if self.args.re_dirsz: db.c.execute("delete from ds") db.n += 1 rtop = absreal(top) n_add = n_rm = 0 try: if dir_is_empty(self.log_func, not self.args.no_scandir, rtop): t = "volume /%s at [%s] is empty; will not be indexed as this could be due to an offline filesystem" self.log(t % (vol.vpath, rtop), 6) return True, False if not vol.check_landmarks(): t = "volume /%s at [%s] will not be indexed due to bad landmarks" self.log(t % (vol.vpath, rtop), 6) return True, False n_add, _, _ = self._build_dir( db, top, set(excl), top, rtop, rei, reh, n4g, ffat, [], cst, dev, bool(vol.flags.get("xvol")), ) if not n4g: n_rm = self._drop_lost(db.c, top, excl) except Exception as ex: t = "failed to index volume [{}]:\n{}" self.log(t.format(top, min_ex()), c=1) if db_ex_chk(self.log, ex, db_path): self.hub.log_stacks() if db.n: self.log("commit %d new files; %d updates" % (db.nf, db.n)) if self.args.no_dhash: if db.c.execute("select d from dh").fetchone(): db.c.execute("delete from dh") self.log("forgetting dhashes in {}".format(top)) elif n_add or n_rm: self._set_tagscan(db.c, True) db.c.connection.commit() if ( vol.flags.get("vmaxb") or vol.flags.get("vmaxn") or (self.args.stats and not self.args.nos_vol) ): zs = "select count(sz), sum(sz) from up" vn, vb = db.c.execute(zs).fetchone() vb = vb or 0 vb += vn * 2048 self.volsize[db.c] = vb self.volnfiles[db.c] = vn vmaxb = unhumanize(vol.flags.get("vmaxb") or "0") vmaxn = unhumanize(vol.flags.get("vmaxn") or "0") t = "{:>5} / {:>5} ( {:>5} / {:>5} files) in {}".format( humansize(vb, True), humansize(vmaxb, True), humansize(vn, True).rstrip("B"), humansize(vmaxn, True).rstrip("B"), vol.realpath, ) self.log(t) return True, bool(n_add or n_rm or do_vac) def _fika(self, db: Dbw) -> None: zs = self.fika self.fika = "" if zs not in self.args.fika: return t = "fika(%s); commit %d new files; %d updates" self.log(t % (zs, db.nf, db.n)) db.c.connection.commit() db.n = db.nf = 0 db.t = time.time() self.mutex.release() time.sleep(0.5) self.mutex.acquire() db.t = time.time() def _build_dir( self, db: Dbw, top: str, excl: set[str], cdir: str, rcdir: str, rei: Optional[Pattern[str]], reh: Optional[Pattern[str]], n4g: bool, ffat: bool, seen: list[str], cst: os.stat_result, dev: int, xvol: bool, ) -> tuple[int, int, int]: if xvol and not rcdir.startswith(top): self.log("skip xvol: %r -> %r" % (cdir, rcdir), 6) return 0, 0, 0 if rcdir in seen: t = "bailing from symlink loop,\n prev: %r\n curr: %r\n from: %r" self.log(t % (seen[-1], rcdir, cdir), 3) return 0, 0, 0 # total-files-added, total-num-files, recursive-size tfa = tnf = rsz = 0 seen = seen + [rcdir] unreg: list[str] = [] files: list[tuple[int, int, str]] = [] fat32 = True cv = vcv = acv = "" e_d = {} th_cvd = self.args.th_coversd th_cvds = self.args.th_coversd_set scan_pr_s = self.args.scan_pr_s assert self.pp and self.mem_cur # !rm self.pp.msg = "a%d %s" % (self.pp.n, cdir) rd = cdir[len(top) :].strip("/") if WINDOWS: rd = rd.replace("\\", "/").strip("/") rds = rd + "/" if rd else "" cdirs = cdir + os.sep g = statdir(self.log_func, not self.args.no_scandir, True, cdir, False) gl = sorted(g) partials = set([x[0] for x in gl if "PARTIAL" in x[0]]) for iname, inf in gl: if self.fika: if not self.stop: self._fika(db) if self.stop: self.fika = "f" return -1, 0, 0 rp = rds + iname abspath = cdirs + iname if rei and rei.search(abspath): unreg.append(rp) continue lmod = int(inf.st_mtime) if stat.S_ISLNK(inf.st_mode): try: inf = bos.stat(abspath) except: continue sz = inf.st_size if fat32 and not ffat and inf.st_mtime % 2: fat32 = False if stat.S_ISDIR(inf.st_mode): rap = absreal(abspath) if ( dev and inf.st_dev != dev and not (ANYWIN and bos.stat(rap).st_dev == dev) ): self.log("skip xdev %s->%s: %r" % (dev, inf.st_dev, abspath), 6) continue if abspath in excl or rap in excl: unreg.append(rp) continue if iname == ".th" and bos.path.isdir(os.path.join(abspath, "top")): # abandoned or foreign, skip continue # self.log(" dir: {}".format(abspath)) try: i1, i2, i3 = self._build_dir( db, top, excl, abspath, rap, rei, reh, n4g, fat32, seen, inf, dev, xvol, ) tfa += i1 tnf += i2 rsz += i3 except: t = "failed to index subdir %r:\n%s" self.log(t % (abspath, min_ex()), 1) elif not stat.S_ISREG(inf.st_mode): self.log("skip type-0%o file %r" % (inf.st_mode, abspath)) else: # self.log("file: {}".format(abspath)) if rp.endswith(".PARTIAL") and time.time() - lmod < 60: # rescan during upload continue if not sz and ( "%s.PARTIAL" % (iname,) in partials or ".%s.PARTIAL" % (iname,) in partials ): # placeholder for unfinished upload continue rsz += sz files.append((sz, lmod, iname)) if sz: liname = iname.lower() ext = liname.rsplit(".", 1)[-1] if ( liname in th_cvds or (not cv and ext in ICV_EXTS and not iname.startswith(".")) ) and ( not cv or liname not in th_cvds or cv.lower() not in th_cvds or th_cvd.index(liname) < th_cvd.index(cv.lower()) ): cv = iname elif not vcv and ext in VCV_EXTS and not iname.startswith("."): vcv = iname elif not acv and ext in ACV_EXTS and not iname.startswith("."): acv = iname if not cv: cv = vcv or acv if not self.args.no_dirsz: tnf += len(files) q = "select sz, nf from ds where rd=? limit 1" try: db_sz, db_nf = db.c.execute(q, (rd,)).fetchone() or (-1, -1) if rsz != db_sz or tnf != db_nf: db.c.execute("delete from ds where rd=?", (rd,)) db.c.execute("insert into ds values (?,?,?)", (rd, rsz, tnf)) db.n += 1 except: pass # mojibake rd # folder of 1000 files = ~1 MiB RAM best-case (tiny filenames); # free up stuff we're done with before dhashing gl = [] partials.clear() if not self.args.no_dhash: if len(files) < 9000: zh = hashlib.sha1(str(files).encode("utf-8", "replace")) else: zh = hashlib.sha1() _ = [zh.update(str(x).encode("utf-8", "replace")) for x in files] zh.update(cv.encode("utf-8", "replace")) zh.update(spack(b"<d", cst.st_mtime)) dhash = ub64enc(zh.digest()[:12]).decode("ascii") sql = "select d from dh where d=? and +h=?" try: c = db.c.execute(sql, (rd, dhash)) drd = rd except: drd = "//" + w8b64enc(rd) c = db.c.execute(sql, (drd, dhash)) if c.fetchone(): return tfa, tnf, rsz if cv and rd: # mojibake not supported (for performance / simplicity): try: q = "select * from cv where rd=? and dn=? and +fn=?" crd, cdn = rd.rsplit("/", 1) if "/" in rd else ("", rd) if not db.c.execute(q, (crd, cdn, cv)).fetchone(): db.c.execute("delete from cv where rd=? and dn=?", (crd, cdn)) db.c.execute("insert into cv values (?,?,?)", (crd, cdn, cv)) db.n += 1 except Exception as ex: self.log("cover %r/%r failed: %s" % (rd, cv, ex), 6) seen_files = set([x[2] for x in files]) # for dropcheck for sz, lmod, fn in files: if self.fika: if not self.stop: self._fika(db) if self.stop: self.fika = "f" return -1, 0, 0 rp = rds + fn abspath = cdirs + fn nohash = reh.search(abspath) if reh else False sql = "select w, mt, sz, ip, at, un from up where rd = ? and fn = ?" try: c = db.c.execute(sql, (rd, fn)) except: c = db.c.execute(sql, s3enc(self.mem_cur, rd, fn)) in_db = list(c.fetchall()) if in_db: self.pp.n -= 1 dw, dts, dsz, ip, at, un = in_db[0] if len(in_db) > 1: t = "WARN: multiple entries: %r => %r |%d|\n%r" rep_db = "\n".join([repr(x) for x in in_db]) self.log(t % (top, rp, len(in_db), rep_db)) dts = -1 if fat32 and abs(dts - lmod) == 1: dts = lmod if dts == lmod and dsz == sz and (nohash or dw[0] != "#" or not sz): continue if un is None: un = "" t = "reindex %r => %r mtime(%s/%s) size(%s/%s)" self.log(t % (top, rp, dts, lmod, dsz, sz)) self.db_rm(db.c, e_d, rd, fn, 0) tfa += 1 db.n += 1 in_db = [] else: dw = "" ip = "" at = 0 un = "" self.pp.msg = "a%d %s" % (self.pp.n, abspath) if nohash or not sz: wark = up2k_wark_from_metadata(self.salt, sz, lmod, rd, fn) else: if sz > 1024 * 1024 * scan_pr_s: self.log("file: %r" % (abspath,)) try: hashes, _ = self._hashlist_from_file( abspath, "a{}, ".format(self.pp.n) ) except Exception as ex: self._ex_hash(ex, abspath) continue if not hashes: return -1, 0, 0 wark = up2k_wark_from_hashlist(self.salt, sz, hashes) if dw and dw != wark: ip = "" at = 0 un = "" # skip upload hooks by not providing vflags self.db_add(db.c, e_d, rd, fn, lmod, sz, "", "", wark, wark, "", un, ip, at) db.n += 1 db.nf += 1 tfa += 1 td = time.time() - db.t if db.n >= 4096 or td >= 60: self.log("commit %d new files; %d updates" % (db.nf, db.n)) db.c.connection.commit() db.n = db.nf = 0 db.t = time.time() if not self.args.no_dhash: db.c.execute("delete from dh where d = ?", (drd,)) # type: ignore db.c.execute("insert into dh values (?,?)", (drd, dhash)) # type: ignore if self.stop: return -1, 0, 0 # drop shadowed folders for sh_rd in unreg: n = 0 q = "select count(w) from up where (rd=? or rd like ?||'/%')" for sh_erd in [sh_rd, "//" + w8b64enc(sh_rd)]: try: erd_erd = (sh_erd, sh_erd) n = db.c.execute(q, erd_erd).fetchone()[0] break except: pass assert erd_erd # type: ignore # !rm if n: t = "forgetting %d shadowed autoindexed files in %r > %r" self.log(t % (n, top, sh_rd)) q = "delete from dh where (d = ? or d like ?||'/%')" db.c.execute(q, erd_erd) q = "delete from up where (rd=? or rd like ?||'/%')" db.c.execute(q, erd_erd) tfa += n q = "delete from ds where (rd=? or rd like ?||'/%')" db.c.execute(q, erd_erd) if n4g: return tfa, tnf, rsz # drop missing files q = "select fn from up where rd = ?" try: c = db.c.execute(q, (rd,)) except: c = db.c.execute(q, ("//" + w8b64enc(rd),)) hits = [w8b64dec(x[2:]) if x.startswith("//") else x for (x,) in c] rm_files = [x for x in hits if x not in seen_files] n_rm = len(rm_files) for fn in rm_files: self.db_rm(db.c, e_d, rd, fn, 0) if n_rm: self.log("forgot {} deleted files".format(n_rm)) return tfa, tnf, rsz def _drop_lost(self, cur: "sqlite3.Cursor", top: str, excl: list[str]) -> int: rm = [] n_rm = 0 nchecked = 0 assert self.pp # `_build_dir` did all unshadowed files; first do dirs: ndirs = next(cur.execute("select count(distinct rd) from up"))[0] c = cur.execute("select distinct rd from up order by rd desc") for (drd,) in c: nchecked += 1 if drd.startswith("//"): rd = w8b64dec(drd[2:]) else: rd = drd abspath = djoin(top, rd) self.pp.msg = "b%d %s" % (ndirs - nchecked, abspath) try: if os.path.isdir(abspath): continue except: pass rm.append(drd) if rm: q = "select count(w) from up where rd = ?" for rd in rm: n_rm += next(cur.execute(q, (rd,)))[0] self.log("forgetting {} deleted dirs, {} files".format(len(rm), n_rm)) for rd in rm: cur.execute("delete from dh where d = ?", (rd,)) cur.execute("delete from up where rd = ?", (rd,)) # then shadowed deleted files n_rm2 = 0 c2 = cur.connection.cursor() excl = [x[len(top) + 1 :] for x in excl if x.startswith(top + "/")] q = "select rd, fn from up where (rd = ? or rd like ?||'%') order by rd" for rd in excl: for erd in [rd, "//" + w8b64enc(rd)]: try: c = cur.execute(q, (erd, erd + "/")) break except: pass crd = "///" cdc: set[str] = set() for drd, dfn in c: rd, fn = s3dec(drd, dfn) if crd != rd: crd = rd try: cdc = set(os.listdir(djoin(top, rd))) except: cdc.clear() if fn not in cdc: q = "delete from up where rd = ? and fn = ?" c2.execute(q, (drd, dfn)) n_rm2 += 1 if n_rm2: self.log("forgetting {} shadowed deleted files".format(n_rm2)) c2.connection.commit() # then covers n_rm3 = 0 qu = "select 1 from up where rd=? and fn=? limit 1" q = "delete from cv where rd=? and dn=? and +fn=?" for crd, cdn, fn in cur.execute("select * from cv"): urd = vjoin(crd, cdn) if not c2.execute(qu, (urd, fn)).fetchone(): c2.execute(q, (crd, cdn, fn)) n_rm3 += 1 if n_rm3: self.log("forgetting {} deleted covers".format(n_rm3)) c2.connection.commit() c2.close() return n_rm + n_rm2 def _verify_integrity(self, vol: VFS) -> int: ptop = vol.realpath assert self.pp cur = self.cur[ptop] rei = vol.flags.get("noidx") reh = vol.flags.get("nohash") e2vu = "e2vu" in vol.flags e2vp = "e2vp" in vol.flags excl = [ d[len(vol.vpath) :].lstrip("/") for d in self.vfs.all_vols if d != vol.vpath and (d.startswith(vol.vpath + "/") or not vol.vpath) ] qexa: list[str] = [] pexa: list[str] = [] for vpath in excl: qexa.append("up.rd != ? and not up.rd like ?||'%'") pexa.extend([vpath, vpath]) pex: tuple[Any, ...] = tuple(pexa) qex = " and ".join(qexa) if qex: qex = " where " + qex rewark: list[tuple[str, str, str, int, int]] = [] f404: list[tuple[str, str, str]] = [] with self.mutex: b_left = 0 n_left = 0 q = "select sz from up" + qex for (sz,) in cur.execute(q, pex): b_left += sz # sum() can overflow according to docs n_left += 1 tf, _ = self._spool_warks(cur, "select w, rd, fn from up" + qex, pex, 0) with gzip.GzipFile(mode="rb", fileobj=tf) as gf: for zb in gf: if self.stop: return -1 zs = zb[:-1].decode("utf-8").replace("\x00\x02", "\n") w, drd, dfn = zs.split("\x00\x01") with self.mutex: q = "select mt, sz from up where rd=? and fn=? and +w=?" try: mt, sz = cur.execute(q, (drd, dfn, w)).fetchone() except: # file moved/deleted since spooling continue n_left -= 1 b_left -= sz if drd.startswith("//") or dfn.startswith("//"): rd, fn = s3dec(drd, dfn) else: rd = drd fn = dfn abspath = djoin(ptop, rd, fn) if rei and rei.search(abspath): continue nohash = reh.search(abspath) if reh else False pf = "v{}, {:.0f}+".format(n_left, b_left / 1024 / 1024) self.pp.msg = pf + abspath try: stl = bos.lstat(abspath) st = bos.stat(abspath) if stat.S_ISLNK(stl.st_mode) else stl except Exception as ex: self.log("missing file: %r" % (abspath,), 3) f404.append((drd, dfn, w)) continue mt2 = int(stl.st_mtime) sz2 = st.st_size if nohash or not sz2: w2 = up2k_wark_from_metadata(self.salt, sz2, mt2, rd, fn) else: if sz2 > 1024 * 1024 * 32: self.log("file: %r" % (abspath,)) try: hashes, _ = self._hashlist_from_file(abspath, pf) except Exception as ex: self._ex_hash(ex, abspath) continue if not hashes: return -1 w2 = up2k_wark_from_hashlist(self.salt, sz2, hashes) if w == w2: continue # symlink mtime was inconsistent before v1.9.4; check if that's it if st != stl and (nohash or not sz2): mt2b = int(st.st_mtime) w2b = up2k_wark_from_metadata(self.salt, sz2, mt2b, rd, fn) if w == w2b: continue rewark.append((drd, dfn, w2, sz2, mt2)) t = "hash mismatch: %r\n db: %s (%d byte, %d)\n fs: %s (%d byte, %d)" self.log(t % (abspath, w, sz, mt, w2, sz2, mt2), 1) if e2vp and (rewark or f404): self.hub.retcode = 1 Daemon(self.hub.sigterm) t = "in volume /%s: %s files missing, %s files have incorrect hashes" t = t % (vol.vpath, len(f404), len(rewark)) self.log(t, 1) raise Exception(t) if not e2vu or (not rewark and not f404): return 0 with self.mutex: q = "update up set w=?, sz=?, mt=? where rd=? and fn=?" for rd, fn, w, sz, mt in rewark: cur.execute(q, (w, sz, int(mt), rd, fn)) if f404: q = "delete from up where rd=? and fn=? and +w=?" cur.executemany(q, f404) cur.connection.commit() return len(rewark) + len(f404) def _build_tags_index(self, vol: VFS) -> tuple[int, int, bool]: ptop = vol.realpath with self.mutex, self.reg_mutex: reg = self.register_vpath(ptop, vol.flags) assert reg and self.pp cur = self.cur[ptop] if not self.args.no_dhash: with self.mutex: c = cur.execute("select k from kv where k = 'tagscan'") if not c.fetchone(): return 0, 0, bool(self.mtag) ret = self._build_tags_index_2(ptop) with self.mutex: self._set_tagscan(cur, False) cur.connection.commit() return ret def _drop_caches(self) -> None: self.log("dropping caches for a full filesystem scan") for vol in self.vfs.all_vols.values(): reg = self.register_vpath(vol.realpath, vol.flags) if not reg: continue cur, _ = reg self._set_tagscan(cur, True) cur.execute("delete from dh") cur.execute("delete from cv") cur.connection.commit() def _set_tagscan(self, cur: "sqlite3.Cursor", need: bool) -> bool: if self.args.no_dhash: return False c = cur.execute("select k from kv where k = 'tagscan'") if bool(c.fetchone()) == need: return False if need: cur.execute("insert into kv values ('tagscan',1)") else: cur.execute("delete from kv where k = 'tagscan'") return True def _build_tags_index_2(self, ptop: str) -> tuple[int, int, bool]: entags = self.entags[ptop] flags = self.flags[ptop] cur = self.cur[ptop] n_add = 0 n_rm = 0 if "e2tsr" in flags: with self.mutex: n_rm = cur.execute("select count(w) from mt").fetchone()[0] if n_rm: self.log("discarding {} media tags for a full rescan".format(n_rm)) cur.execute("delete from mt") # integrity: drop tags for tracks that were deleted if "e2t" in flags: with self.mutex: n = 0 c2 = cur.connection.cursor() up_q = "select w from up where substr(w,1,16) = ?" rm_q = "delete from mt where w = ?" for (w,) in cur.execute("select w from mt"): if not c2.execute(up_q, (w,)).fetchone(): c2.execute(rm_q, (w[:16],)) n += 1 c2.close() if n: t = "discarded media tags for {} deleted files" self.log(t.format(n)) n_rm += n with self.mutex: cur.connection.commit() # bail if a volflag disables indexing if "d2t" in flags or "d2d" in flags: return 0, n_rm, True # add tags for new files if "e2ts" in flags: if not self.mtag: return 0, n_rm, False nq = 0 with self.mutex: tf, nq = self._spool_warks( cur, "select w from up order by rd, fn", (), 1 ) if not nq: # self.log("tags ok") self._unspool(tf) return 0, n_rm, True if nq == -1: return -1, -1, True with gzip.GzipFile(mode="rb", fileobj=tf) as gf: n_add = self._e2ts_q(gf, nq, cur, ptop, entags) self._unspool(tf) return n_add, n_rm, True def _e2ts_q( self, qf: gzip.GzipFile, nq: int, cur: "sqlite3.Cursor", ptop: str, entags: set[str], ) -> int: assert self.pp and self.mtag flags = self.flags[ptop] mpool: Optional[Queue[Mpqe]] = None if self.mtag.prefer_mt and self.args.mtag_mt > 1: mpool = self._start_mpool() n_add = 0 n_buf = 0 last_write = time.time() for bw in qf: if self.stop: return -1 w = bw[:-1].decode("ascii") w16 = w[:16] with self.mutex: try: q = "select rd, fn, ip, at, un from up where substr(w,1,16)=? and +w=?" rd, fn, ip, at, un = cur.execute(q, (w16, w)).fetchone() except: # file modified/deleted since spooling continue if rd.startswith("//") or fn.startswith("//"): rd, fn = s3dec(rd, fn) if "mtp" in flags: q = "select 1 from mt where w=? and +k='t:mtp' limit 1" if cur.execute(q, (w16,)).fetchone(): continue q = "insert into mt values (?,'t:mtp','a')" cur.execute(q, (w16,)) abspath = djoin(ptop, rd, fn) self.pp.msg = "c%d %s" % (nq, abspath) if not mpool: n_tags = self._tagscan_file(cur, entags, flags, w, abspath, ip, at, un) else: oth_tags = {} if ip: oth_tags["up_ip"] = ip if at: oth_tags["up_at"] = at if un: oth_tags["up_by"] = un mpool.put(Mpqe({}, entags, flags, w, abspath, oth_tags)) with self.mutex: n_tags = len(self._flush_mpool(cur)) n_add += n_tags n_buf += n_tags nq -= 1 td = time.time() - last_write if n_buf >= 4096 or td >= self.timeout / 2: self.log("commit {} new tags".format(n_buf)) with self.mutex: cur.connection.commit() last_write = time.time() n_buf = 0 if mpool: self._stop_mpool(mpool) with self.mutex: n_add += len(self._flush_mpool(cur)) with self.mutex: cur.connection.commit() return n_add def _spool_warks( self, cur: "sqlite3.Cursor", q: str, params: tuple[Any, ...], flt: int, ) -> tuple[tempfile.SpooledTemporaryFile[bytes], int]: n = 0 c2 = cur.connection.cursor() tf = tempfile.SpooledTemporaryFile(1024 * 1024 * 8, "w+b", prefix="cpp-tq-") with gzip.GzipFile(mode="wb", fileobj=tf) as gf: for row in cur.execute(q, params): if self.stop: return tf, -1 if flt == 1: q = "select 1 from mt where w=? and +k != 't:mtp'" if c2.execute(q, (row[0][:16],)).fetchone(): continue zs = "\x00\x01".join(row).replace("\n", "\x00\x02") gf.write((zs + "\n").encode("utf-8")) n += 1 c2.close() tf.seek(0) self.spools.add(tf) return tf, n def _unspool(self, tf: tempfile.SpooledTemporaryFile[bytes]) -> None: try: self.spools.remove(tf) except: return try: tf.close() except Exception as ex: self.log("failed to delete spool: {}".format(ex), 3) def _flush_mpool(self, wcur: "sqlite3.Cursor") -> list[str]: ret = [] for x in self.pending_tags: self._tag_file(wcur, *x) ret.append(x[1]) self.pending_tags = [] return ret def _run_all_mtp(self, gid: int) -> None: t0 = time.time() for ptop, flags in self.flags.items(): if "mtp" in flags: if ptop not in self.entags: t = "skipping mtp for unavailable volume {}" self.log(t.format(ptop), 1) else: self._run_one_mtp(ptop, gid) vtop = "\n" for vol in self.vfs.all_vols.values(): if vol.realpath == ptop: vtop = vol.vpath if "running mtp" in self.volstate.get(vtop, ""): self.volstate[vtop] = "online, idle" td = time.time() - t0 msg = "mtp finished in {:.2f} sec ({})" self.log(msg.format(td, s2hms(td, True))) self.unpp() if self.args.exit == "idx": self.hub.sigterm() def _run_one_mtp(self, ptop: str, gid: int) -> None: if gid != self.gid: return entags = self.entags[ptop] vf = self.flags[ptop] parsers = {} for parser in vf["mtp"]: try: parser = MParser(parser) except: self.log("invalid argument (could not find program): " + parser, 1) return for tag in entags: if tag in parser.tags: parsers[parser.tag] = parser if self.args.mtag_vv: t = "parsers for {}: \033[0m{}" self.log(t.format(ptop, list(parsers.keys())), "90") self.mtp_parsers[ptop] = parsers q = "select count(w) from mt where k = 't:mtp'" with self.mutex: cur = self.cur[ptop] cur = cur.connection.cursor() wcur = cur.connection.cursor() n_left = cur.execute(q).fetchone()[0] mpool = self._start_mpool() batch_sz = mpool.maxsize * 3 t_prev = time.time() n_prev = n_left n_done = 0 to_delete = {} in_progress = {} while True: did_nothing = True with self.mutex: if gid != self.gid: break q = "select w from mt where k = 't:mtp' limit ?" zq = cur.execute(q, (batch_sz,)).fetchall() warks = [str(x[0]) for x in zq] jobs = [] for w in warks: if w in in_progress: continue q = "select rd, fn, ip, at, un from up where substr(w,1,16)=? limit 1" rd, fn, ip, at, un = cur.execute(q, (w,)).fetchone() rd, fn = s3dec(rd, fn) abspath = djoin(ptop, rd, fn) q = "select k from mt where w = ?" zq = cur.execute(q, (w,)).fetchall() have: dict[str, Union[str, float]] = {x[0]: 1 for x in zq} did_nothing = False parsers = self._get_parsers(ptop, have, abspath) if not parsers: to_delete[w] = True n_left -= 1 continue if next((x for x in parsers.values() if x.pri), None): q = "select k, v from mt where w = ?" zq2 = cur.execute(q, (w,)).fetchall() oth_tags = {str(k): v for k, v in zq2} else: oth_tags = {} if ip: oth_tags["up_ip"] = ip if at: oth_tags["up_at"] = at if un: oth_tags["up_by"] = un jobs.append(Mpqe(parsers, set(), vf, w, abspath, oth_tags)) in_progress[w] = True with self.mutex: done = self._flush_mpool(wcur) for w in done: to_delete[w] = True did_nothing = False in_progress.pop(w) n_done += 1 for w in to_delete: q = "delete from mt where w = ? and +k = 't:mtp'" cur.execute(q, (w,)) to_delete = {} if not warks: break if did_nothing: with self.tag_event: self.tag_event.wait(0.2) if not jobs: continue try: now = time.time() s = ((now - t_prev) / (n_prev - n_left)) * n_left h, s = divmod(s, 3600) m, s = divmod(s, 60) n_prev = n_left t_prev = now except: h = 1 m = 1 msg = "mtp: {} done, {} left, eta {}h {:02d}m" with self.mutex: msg = msg.format(n_done, n_left, int(h), int(m)) self.log(msg, c=6) for j in jobs: n_left -= 1 mpool.put(j) with self.mutex: cur.connection.commit() self._stop_mpool(mpool) with self.mutex: done = self._flush_mpool(wcur) for w in done: q = "delete from mt where w = ? and +k = 't:mtp'" cur.execute(q, (w,)) cur.connection.commit() if n_done: self.log("mtp: scanned {} files in {}".format(n_done, ptop), c=6) cur.execute("vacuum") wcur.close() cur.close() def _get_parsers( self, ptop: str, have: dict[str, Union[str, float]], abspath: str ) -> dict[str, MParser]: try: all_parsers = self.mtp_parsers[ptop] except: if self.args.mtag_vv: self.log("no mtp defined for {}".format(ptop), "90") return {} entags = self.entags[ptop] parsers = {} for k, v in all_parsers.items(): if "ac" in entags or ".aq" in entags: if "ac" in have or ".aq" in have: # is audio, require non-audio? if v.audio == "n": if self.args.mtag_vv: t = "skip mtp {}; want no-audio, got audio" self.log(t.format(k), "90") continue # is not audio, require audio? elif v.audio == "y": if self.args.mtag_vv: t = "skip mtp {}; want audio, got no-audio" self.log(t.format(k), "90") continue if v.ext: match = False for ext in v.ext: if abspath.lower().endswith("." + ext): match = True break if not match: if self.args.mtag_vv: t = "skip mtp {}; want file-ext {}, got {}" self.log(t.format(k, v.ext, abspath.rsplit(".")[-1]), "90") continue parsers[k] = v parsers = {k: v for k, v in parsers.items() if v.force or k not in have} return parsers def _start_mpool(self) -> Queue[Mpqe]: # mp.pool.ThreadPool and concurrent.futures.ThreadPoolExecutor # both do crazy runahead so lets reinvent another wheel nw = max(1, self.args.mtag_mt) assert self.mtag # !rm if not self.mpool_used: self.mpool_used = True self.log("using {}x {}".format(nw, self.mtag.backend)) mpool: Queue[Mpqe] = Queue(nw) for _ in range(nw): Daemon(self._tag_thr, "up2k-mpool", (mpool,)) return mpool def _stop_mpool(self, mpool: Queue[Mpqe]) -> None: if not mpool: return for _ in range(mpool.maxsize): mpool.put(Mpqe({}, set(), {}, "", "", {})) mpool.join() def _tag_thr(self, q: Queue[Mpqe]) -> None: assert self.mtag while True: qe = q.get() if not qe.w: q.task_done() return try: st = bos.stat(qe.abspath) if not qe.mtp: if self.args.mtag_vv: t = "tag-thr: {}({})" self.log(t.format(self.mtag.backend, qe.abspath), "90") tags = self.mtag.get(qe.abspath, qe.vf) if st.st_size else {} else: if self.args.mtag_vv: t = "tag-thr: {}({})" self.log(t.format(list(qe.mtp.keys()), qe.abspath), "90") tags = self.mtag.get_bin(qe.mtp, qe.abspath, qe.oth_tags) vtags = [ "\033[36m{} \033[33m{}".format(k, v) for k, v in tags.items() ] if vtags: self.log("{}\033[0m [{}]".format(" ".join(vtags), qe.abspath)) with self.mutex: self.pending_tags.append((qe.entags, qe.w, qe.abspath, tags)) except: ex = traceback.format_exc() self._log_tag_err(qe.mtp or self.mtag.backend, qe.abspath, ex) finally: if qe.mtp: with self.tag_event: self.tag_event.notify_all() q.task_done() def _log_tag_err(self, parser: Any, abspath: str, ex: Any) -> None: msg = "%s failed to read tags from %r:\n%s" % (parser, abspath, ex) self.log(msg.lstrip(), c=1 if "<Signals.SIG" in msg else 3) def _tagscan_file( self, write_cur: "sqlite3.Cursor", entags: set[str], vf: dict[str, Any], wark: str, abspath: str, ip: str, at: float, un: Optional[str], ) -> int: assert self.mtag # !rm try: st = bos.stat(abspath) except: return 0 if not stat.S_ISREG(st.st_mode): return 0 try: tags = self.mtag.get(abspath, vf) if st.st_size else {} except Exception as ex: self._log_tag_err("", abspath, ex) return 0 if ip: tags["up_ip"] = ip if at: tags["up_at"] = at if un: tags["up_by"] = un with self.mutex: return self._tag_file(write_cur, entags, wark, abspath, tags) def _tag_file( self, write_cur: "sqlite3.Cursor", entags: set[str], wark: str, abspath: str, tags: dict[str, Union[str, float]], ) -> int: assert self.mtag # !rm if not bos.path.isfile(abspath): return 0 if entags: tags = {k: v for k, v in tags.items() if k in entags} if not tags: # indicate scanned without tags tags = {"x": 0} if not tags: return 0 for k in tags.keys(): q = "delete from mt where w = ? and ({})".format( " or ".join(["+k = ?"] * len(tags)) ) args = [wark[:16]] + list(tags.keys()) write_cur.execute(q, tuple(args)) ret = 0 for k, v in tags.items(): q = "insert into mt values (?,?,?)" write_cur.execute(q, (wark[:16], k, v)) ret += 1 self._set_tagscan(write_cur, True) return ret def _trace(self, msg: str) -> None: self.log("ST: {}".format(msg)) def _open_db_wd(self, db_path: str) -> "sqlite3.Cursor": ok: list[int] = [] if not self.hub.is_dut: Daemon(self._open_db_timeout, "opendb_watchdog", [db_path, ok]) try: return self._open_db(db_path) finally: ok.append(1) def _open_db_timeout(self, db_path, ok: list[int]) -> None: # give it plenty of time due to the count statement (and wisdom from byte's box) for _ in range(60): time.sleep(1) if ok: return t = "WARNING:\n\n initializing an up2k database is taking longer than one minute; something has probably gone wrong:\n\n" self._log_sqlite_incompat(db_path, t) def _log_sqlite_incompat(self, db_path, t0) -> None: txt = t0 or "" digest = hashlib.sha512(db_path.encode("utf-8", "replace")).digest() stackname = ub64enc(digest[:9]).decode("ascii") stackpath = os.path.join(E.cfg, "stack-%s.txt" % (stackname,)) t = " the filesystem at %s may not support locking, or is otherwise incompatible with sqlite\n\n %s\n\n" t += " PS: if you think this is a bug and wish to report it, please include your configuration + the following file: %s\n" txt += t % (db_path, HINT_HISTPATH, stackpath) self.log(txt, 3) try: stk = alltrace() with open(stackpath, "wb") as f: f.write(stk.encode("utf-8", "replace")) except Exception as ex: self.log("warning: failed to write %s: %s" % (stackpath, ex), 3) if self.args.q: t = "-" * 72 raise Exception("%s\n%s\n%s" % (t, txt, t)) def _orz(self, db_path: str) -> "sqlite3.Cursor": assert sqlite3 # type: ignore # !rm c = sqlite3.connect( db_path, timeout=self.timeout, check_same_thread=False ).cursor() # c.connection.set_trace_callback(self._trace) return c def _open_db(self, db_path: str) -> "sqlite3.Cursor": existed = bos.path.exists(db_path) cur = self._orz(db_path) ver = self._read_ver(cur) if not existed and ver is None: return self._try_create_db(db_path, cur) for upver in (4, 5): if ver != upver: continue try: t = "creating backup before upgrade: " cur = self._backup_db(db_path, cur, ver, t) getattr(self, "_upgrade_v%d" % (upver,))(cur) ver += 1 # type: ignore except: self.log("WARN: failed to upgrade from v%d" % (ver,), 3) if ver == DB_VER: # these no longer serve their intended purpose but they're great as additional sanchks self._add_dhash_tab(cur) self._add_xiu_tab(cur) self._add_cv_tab(cur) self._add_idx_up_vp(cur, db_path) self._add_ds_tab(cur) try: nfiles = next(cur.execute("select count(w) from up"))[0] self.log(" {} |{}|".format(db_path, nfiles), "90") return cur except: self.log("WARN: could not list files; DB corrupt?\n" + min_ex()) if (ver or 0) > DB_VER: t = "database is version {}, this copyparty only supports versions <= {}" raise Exception(t.format(ver, DB_VER)) msg = "creating new DB (old is bad); backup: " if ver: msg = "creating new DB (too old to upgrade); backup: " cur = self._backup_db(db_path, cur, ver, msg) db = cur.connection cur.close() db.close() self._delete_db(db_path) return self._try_create_db(db_path, None) def _delete_db(self, db_path: str): for suf in ("", "-shm", "-wal", "-journal"): try: bos.unlink(db_path + suf) except: if not suf: raise def _backup_db( self, db_path: str, cur: "sqlite3.Cursor", ver: Optional[int], msg: str ) -> "sqlite3.Cursor": assert sqlite3 # type: ignore # !rm bak = "{}.bak.{:x}.v{}".format(db_path, int(time.time()), ver) self.log(msg + bak) try: c2 = sqlite3.connect(bak) with c2: cur.connection.backup(c2) return cur except: t = "native sqlite3 backup failed; using fallback method:\n" self.log(t + min_ex()) finally: c2.close() # type: ignore db = cur.connection cur.close() db.close() trystat_shutil_copy2(self.log, fsenc(db_path), fsenc(bak)) return self._orz(db_path) def _read_ver(self, cur: "sqlite3.Cursor") -> Optional[int]: for tab in ["ki", "kv"]: try: c = cur.execute(r"select v from {} where k = 'sver'".format(tab)) except: continue rows = c.fetchall() if rows: return int(rows[0][0]) return None def _try_create_db( self, db_path: str, cur: Optional["sqlite3.Cursor"] ) -> "sqlite3.Cursor": try: return self._create_db(db_path, cur) except: try: self._delete_db(db_path) except: pass raise def _create_db( self, db_path: str, cur: Optional["sqlite3.Cursor"] ) -> "sqlite3.Cursor": if not cur: cur = self._orz(db_path) idx = r"create index up_w on up(substr(w,1,16))" if self.no_expr_idx: idx = r"create index up_w on up(w)" for cmd in [ r"create table up (w text, mt int, sz int, rd text, fn text, ip text, at int, un text)", r"create index up_vp on up(rd, fn)", r"create index up_fn on up(fn)", r"create index up_ip on up(ip)", r"create index up_at on up(at)", idx, r"create table mt (w text, k text, v int)", r"create index mt_w on mt(w)", r"create index mt_k on mt(k)", r"create index mt_v on mt(v)", r"create table kv (k text, v int)", r"insert into kv values ('sver', {})".format(DB_VER), ]: cur.execute(cmd) self._add_dhash_tab(cur) self._add_xiu_tab(cur) self._add_cv_tab(cur) self._add_ds_tab(cur) self.log("created DB at {}".format(db_path)) return cur def _upgrade_v4(self, cur: "sqlite3.Cursor") -> None: for cmd in [ r"alter table up add column ip text", r"alter table up add column at int", r"create index up_ip on up(ip)", r"update kv set v=5 where k='sver'", ]: cur.execute(cmd) cur.connection.commit() def _upgrade_v5(self, cur: "sqlite3.Cursor") -> None: for cmd in [ r"alter table up add column un text", r"update kv set v=6 where k='sver'", ]: cur.execute(cmd) cur.connection.commit() def _add_dhash_tab(self, cur: "sqlite3.Cursor") -> None: # v5 -> v5a try: cur.execute("select d, h from dh limit 1").fetchone() return except: pass for cmd in [ r"create table dh (d text, h text)", r"create index dh_d on dh(d)", r"insert into kv values ('tagscan',1)", ]: cur.execute(cmd) cur.connection.commit() def _add_xiu_tab(self, cur: "sqlite3.Cursor") -> None: # v5a -> v5b # store rd+fn rather than warks to support nohash vols try: cur.execute("select c, w, rd, fn from iu limit 1").fetchone() return except: pass try: cur.execute("drop table iu") except: pass for cmd in [ r"create table iu (c int, w text, rd text, fn text)", r"create index iu_c on iu(c)", r"create index iu_w on iu(w)", ]: cur.execute(cmd) cur.connection.commit() def _add_cv_tab(self, cur: "sqlite3.Cursor") -> None: # v5b -> v5c try: cur.execute("select rd, dn, fn from cv limit 1").fetchone() return except: pass for cmd in [ r"create table cv (rd text, dn text, fn text)", r"create index cv_i on cv(rd, dn)", ]: cur.execute(cmd) try: cur.execute("delete from dh") except: pass cur.connection.commit() def _add_idx_up_vp(self, cur: "sqlite3.Cursor", db_path: str) -> None: # v5c -> v5d try: cur.execute("drop index up_rd") except: return for cmd in [ r"create index up_vp on up(rd, fn)", r"create index up_at on up(at)", ]: self.log("upgrading db [%s]: %s" % (db_path, cmd[:18])) cur.execute(cmd) self.log("upgrading db [%s]: writing to disk..." % (db_path,)) cur.connection.commit() cur.execute("vacuum") def _add_ds_tab(self, cur: "sqlite3.Cursor") -> None: # v5d -> v5e try: cur.execute("select rd, sz from ds limit 1").fetchone() return except: pass for cmd in [ r"create table ds (rd text, sz int, nf int)", r"create index ds_rd on ds(rd)", ]: cur.execute(cmd) cur.connection.commit() def wake_rescanner(self): with self.rescan_cond: self.rescan_cond.notify_all() def handle_json( self, cj: dict[str, Any], busy_aps: dict[str, int] ) -> dict[str, Any]: # busy_aps is u2fh (always undefined if -j0) so this is safe self.busy_aps = busy_aps if self.reload_flag or self.reloading: raise Pebkac(503, SBUSY % ("fs-reload",)) got_lock = False self.fika = "u" try: # bit expensive; 3.9=10x 3.11=2x if self.mutex.acquire(timeout=10): got_lock = True with self.reg_mutex: ret = self._handle_json(cj) else: raise Pebkac(503, SBUSY % (self.blocked or "[unknown]",)) except TypeError: if not PY2: raise with self.mutex, self.reg_mutex: ret = self._handle_json(cj) finally: if got_lock: self.mutex.release() if self.fx_backlog: self.do_fx_backlog() return ret def _handle_json(self, cj: dict[str, Any], depth: int = 1) -> dict[str, Any]: if depth > 16: raise Pebkac(500, "too many xbu relocs, giving up") ptop = cj["ptop"] if not self.register_vpath(ptop, cj["vcfg"]): if ptop not in self.registry: raise Pebkac(410, "location unavailable") cj["poke"] = now = self.db_act = self.vol_act[ptop] = time.time() wark = dwark = self._get_wark(cj) job = None pdir = djoin(ptop, cj["prel"]) inc_ap = djoin(pdir, cj["name"]) try: dev = bos.stat(pdir).st_dev except: dev = 0 # check if filesystem supports sparse files; # refuse out-of-order / multithreaded uploading if sprs False sprs = self.fstab.get(pdir)[0] != "ng" if True: jcur = self.cur.get(ptop) reg = self.registry[ptop] vfs = self.vfs.all_vols[cj["vtop"]] n4g = bool(vfs.flags.get("noforget")) noclone = bool(vfs.flags.get("noclone")) rand = vfs.flags.get("rand") or cj.get("rand") lost: list[tuple["sqlite3.Cursor", str, str]] = [] safe_dedup = vfs.flags.get("safededup") or 50 data_ok = safe_dedup < 10 or n4g vols = [(ptop, jcur)] if jcur else [] if vfs.flags.get("xlink"): vols += [(k, v) for k, v in self.cur.items() if k != ptop] if noclone: wark = up2k_wark_from_metadata( self.salt, cj["size"], cj["lmod"], cj["prel"], cj["name"] ) zi = cj["lmod"] bad_mt = zi <= 0 or zi > 0xAAAAAAAA if bad_mt or vfs.flags.get("up_ts", "") == "fu": # force upload time rather than last-modified cj["lmod"] = int(time.time()) if zi and bad_mt: t = "ignoring impossible last-modified time from client: %s" self.log(t % (zi,), 6) alts: list[tuple[int, int, dict[str, Any], "sqlite3.Cursor", str, str]] = [] for ptop, cur in vols: allv = self.vfs.all_vols cvfs = next((v for v in allv.values() if v.realpath == ptop), vfs) vtop = cj["vtop"] if cur == jcur else cvfs.vpath if self.no_expr_idx: q = r"select * from up where w = ?" argv = [dwark] else: q = r"select * from up where substr(w,1,16)=? and +w=?" argv = [dwark[:16], dwark] c2 = cur.execute(q, tuple(argv)) for _, dtime, dsize, dp_dir, dp_fn, ip, at, _ in c2: if dp_dir.startswith("//") or dp_fn.startswith("//"): dp_dir, dp_fn = s3dec(dp_dir, dp_fn) dp_abs = djoin(ptop, dp_dir, dp_fn) if noclone and dp_abs != inc_ap: continue try: st = bos.stat(dp_abs) if stat.S_ISLNK(st.st_mode): # broken symlink raise Exception() if st.st_size != dsize: t = "candidate ignored (db/fs desync): {}, size fs={} db={}, mtime fs={} db={}, file: {}" t = t.format( dwark, st.st_size, dsize, st.st_mtime, dtime, dp_abs ) self.log(t) raise Exception() except Exception as ex: if n4g: st = NULLSTAT else: lost.append((cur, dp_dir, dp_fn)) continue j = { "name": dp_fn, "prel": dp_dir, "vtop": vtop, "ptop": ptop, "sprs": sprs, # dontcare; finished anyways "size": dsize, "lmod": dtime, "host": cj["host"], "user": cj["user"], "addr": ip, "at": at, } for k in ["life"]: if k in cj: j[k] = cj[k] # offset of 1st diff in vpaths zig = ( n + 1 for n, (c1, c2) in enumerate( zip(dp_dir + "\r", cj["prel"] + "\n") ) if c1 != c2 ) score = ( (6969 if st.st_dev == dev else 0) + (3210 if dp_dir == cj["prel"] else next(zig)) + (1 if dp_fn == cj["name"] else 0) ) alts.append((score, -len(alts), j, cur, dp_dir, dp_fn)) job = None for dupe in sorted(alts, reverse=True): rj = dupe[2] orig_ap = djoin(rj["ptop"], rj["prel"], rj["name"]) if data_ok or inc_ap == orig_ap: data_ok = True job = rj break else: self.log("asserting contents of %r" % (orig_ap,)) hashes2, st = self._hashlist_from_file(orig_ap) wark2 = up2k_wark_from_hashlist(self.salt, st.st_size, hashes2) if dwark != wark2: t = "will not dedup (fs index desync): fs=%s, db=%s, file: %r\n%s" self.log(t % (wark2, dwark, orig_ap, rj)) lost.append(dupe[3:]) continue data_ok = True job = rj break if job: if wark in reg: del reg[wark] job["hash"] = job["need"] = [] job["done"] = 1 job["busy"] = {} if lost: c2 = None for cur, dp_dir, dp_fn in lost: t = "forgetting desynced db entry: %r" self.log(t % ("/" + vjoin(vjoin(vfs.vpath, dp_dir), dp_fn))) self.db_rm(cur, vfs.flags, dp_dir, dp_fn, cj["size"]) if c2 and c2 != cur: c2.connection.commit() c2 = cur assert c2 # !rm c2.connection.commit() cur = jcur ptop = None # use cj or job as appropriate if not job and wark in reg: # ensure the files haven't been edited or deleted path = "" st = None rj = reg[wark] names = [rj[x] for x in ["name", "tnam"] if x in rj] for fn in names: path = djoin(rj["ptop"], rj["prel"], fn) try: st = bos.stat(path) if st.st_size > 0 or "done" in rj: # upload completed or both present break except: # missing; restart if not self.args.nw and not n4g: t = "forgetting deleted partial upload at %r" self.log(t % (path,)) del reg[wark] break inc_ap = djoin(cj["ptop"], cj["prel"], cj["name"]) orig_ap = djoin(rj["ptop"], rj["prel"], rj["name"]) if self.args.nw or n4g or not st or "done" not in rj: pass elif st.st_size != rj["size"]: t = "will not dedup (fs index desync): %s, size fs=%d db=%d, mtime fs=%d db=%d, file: %r\n%s" t = t % ( wark, st.st_size, rj["size"], st.st_mtime, rj["lmod"], path, rj, ) self.log(t) del reg[wark] elif inc_ap != orig_ap and not data_ok and "done" in reg[wark]: self.log("asserting contents of %r" % (orig_ap,)) hashes2, _ = self._hashlist_from_file(orig_ap) wark2 = up2k_wark_from_hashlist(self.salt, st.st_size, hashes2) if wark != wark2: t = "will not dedup (fs index desync): fs=%s, idx=%s, file: %r\n%s" self.log(t % (wark2, wark, orig_ap, rj)) del reg[wark] if job or wark in reg: job = job or reg[wark] if ( job["ptop"] != cj["ptop"] or job["prel"] != cj["prel"] or job["name"] != cj["name"] ): # file contents match, but not the path src = djoin(job["ptop"], job["prel"], job["name"]) dst = djoin(cj["ptop"], cj["prel"], cj["name"]) vsrc = djoin(job["vtop"], job["prel"], job["name"]) vsrc = vsrc.replace("\\", "/") # just for prints anyways if vfs.lim: dst, cj["prel"] = vfs.lim.all( cj["addr"], cj["prel"], cj["size"], cj["ptop"], djoin(cj["ptop"], cj["prel"]), self.hub.broker, reg, "up2k._get_volsize", ) bos.makedirs(dst, vf=vfs.flags) vfs.lim.nup(cj["addr"]) vfs.lim.bup(cj["addr"], cj["size"]) if "done" not in job: self.log("unfinished:\n %r\n %r" % (src, dst)) err = "partial upload exists at a different location; please resume uploading here instead:\n" err += "/" + quotep(vsrc) + " " # registry is size-constrained + can only contain one unique wark; # let want_recheck trigger symlink (if still in reg) or reupload if cur: dupe = (cj["prel"], cj["name"], cj["lmod"]) try: if dupe not in self.dupesched[src]: self.dupesched[src].append(dupe) except: self.dupesched[src] = [dupe] raise Pebkac(422, err) elif "nodupe" in vfs.flags: self.log("dupe-reject:\n %r\n %r" % (src, dst)) err = "upload rejected, file already exists:\n" err += "/" + quotep(vsrc) + " " raise Pebkac(409, err) else: # symlink to the client-provided name, # returning the previous upload info psrc = src + ".PARTIAL" if self.args.dotpart: m = re.match(r"(.*[\\/])(.*)", psrc) if m: # always true but... zs1, zs2 = m.groups() psrc = zs1 + "." + zs2 if ( src in self.busy_aps or psrc in self.busy_aps or (wark in reg and "done" not in reg[wark]) ): raise Pebkac( 422, "source file busy; please try again later" ) job = deepcopy(job) job["wark"] = wark job["dwrk"] = dwark job["at"] = cj.get("at") or now zs = "vtop ptop prel name lmod host user addr poke" for k in zs.split(): job[k] = cj.get(k) or "" for k in ("life", "replace"): if k in cj: job[k] = cj[k] pdir = djoin(cj["ptop"], cj["prel"]) if rand: job["name"] = rand_name( pdir, cj["name"], vfs.flags["nrand"] ) dst = djoin(job["ptop"], job["prel"], job["name"]) xbu = vfs.flags.get("xbu") if xbu: vp = djoin(job["vtop"], job["prel"], job["name"]) hr = runhook( self.log, None, self, "xbu.up2k.dupe", xbu, # type: ignore dst, vp, job["host"], job["user"], self.vfs.get_perms(job["vtop"], job["user"]), job["lmod"], job["size"], job["addr"], job["at"], None, ) t = hr.get("rejectmsg") or "" if t or hr.get("rc") != 0: if not t: t = "upload blocked by xbu server config: %r" t = t % (vp,) self.log(t, 1) raise Pebkac(403, t) if hr.get("reloc"): x = pathmod(self.vfs, dst, vp, hr["reloc"]) if x: ud1 = (vfs.vpath, job["prel"], job["name"]) pdir, _, job["name"], (vfs, rem) = x dst = os.path.join(pdir, job["name"]) job["vcfg"] = vfs.flags job["ptop"] = vfs.realpath job["vtop"] = vfs.vpath job["prel"] = rem job["name"] = sanitize_fn(job["name"]) ud2 = (vfs.vpath, job["prel"], job["name"]) if ud1 != ud2: # print(json.dumps(job, sort_keys=True, indent=4)) job["hash"] = cj["hash"] self.log("xbu reloc1:%d..." % (depth,), 6) return self._handle_json(job, depth + 1) job["name"] = self._untaken(pdir, job, now) dst = djoin(job["ptop"], job["prel"], job["name"]) if not self.args.nw: dvf: dict[str, Any] = vfs.flags try: dvf = self.flags[job["ptop"]] self._symlink(src, dst, dvf, lmod=cj["lmod"], rm=True) except: if bos.path.exists(dst): wunlink(self.log, dst, dvf) if not n4g: raise if cur and not self.args.nw: zs = "prel name lmod size ptop vtop wark dwrk host user addr at" a = [job[x] for x in zs.split()] self.db_add(cur, vfs.flags, *a) cur.connection.commit() elif wark in reg: # checks out, but client may have hopped IPs job["addr"] = cj["addr"] if not job: ap1 = djoin(cj["ptop"], cj["prel"]) if rand: cj["name"] = rand_name(ap1, cj["name"], vfs.flags["nrand"]) if vfs.lim: ap2, cj["prel"] = vfs.lim.all( cj["addr"], cj["prel"], cj["size"], cj["ptop"], ap1, self.hub.broker, reg, "up2k._get_volsize", ) bos.makedirs(ap2, vf=vfs.flags) vfs.lim.nup(cj["addr"]) vfs.lim.bup(cj["addr"], cj["size"]) job = { "wark": wark, "dwrk": dwark, "t0": now, "sprs": sprs, "hash": deepcopy(cj["hash"]), "need": [], "busy": {}, } # client-provided, sanitized by _get_wark: name, size, lmod zs = "vtop ptop prel name size lmod host user addr poke" for k in zs.split(): job[k] = cj[k] for k in ["life", "replace"]: if k in cj: job[k] = cj[k] # one chunk may occur multiple times in a file; # filter to unique values for the list of missing chunks # (preserve order to reduce disk thrashing) lut = set() for k in cj["hash"]: if k not in lut: job["need"].append(k) lut.add(k) try: ret = self._new_upload(job, vfs, depth) if ret: return ret # xbu recursed except: self.registry[job["ptop"]].pop(job["wark"], None) raise purl = "{}/{}".format(job["vtop"], job["prel"]).strip("/") purl = "/{}/".format(purl) if purl else "/" ret = { "name": job["name"], "purl": purl, "size": job["size"], "lmod": job["lmod"], "sprs": job.get("sprs", sprs), "hash": job["need"], "dwrk": dwark, "wark": wark, } if ( not ret["hash"] and "fk" in vfs.flags and not self.args.nw and (cj["user"] in vfs.axs.uread or cj["user"] in vfs.axs.upget) ): alg = 2 if "fka" in vfs.flags else 1 ap = absreal(djoin(job["ptop"], job["prel"], job["name"])) ino = 0 if ANYWIN else bos.stat(ap).st_ino fk = self.gen_fk(alg, self.args.fk_salt, ap, job["size"], ino) ret["fk"] = fk[: vfs.flags["fk"]] if ( not ret["hash"] and cur and cj.get("umod") and int(cj["lmod"]) != int(job["lmod"]) and not self.args.nw and cj["user"] in vfs.axs.uwrite and cj["user"] in vfs.axs.udel ): sql = "update up set mt=? where substr(w,1,16)=? and +rd=? and +fn=?" try: cur.execute(sql, (cj["lmod"], dwark[:16], job["prel"], job["name"])) cur.connection.commit() ap = djoin(job["ptop"], job["prel"], job["name"]) mt = bos.utime_c(self.log, ap, int(cj["lmod"]), False, True) self.log("touched %r from %d to %d" % (ap, job["lmod"], mt)) except Exception as ex: self.log("umod failed, %r" % (ex,), 3) return ret def _untaken(self, fdir: str, job: dict[str, Any], ts: float) -> str: fname = job["name"] ip = job["addr"] if self.args.nw: return fname fp = djoin(fdir, fname) ow = job.get("replace") and bos.path.exists(fp) if ow: replace_arg = str(job["replace"]).lower() if ow and "skip" in replace_arg: # type: ignore self.log("skipping upload, filename already exists: %r" % fp) err = "upload rejected, a file with that name already exists" raise Pebkac(409, err) if ow and "mt" in replace_arg: # type: ignore mts = bos.stat(fp).st_mtime mtc = job["lmod"] if mtc < mts: t = "will not overwrite; server %d sec newer than client; %d > %d %r" self.log(t % (mts - mtc, mts, mtc, fp)) ow = False ptop = job["ptop"] vf = self.flags.get(ptop) or {} if ow: self.log("replacing existing file at %r" % (fp,)) cur = None st = bos.stat(fp) try: vrel = vjoin(job["prel"], fname) xlink = bool(vf.get("xlink")) cur, wark, _, _, _, _, _ = self._find_from_vpath(ptop, vrel) self._forget_file(ptop, vrel, vf, cur, wark, True, st.st_size, xlink) except Exception as ex: self.log("skipping replace-relink: %r" % (ex,)) finally: if cur: cur.connection.commit() wunlink(self.log, fp, vf) if self.args.plain_ip: dip = ip.replace(":", ".") else: dip = self.hub.iphash.s(ip) f, ret = ren_open( fname, "wb", fdir=fdir, suffix="-%.6f-%s" % (ts, dip), vf=vf, ) f.close() return ret def _symlink( self, src: str, dst: str, flags: dict[str, Any], verbose: bool = True, rm: bool = False, lmod: float = 0, fsrc: Optional[str] = None, is_mv: bool = False, ) -> None: if src == dst or (fsrc and fsrc == dst): t = "symlinking a file to itself?? orig(%s) fsrc(%s) link(%s)" raise Exception(t % (src, fsrc, dst)) if verbose: t = "linking dupe:\n point-to: {0!r}\n link-loc: {1!r}" if fsrc: t += "\n data-src: {2!r}" self.log(t.format(src, dst, fsrc)) if self.args.nw: return linked = 0 try: if rm and bos.path.exists(dst): wunlink(self.log, dst, flags) if not is_mv and not flags.get("dedup"): raise Exception("dedup is disabled in config") if "reflink" in flags: if not USE_FICLONE: raise Exception("reflink") # python 3.14 or newer; no need try: with open(fsenc(src), "rb") as fi, open(fsenc(dst), "wb") as fo: fcntl.ioctl(fo.fileno(), fcntl.FICLONE, fi.fileno()) if "fperms" in flags: set_fperms(fo, flags) except: if bos.path.exists(dst): wunlink(self.log, dst, flags) raise if lmod: bos.utime_c(self.log, dst, int(lmod), False) return lsrc = src ldst = dst fs1 = bos.stat(os.path.dirname(src)).st_dev fs2 = bos.stat(os.path.dirname(dst)).st_dev if fs1 == 0 or fs2 == 0: # py2 on winxp or other unsupported combination raise OSError(errno.ENOSYS, "filesystem does not have st_dev") elif fs1 == fs2: # same fs; make symlink as relative as possible spl = r"[\\/]" if WINDOWS else "/" nsrc = re.split(spl, src) ndst = re.split(spl, dst) nc = 0 for a, b in zip(nsrc, ndst): if a != b: break nc += 1 if nc > 1: zsl = nsrc[nc:] hops = len(ndst[nc:]) - 1 lsrc = "../" * hops + "/".join(zsl) if WINDOWS: lsrc = lsrc.replace("/", "\\") ldst = ldst.replace("/", "\\") try: if "hardlink" in flags: os.link(fsenc(absreal(src)), fsenc(dst)) linked = 2 except Exception as ex: self.log("cannot hardlink: " + repr(ex)) if "hardlinkonly" in flags: raise Exception("symlink-fallback disabled in cfg") if not linked: if ANYWIN: Path(ldst).symlink_to(lsrc) if not bos.path.exists(dst): try: wunlink(self.log, dst, flags) except: pass t = "the created symlink [%s] did not resolve to [%s]" raise Exception(t % (ldst, lsrc)) else: os.symlink(fsenc(lsrc), fsenc(ldst)) linked = 1 except Exception as ex: if str(ex) != "reflink": self.log("cannot link; creating copy: " + repr(ex)) if bos.path.isfile(src): csrc = src elif fsrc and bos.path.isfile(fsrc): csrc = fsrc else: t = "BUG: no valid sources to link from! orig(%r) fsrc(%r) link(%r)" self.log(t, 1) raise Exception(t % (src, fsrc, dst)) trystat_shutil_copy2(self.log, fsenc(csrc), fsenc(dst)) if linked < 2 and (linked < 1 or SYMTIME): if lmod: bos.utime_c(self.log, dst, int(lmod), False) if "fperms" in flags: set_ap_perms(dst, flags) def handle_chunks( self, ptop: str, wark: str, chashes: list[str] ) -> tuple[list[str], int, list[list[int]], str, float, int, bool]: self.fika = "u" with self.mutex, self.reg_mutex: self.db_act = self.vol_act[ptop] = time.time() job = self.registry[ptop].get(wark) if not job: known = " ".join([x for x in self.registry[ptop].keys()]) self.log("unknown wark [{}], known: {}".format(wark, known)) raise Pebkac(400, "unknown wark" + SEESLOG) if "t0c" not in job: job["t0c"] = time.time() if len(chashes) > 1 and len(chashes[1]) < 44: # first hash is full-length; expand remaining ones uniq = [] lut = set() for chash in job["hash"]: if chash not in lut: uniq.append(chash) lut.add(chash) try: nchunk = uniq.index(chashes[0]) except: raise Pebkac(400, "unknown chunk0 [%s]" % (chashes[0],)) expanded = [chashes[0]] for prefix in chashes[1:]: nchunk += 1 chash = uniq[nchunk] if not chash.startswith(prefix): t = "next sibling chunk does not start with expected prefix [%s]: [%s]" raise Pebkac(400, t % (prefix, chash)) expanded.append(chash) chashes = expanded for chash in chashes: if chash not in job["need"]: msg = "chash = {} , need:\n".format(chash) msg += "\n".join(job["need"]) self.log(msg) t = "already got that (%s) but thanks??" if chash not in job["hash"]: t = "unknown chunk wtf: %s" raise Pebkac(400, t % (chash,)) if chash in job["busy"]: nh = len(job["hash"]) idx = job["hash"].index(chash) t = "that chunk is already being written to:\n {}\n {} {}/{}\n {}" raise Pebkac(400, t.format(wark, chash, idx, nh, job["name"])) assert chash # type: ignore # !rm chunksize = up2k_chunksize(job["size"]) coffsets = [] nchunks = [] for chash in chashes: nchunk = [n for n, v in enumerate(job["hash"]) if v == chash] if not nchunk: raise Pebkac(400, "unknown chunk %s" % (chash,)) ofs = [chunksize * x for x in nchunk] coffsets.append(ofs) nchunks.append(nchunk) for ofs1, ofs2 in zip(coffsets, coffsets[1:]): gap = (ofs2[0] - ofs1[0]) - chunksize if gap: t = "only sibling chunks can be stitched; gap of %d bytes between offsets %d and %d in %s" raise Pebkac(400, t % (gap, ofs1[0], ofs2[0], job["name"])) path = djoin(job["ptop"], job["prel"], job["tnam"]) if not job["sprs"]: cur_sz = bos.path.getsize(path) if coffsets[0][0] > cur_sz: t = "please upload sequentially using one thread;\nserver filesystem does not support sparse files.\n file: {}\n chunk: {}\n cofs: {}\n flen: {}" t = t.format(job["name"], nchunks[0][0], coffsets[0][0], cur_sz) raise Pebkac(400, t) for chash in chashes: job["busy"][chash] = 1 job["poke"] = time.time() return chashes, chunksize, coffsets, path, job["lmod"], job["size"], job["sprs"] def fast_confirm_chunks( self, ptop: str, wark: str, chashes: list[str], locked: list[str] ) -> tuple[int, str]: if not self.mutex.acquire(False): return -1, "" if not self.reg_mutex.acquire(False): self.mutex.release() return -1, "" try: return self._confirm_chunks(ptop, wark, chashes, locked, False) finally: self.reg_mutex.release() self.mutex.release() def confirm_chunks( self, ptop: str, wark: str, written: list[str], locked: list[str] ) -> tuple[int, str]: self.fika = "u" with self.mutex, self.reg_mutex: return self._confirm_chunks(ptop, wark, written, locked, True) def _confirm_chunks( self, ptop: str, wark: str, written: list[str], locked: list[str], final: bool ) -> tuple[int, str]: if True: self.db_act = self.vol_act[ptop] = time.time() try: job = self.registry[ptop][wark] pdir = djoin(job["ptop"], job["prel"]) src = djoin(pdir, job["tnam"]) dst = djoin(pdir, job["name"]) except Exception as ex: return -2, "confirm_chunk, wark(%r)" % (ex,) # type: ignore for chash in locked if final else written: job["busy"].pop(chash, None) try: for chash in written: job["need"].remove(chash) except Exception as ex: for zs in locked: if job["busy"].pop(zs, None): self.log("panic-unlock wark(%s) chunk(%s)" % (wark, zs), 1) return -2, "confirm_chunk, chash(%s) %r" % (chash, ex) # type: ignore ret = len(job["need"]) if ret > 0: return ret, src if self.args.nw: self.regdrop(ptop, wark) return ret, dst def finish_upload(self, ptop: str, wark: str, busy_aps: dict[str, int]) -> None: self.busy_aps = busy_aps self.fika = "u" with self.mutex, self.reg_mutex: self._finish_upload(ptop, wark) if self.fx_backlog: self.do_fx_backlog() def _finish_upload(self, ptop: str, wark: str) -> None: try: job = self.registry[ptop][wark] pdir = djoin(job["ptop"], job["prel"]) src = djoin(pdir, job["tnam"]) dst = djoin(pdir, job["name"]) except Exception as ex: self.log(min_ex(), 1) raise Pebkac(500, "finish_upload, wark, %r%s" % (ex, SEESLOG)) if job["need"]: self.log(min_ex(), 1) t = "finish_upload %s with remaining chunks %s%s" raise Pebkac(500, t % (wark, job["need"], SEESLOG)) upt = job.get("at") or time.time() vflags = self.flags[ptop] atomic_move(self.log, src, dst, vflags) times = (int(time.time()), int(job["lmod"])) t = "no more chunks, setting times %s (%d) on %r" self.log(t % (times, bos.path.getsize(dst), dst)) bos.utime_c(self.log, dst, times[1], False) # the above logmsg (and associated logic) is retained due to unforget.py zs = "prel name lmod size ptop vtop wark dwrk host user addr" z2 = [job[x] for x in zs.split()] wake_sr = False try: flt = job["life"] vfs = self.vfs.all_vols[job["vtop"]] vlt = vfs.flags["lifetime"] if vlt and flt > 1 and flt < vlt: upt -= vlt - flt wake_sr = True t = "using client lifetime; at={:.0f} ({}-{})" self.log(t.format(upt, vlt, flt)) except: pass z2.append(upt) if self.idx_wark(vflags, *z2): del self.registry[ptop][wark] else: for k in "host tnam busy sprs poke".split(): del job[k] job.pop("t0c", None) job["t0"] = int(job["t0"]) job["hash"] = [] job["done"] = 1 self.regdrop(ptop, wark) if wake_sr: with self.rescan_cond: self.rescan_cond.notify_all() dupes = self.dupesched.pop(dst, []) if not dupes: return cur = self.cur.get(ptop) for rd, fn, lmod in dupes: d2 = djoin(ptop, rd, fn) if os.path.exists(d2): continue self._symlink(dst, d2, self.flags[ptop], lmod=lmod) if cur: self.db_add(cur, vflags, rd, fn, lmod, *z2[3:]) if cur: cur.connection.commit() def regdrop(self, ptop: str, wark: str) -> None: olds = self.droppable[ptop] if wark: olds.append(wark) if len(olds) <= self.args.reg_cap: return n = len(olds) - int(self.args.reg_cap / 2) t = "up2k-registry [{}] has {} droppables; discarding {}" self.log(t.format(ptop, len(olds), n)) for k in olds[:n]: self.registry[ptop].pop(k, None) self.droppable[ptop] = olds[n:] def idx_wark( self, vflags: dict[str, Any], rd: str, fn: str, lmod: float, sz: int, ptop: str, vtop: str, wark: str, dwark: str, host: str, usr: str, ip: str, at: float, skip_xau: bool = False, ) -> bool: cur = self.cur.get(ptop) if not cur: return False self.db_act = self.vol_act[ptop] = time.time() try: self.db_add( cur, vflags, rd, fn, lmod, sz, ptop, vtop, wark, dwark, host, usr, ip, at, skip_xau, ) cur.connection.commit() except Exception as ex: x = self.register_vpath(ptop, {}) assert x # !rm db_ex_chk(self.log, ex, x[1]) raise if "e2t" in self.flags[ptop]: self.tagq.put((ptop, dwark, rd, fn, sz, ip, at)) self.n_tagq += 1 return True def db_rm( self, db: "sqlite3.Cursor", vflags: dict[str, Any], rd: str, fn: str, sz: int ) -> None: sql = "delete from up where rd = ? and fn = ?" try: r = db.execute(sql, (rd, fn)) except: assert self.mem_cur # !rm r = db.execute(sql, s3enc(self.mem_cur, rd, fn)) if not r.rowcount: return self.volsize[db] -= sz self.volnfiles[db] -= 1 if "nodirsz" not in vflags: try: q = "update ds set nf=nf-1, sz=sz-? where rd=?" while True: db.execute(q, (sz, rd)) if not rd: break rd = rd.rsplit("/", 1)[0] if "/" in rd else "" except: pass def db_add( self, db: "sqlite3.Cursor", vflags: dict[str, Any], rd: str, fn: str, ts: float, sz: int, ptop: str, vtop: str, wark: str, dwark: str, host: str, usr: str, ip: str, at: float, skip_xau: bool = False, ) -> None: self.db_rm(db, vflags, rd, fn, sz) if not ip: db_ip = "" else: # plugins may expect this to look like an actual IP db_ip = "1.1.1.1" if "no_db_ip" in vflags else ip sql = "insert into up values (?,?,?,?,?,?,?,?)" v = (dwark, int(ts), sz, rd, fn, db_ip, int(at or 0), usr) try: db.execute(sql, v) except: assert self.mem_cur # !rm rd, fn = s3enc(self.mem_cur, rd, fn) v = (dwark, int(ts), sz, rd, fn, db_ip, int(at or 0), usr) db.execute(sql, v) self.volsize[db] += sz self.volnfiles[db] += 1 xau = False if skip_xau else vflags.get("xau") dst = djoin(ptop, rd, fn) if xau: hr = runhook( self.log, None, self, "xau.up2k", xau, dst, djoin(vtop, rd, fn), host, usr, self.vfs.get_perms(djoin(vtop, rd, fn), usr), ts, sz, ip, at or time.time(), None, ) t = hr.get("rejectmsg") or "" if t or hr.get("rc") != 0: if not t: t = "upload blocked by xau server config: %r" t = t % (djoin(vtop, rd, fn),) self.log(t, 1) wunlink(self.log, dst, vflags) self.registry[ptop].pop(wark, None) raise Pebkac(403, t) xiu = vflags.get("xiu") if xiu: cds: set[int] = set() for cmd in xiu: m = self.xiu_ptn.search(cmd) cds.add(int(m.group(1)) if m else 5) q = "insert into iu values (?,?,?,?)" for cd in cds: # one for each unique cooldown duration try: db.execute(q, (cd, dwark[:16], rd, fn)) except: assert self.mem_cur # !rm rd, fn = s3enc(self.mem_cur, rd, fn) db.execute(q, (cd, dwark[:16], rd, fn)) if self.xiu_asleep: self.xiu_asleep = False with self.rescan_cond: self.rescan_cond.notify_all() if rd and sz and fn.lower() in self.args.th_coversd_set: # wasteful; db_add will re-index actual covers # but that won't catch existing files crd, cdn = rd.rsplit("/", 1) if "/" in rd else ("", rd) try: q = "select fn from cv where rd=? and dn=?" db_cv = db.execute(q, (crd, cdn)).fetchone()[0] db_lcv = db_cv.lower() if db_lcv in self.args.th_coversd_set: idx_db = self.args.th_coversd.index(db_lcv) idx_fn = self.args.th_coversd.index(fn.lower()) add_cv = idx_fn < idx_db else: add_cv = True except: add_cv = True if add_cv: try: db.execute("delete from cv where rd=? and dn=?", (crd, cdn)) db.execute("insert into cv values (?,?,?)", (crd, cdn, fn)) except: pass if "nodirsz" not in vflags: try: q = "update ds set nf=nf+1, sz=sz+? where rd=?" q2 = "insert into ds values(?,?,1)" while True: if not db.execute(q, (sz, rd)).rowcount: db.execute(q2, (rd, sz)) if not rd: break rd = rd.rsplit("/", 1)[0] if "/" in rd else "" except: pass def handle_fs_abrt(self, akey: str) -> None: self.abrt_key = akey def handle_rm( self, uname: str, ip: str, vpaths: list[str], lim: list[int], rm_up: bool, unpost: bool, ) -> str: n_files = 0 ok = {} ng = {} for vp in vpaths: if lim and lim[0] <= 0: self.log("hit delete limit of {} files".format(lim[1]), 3) break a, b, c = self._handle_rm(uname, ip, vp, lim, rm_up, unpost) n_files += a for k in b: ok[k] = 1 for k in c: ng[k] = 1 ng = {k: 1 for k in ng if k not in ok} iok = len(ok) ing = len(ng) return "deleted {} files (and {}/{} folders)".format(n_files, iok, iok + ing) def _handle_rm( self, uname: str, ip: str, vpath: str, lim: list[int], rm_up: bool, unpost: bool ) -> tuple[int, list[str], list[str]]: self.db_act = time.time() partial = "" if not unpost: permsets = [[True, False, False, True]] vn0, rem0 = self.vfs.get(vpath, uname, *permsets[0]) vn, rem = vn0.get_dbv(rem0) else: # unpost with missing permissions? verify with db permsets = [[False, True]] vn0, rem0 = self.vfs.get(vpath, uname, *permsets[0]) vn, rem = vn0.get_dbv(rem0) ptop = vn.realpath self.fika = "d" with self.mutex, self.reg_mutex: abrt_cfg = vn.flags.get("u2abort", 1) addr = (ip or "\n") if abrt_cfg in (1, 2) else "" user = ((uname or "\n"), "*") if abrt_cfg in (1, 3) else None reg = self.registry.get(ptop, {}) if abrt_cfg else {} for wark, job in reg.items(): if (addr and addr != job["addr"]) or ( user and job["user"] not in user ): continue jrem = djoin(job["prel"], job["name"]) if ANYWIN: jrem = jrem.replace("\\", "/") if jrem == rem: if job["ptop"] != ptop: t = "job.ptop [%s] != vol.ptop [%s] ??" raise Exception(t % (job["ptop"], ptop)) partial = vn.canonical(vjoin(job["prel"], job["tnam"])) break if partial: dip = ip dat = time.time() dun = uname un_cfg = 1 else: un_cfg = vn.flags["unp_who"] if not self.args.unpost or not un_cfg: t = "the unpost feature is disabled in server config" raise Pebkac(400, t) _, _, _, _, dip, dat, dun = self._find_from_vpath(ptop, rem) t = "you cannot delete this: " if not dip: t += "file not found" elif dip != ip and un_cfg in (1, 2): t += "not uploaded by (You)" elif dun != uname and un_cfg in (1, 3): t += "not uploaded by (You)" elif dat < time.time() - self.args.unpost: t += "uploaded too long ago" else: t = "" if t: raise Pebkac(400, t) ptop = vn.realpath atop = vn.canonical(rem, False) self.vol_act[ptop] = self.db_act adir, fn = os.path.split(atop) try: st = bos.lstat(atop) is_dir = stat.S_ISDIR(st.st_mode) except: # NOTE: "file not found" *sftpd raise Pebkac(400, "file not found on disk (already deleted?)") if "bcasechk" in vn.flags and not vn.casechk(rem, False): raise Pebkac(400, "file does not exist case-sensitively") scandir = not self.args.no_scandir if is_dir: # note: deletion inside shares would require a rewrite here; # shares necessitate get_dbv which is incompatible with walk g = vn0.walk("", rem0, [], uname, permsets, 2, scandir, True) if unpost: raise Pebkac(400, "cannot unpost folders") elif stat.S_ISLNK(st.st_mode) or stat.S_ISREG(st.st_mode): voldir = vsplit(rem)[0] vpath_dir = vsplit(vpath)[0] g = [(vn, voldir, vpath_dir, adir, [(fn, 0)], [], {})] # type: ignore else: self.log("rm: skip type-0%o file %r" % (st.st_mode, atop)) return 0, [], [] xbd = vn.flags.get("xbd") xad = vn.flags.get("xad") n_files = 0 for dbv, vrem, _, adir, files, rd, vd in g: for fn in [x[0] for x in files]: if lim: lim[0] -= 1 if lim[0] < 0: self.log("hit delete limit of {} files".format(lim[1]), 3) break abspath = djoin(adir, fn) st = stl = bos.lstat(abspath) if stat.S_ISLNK(st.st_mode): try: st = bos.stat(abspath) except: pass volpath = ("%s/%s" % (vrem, fn)).strip("/") vpath = ("%s/%s" % (dbv.vpath, volpath)).strip("/") self.log("rm %r\n %r" % (vpath, abspath)) if not unpost: # recursion-only sanchk _ = dbv.get(volpath, uname, *permsets[0]) if xbd: hr = runhook( self.log, None, self, "xbd", xbd, abspath, vpath, "", uname, self.vfs.get_perms(vpath, uname), stl.st_mtime, st.st_size, ip, time.time(), None, ) t = hr.get("rejectmsg") or "" if t or hr.get("rc") != 0: if not t: t = "delete blocked by xbd server config: %r" % (abspath,) self.log(t, 1) continue n_files += 1 self.fika = "d" with self.mutex, self.reg_mutex: cur = None try: ptop = dbv.realpath xlink = bool(dbv.flags.get("xlink")) cur, wark, _, _, _, _, _ = self._find_from_vpath(ptop, volpath) self._forget_file( ptop, volpath, dbv.flags, cur, wark, True, st.st_size, xlink ) finally: if cur: cur.connection.commit() wunlink(self.log, abspath, dbv.flags) if partial: wunlink(self.log, partial, dbv.flags) partial = "" if xad: runhook( self.log, None, self, "xad", xad, abspath, vpath, "", uname, self.vfs.get_perms(vpath, uname), stl.st_mtime, st.st_size, ip, time.time(), None, ) if is_dir: ok, ng = rmdirs(self.log_func, scandir, True, atop, 1) else: ok = ng = [] if rm_up: ok2, ng2 = rmdirs_up(os.path.dirname(atop), ptop) else: ok2 = ng2 = [] return n_files, ok + ok2, ng + ng2 def handle_cp(self, abrt: str, uname: str, ip: str, svp: str, dvp: str) -> str: if svp == dvp or dvp.startswith(svp + "/"): raise Pebkac(400, "cp: cannot copy parent into subfolder") svn, srem = self.vfs.get(svp, uname, True, False) dvn, drem = self.vfs.get(dvp, uname, False, True) svn_dbv, _ = svn.get_dbv(srem) sabs = svn.canonical(srem, False) curs: set["sqlite3.Cursor"] = set() self.db_act = self.vol_act[svn_dbv.realpath] = time.time() st = bos.stat(sabs) if "bcasechk" in svn.flags and not svn.casechk(srem, False): raise Pebkac(400, "file does not exist case-sensitively") if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): self.fika = "c" with self.mutex: try: ret = self._cp_file(uname, ip, svp, dvp, curs) finally: for v in curs: v.connection.commit() return ret if not stat.S_ISDIR(st.st_mode): raise Pebkac(400, "cannot copy type-0%o file" % (st.st_mode,)) permsets = [[True, False]] scandir = not self.args.no_scandir # if user can see dotfiles in target volume, only include # dots from source vols where user also has the dot perm dots = 1 if uname in dvn.axs.udot else 2 # don't use svn_dbv; would skip subvols due to _ls `if not rem:` g = svn.walk("", srem, [], uname, permsets, dots, scandir, True) self.fika = "c" with self.mutex: try: for dbv, vrem, _, atop, files, rd, vd in g: for fn in files: self.db_act = self.vol_act[dbv.realpath] = time.time() svpf = "/".join(x for x in [dbv.vpath, vrem, fn[0]] if x) if not svpf.startswith(svp + "/"): # assert self.log(min_ex(), 1) t = "cp: bug at %r, top %r%s" raise Pebkac(500, t % (svpf, svp, SEESLOG)) dvpf = dvp + svpf[len(svp) :] self._cp_file(uname, ip, svpf, dvpf, curs) if abrt and abrt == self.abrt_key: raise Pebkac(400, "filecopy aborted by http-api") for v in curs: v.connection.commit() curs.clear() finally: for v in curs: v.connection.commit() return "k" def _cp_file( self, uname: str, ip: str, svp: str, dvp: str, curs: set["sqlite3.Cursor"] ) -> str: svn, srem = self.vfs.get(svp, uname, True, False) svn_dbv, srem_dbv = svn.get_dbv(srem) dvn, drem = self.vfs.get(dvp, uname, False, True) dvn, drem = dvn.get_dbv(drem) sabs = svn.canonical(srem, False) dabs = dvn.canonical(drem) drd, dfn = vsplit(drem) if bos.path.exists(dabs): raise Pebkac(400, "cp2: target file exists") st = stl = bos.lstat(sabs) if stat.S_ISLNK(stl.st_mode): is_link = True try: st = bos.stat(sabs) except: pass # broken symlink; keep as-is elif not stat.S_ISREG(st.st_mode): self.log("skipping type-0%o file %r" % (st.st_mode, sabs)) return "" else: is_link = False ftime = stl.st_mtime fsize = st.st_size xbc = svn.flags.get("xbc") xac = dvn.flags.get("xac") if xbc: hr = runhook( self.log, None, self, "xbc", xbc, sabs, svp, "", uname, self.vfs.get_perms(svp, uname), ftime, fsize, ip, time.time(), None, ) t = hr.get("rejectmsg") or "" if t or hr.get("rc") != 0: if not t: t = "copy blocked by xbr server config: %r" % (svp,) self.log(t, 1) raise Pebkac(405, t) bos.makedirs(os.path.dirname(dabs), vf=dvn.flags) c1, w, ftime_, fsize_, ip, at, un = self._find_from_vpath( svn_dbv.realpath, srem_dbv ) c2 = self.cur.get(dvn.realpath) if w: assert c1 # !rm if c2 and c2 != c1: self._copy_tags(c1, c2, w) curs.add(c1) if c2: self.db_add( c2, {}, # skip upload hooks drd, dfn, ftime, fsize, dvn.realpath, dvn.vpath, w, w, "", un or "", ip or "", at or 0, ) curs.add(c2) else: self.log("not found in src db: %r" % (svp,)) try: if is_link and st != stl: # relink non-broken symlinks to still work after the move, # but only resolve 1st level to maintain relativity dlink = bos.readlink(sabs) dlink = os.path.join(os.path.dirname(sabs), dlink) dlink = bos.path.abspath(dlink) self._symlink(dlink, dabs, dvn.flags, lmod=ftime) else: self._symlink(sabs, dabs, dvn.flags, lmod=ftime) except OSError as ex: if ex.errno != errno.EXDEV: raise self.log("using plain copy (%s):\n %r\n %r" % (ex.strerror, sabs, dabs)) b1, b2 = fsenc(sabs), fsenc(dabs) is_link = os.path.islink(b1) # due to _relink try: trystat_shutil_copy2(self.log, b1, b2) except: try: wunlink(self.log, dabs, dvn.flags) except: pass if not is_link: raise # broken symlink? keep it as-is try: zb = os.readlink(b1) os.symlink(zb, b2) except: wunlink(self.log, dabs, dvn.flags) raise if is_link: try: times = (int(time.time()), int(ftime)) bos.utime(dabs, times, False) except: pass if "fperms" in dvn.flags: set_ap_perms(dabs, dvn.flags) if xac: runhook( self.log, None, self, "xac", xac, dabs, dvp, "", uname, self.vfs.get_perms(dvp, uname), ftime, fsize, ip, time.time(), None, ) return "k" def handle_mv(self, abrt: str, uname: str, ip: str, svp: str, dvp: str) -> str: if svp == dvp or dvp.startswith(svp + "/"): raise Pebkac(400, "mv: cannot move parent into subfolder") svn, srem = self.vfs.get(svp, uname, True, False, True) jail, jail_rem = svn.get_dbv(srem) sabs = svn.canonical(srem, False) curs: set["sqlite3.Cursor"] = set() self.db_act = self.vol_act[jail.realpath] = time.time() if not jail_rem: raise Pebkac(400, "mv: cannot move a mountpoint") st = bos.lstat(sabs) if "bcasechk" in svn.flags and not svn.casechk(srem, False): raise Pebkac(400, "file does not exist case-sensitively") if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): self.fika = "m" with self.mutex: try: ret = self._mv_file(uname, ip, svp, dvp, curs) finally: for v in curs: v.connection.commit() return ret if not stat.S_ISDIR(st.st_mode): raise Pebkac(400, "cannot move type-0%o file" % (st.st_mode,)) permsets = [[True, False, True]] scandir = not self.args.no_scandir # following symlinks is too scary g = svn.walk("", srem, [], uname, permsets, 2, scandir, True) for dbv, vrem, _, atop, files, rd, vd in g: if dbv != jail: # fail early (prevent partial moves) raise Pebkac(400, "mv: source folder contains other volumes") g = svn.walk("", srem, [], uname, permsets, 2, scandir, True) self.fika = "m" with self.mutex: try: for dbv, vrem, _, atop, files, rd, vd in g: if dbv != jail: # the actual check (avoid toctou) raise Pebkac(400, "mv: source folder contains other volumes") for fn in files: self.db_act = self.vol_act[dbv.realpath] = time.time() svpf = "/".join(x for x in [dbv.vpath, vrem, fn[0]] if x) if not svpf.startswith(svp + "/"): # assert self.log(min_ex(), 1) t = "mv: bug at %r, top %r%s" raise Pebkac(500, t % (svpf, svp, SEESLOG)) dvpf = dvp + svpf[len(svp) :] self._mv_file(uname, ip, svpf, dvpf, curs) if abrt and abrt == self.abrt_key: raise Pebkac(400, "filemove aborted by http-api") for v in curs: v.connection.commit() curs.clear() finally: for v in curs: v.connection.commit() rm_ok, rm_ng = rmdirs(self.log_func, scandir, True, sabs, 1) for zsl in (rm_ok, rm_ng): for ap in reversed(zsl): if not ap.startswith(sabs): self.log(min_ex(), 1) t = "mv_d: bug at %r, top %r%s" raise Pebkac(500, t % (ap, sabs, SEESLOG)) rem = ap[len(sabs) :].replace(os.sep, "/").lstrip("/") vp = vjoin(dvp, rem) try: dvn, drem = self.vfs.get(vp, uname, False, True) dap = dvn.canonical(drem) bos.mkdir(dap, dvn.flags["chmod_d"]) if "chown" in dvn.flags: bos.chown(dap, dvn.flags["uid"], dvn.flags["gid"]) except: pass return "k" def _mv_file( self, uname: str, ip: str, svp: str, dvp: str, curs: set["sqlite3.Cursor"] ) -> str: svn, srem = self.vfs.get(svp, uname, True, False, True) svn, srem = svn.get_dbv(srem) dvn, drem = self.vfs.get(dvp, uname, False, True) dvn, drem = dvn.get_dbv(drem) sabs = svn.canonical(srem, False) dabs = dvn.canonical(drem) drd, dfn = vsplit(drem) n1 = svp.split("/")[-1] n2 = dvp.split("/")[-1] if n1.startswith(".") or n2.startswith("."): if self.args.no_dot_mv: raise Pebkac(400, "moving dotfiles is disabled in server config") elif self.args.no_dot_ren and n1 != n2: raise Pebkac(400, "renaming dotfiles is disabled in server config") if bos.path.exists(dabs): raise Pebkac(400, "mv2: target file exists") is_link = is_dirlink = False st = stl = bos.lstat(sabs) if stat.S_ISLNK(stl.st_mode): is_link = True try: st = bos.stat(sabs) is_dirlink = stat.S_ISDIR(st.st_mode) except: pass # broken symlink; keep as-is ftime = stl.st_mtime fsize = st.st_size xbr = svn.flags.get("xbr") xar = dvn.flags.get("xar") if xbr: hr = runhook( self.log, None, self, "xbr", xbr, sabs, svp, "", uname, self.vfs.get_perms(svp, uname), ftime, fsize, ip, time.time(), None, ) t = hr.get("rejectmsg") or "" if t or hr.get("rc") != 0: if not t: t = "move blocked by xbr server config: %r" % (svp,) self.log(t, 1) raise Pebkac(405, t) is_xvol = svn.realpath != dvn.realpath bos.makedirs(os.path.dirname(dabs), vf=dvn.flags) if is_dirlink: dlabs = absreal(sabs) t = "moving symlink from %r to %r, target %r" self.log(t % (sabs, dabs, dlabs)) mt = bos.path.getmtime(sabs, False) wunlink(self.log, sabs, svn.flags) self._symlink(dlabs, dabs, dvn.flags, False, lmod=mt) # folders are too scary, schedule rescan of both vols self.need_rescan.add(svn.vpath) self.need_rescan.add(dvn.vpath) with self.rescan_cond: self.rescan_cond.notify_all() if xar: runhook( self.log, None, self, "xar.ln", xar, dabs, dvp, "", uname, self.vfs.get_perms(dvp, uname), ftime, fsize, ip, time.time(), None, ) return "k" c1, w, ftime_, fsize_, ip, at, un = self._find_from_vpath(svn.realpath, srem) c2 = self.cur.get(dvn.realpath) has_dupes = False if w: assert c1 # !rm if c2 and c2 != c1: if "nodupem" in dvn.flags: q = "select w from up where substr(w,1,16) = ?" for (w2,) in c2.execute(q, (w[:16],)): if w == w2: t = "file exists in target volume, and dupes are forbidden in config" raise Pebkac(400, t) self._copy_tags(c1, c2, w) xlink = bool(svn.flags.get("xlink")) with self.reg_mutex: has_dupes = self._forget_file( svn.realpath, srem, svn.flags, c1, w, is_xvol, fsize_ or fsize, xlink, ) if not is_xvol: has_dupes = self._relink(w, svn.realpath, srem, dabs, c1, xlink) curs.add(c1) if c2: self.db_add( c2, {}, # skip upload hooks drd, dfn, ftime, fsize, dvn.realpath, dvn.vpath, w, w, "", un or "", ip or "", at or 0, ) curs.add(c2) else: self.log("not found in src db: %r" % (svp,)) try: if is_xvol and has_dupes: raise OSError(errno.EXDEV, "src is symlink") if is_link and st != stl: # relink non-broken symlinks to still work after the move, # but only resolve 1st level to maintain relativity dlink = bos.readlink(sabs) dlink = os.path.join(os.path.dirname(sabs), dlink) dlink = bos.path.abspath(dlink) self._symlink(dlink, dabs, dvn.flags, lmod=ftime, is_mv=True) wunlink(self.log, sabs, svn.flags) else: atomic_move(self.log, sabs, dabs, svn.flags) if svn != dvn and "fperms" in dvn.flags: set_ap_perms(dabs, dvn.flags) except OSError as ex: if ex.errno != errno.EXDEV: raise self.log("using copy+delete (%s):\n %r\n %r" % (ex.strerror, sabs, dabs)) b1, b2 = fsenc(sabs), fsenc(dabs) is_link = os.path.islink(b1) # due to _relink try: trystat_shutil_copy2(self.log, b1, b2) except: try: wunlink(self.log, dabs, dvn.flags) except: pass if not is_link: raise # broken symlink? keep it as-is try: zb = os.readlink(b1) os.symlink(zb, b2) except: wunlink(self.log, dabs, dvn.flags) raise if is_link: try: times = (int(time.time()), int(ftime)) bos.utime(dabs, times, False) except: pass if "fperms" in dvn.flags: set_ap_perms(dabs, dvn.flags) wunlink(self.log, sabs, svn.flags) if xar: runhook( self.log, None, self, "xar.mv", xar, dabs, dvp, "", uname, self.vfs.get_perms(dvp, uname), ftime, fsize, ip, time.time(), None, ) return "k" def _copy_tags( self, csrc: "sqlite3.Cursor", cdst: "sqlite3.Cursor", wark: str ) -> None: w = wark[:16] if cdst.execute("select * from mt where w=? limit 1", (w,)).fetchone(): return # existing tags in dest db for _, k, v in csrc.execute("select * from mt where w=?", (w,)): cdst.execute("insert into mt values(?,?,?)", (w, k, v)) def _find_from_vpath( self, ptop: str, vrem: str ) -> tuple[ Optional["sqlite3.Cursor"], Optional[str], Optional[int], Optional[int], str, Optional[int], str, ]: cur = self.cur.get(ptop) if not cur: return None, None, None, None, "", None, "" rd, fn = vsplit(vrem) q = "select w, mt, sz, ip, at, un from up where rd=? and fn=? limit 1" try: c = cur.execute(q, (rd, fn)) except: assert self.mem_cur # !rm c = cur.execute(q, s3enc(self.mem_cur, rd, fn)) hit = c.fetchone() if hit: wark, ftime, fsize, ip, at, un = hit return cur, wark, ftime, fsize, ip, at, un return cur, None, None, None, "", None, "" def _forget_file( self, ptop: str, vrem: str, vflags: dict[str, Any], cur: Optional["sqlite3.Cursor"], wark: Optional[str], drop_tags: bool, sz: int, xlink: bool, ) -> bool: srd, sfn = vsplit(vrem) has_dupes = False self.log("forgetting %r" % (vrem,)) if wark and cur: self.log("found {} in db".format(wark)) if drop_tags: if self._relink(wark, ptop, vrem, "", cur, xlink): has_dupes = True drop_tags = False if drop_tags: q = "delete from mt where w=?" cur.execute(q, (wark[:16],)) self.db_rm(cur, vflags, srd, sfn, sz) reg = self.registry.get(ptop) if reg: vdir = vsplit(vrem)[0] wark = wark or next( ( x for x, y in reg.items() if sfn in [y["name"], y.get("tnam")] and y["prel"] == vdir ), "", ) job = reg.get(wark) if wark else None if job: if job["need"]: t = "forgetting partial upload {} ({})" p = self._vis_job_progress(job) self.log(t.format(wark, p)) src = djoin(ptop, vrem) zi = len(self.dupesched.pop(src, [])) if zi: t = "...and forgetting %d links in dupesched" self.log(t % (zi,)) assert wark del reg[wark] return has_dupes def _relink( self, wark: str, sptop: str, srem: str, dabs: str, vcur: Optional["sqlite3.Cursor"], xlink: bool, ) -> int: dupes = [] sabs = djoin(sptop, srem) if self.no_expr_idx: q = r"select rd, fn from up where w = ?" argv = (wark,) else: q = r"select rd, fn from up where substr(w,1,16)=? and +w=?" argv = (wark[:16], wark) for ptop, cur in self.cur.items(): if not xlink and cur and cur != vcur: continue for rd, fn in cur.execute(q, argv): if rd.startswith("//") or fn.startswith("//"): rd, fn = s3dec(rd, fn) dvrem = vjoin(rd, fn).strip("/") if ptop != sptop or srem != dvrem: dupes.append([ptop, dvrem]) self.log("found %s dupe: %r %r" % (wark, ptop, dvrem)) if not dupes: return 0 full: dict[str, tuple[str, str]] = {} links: dict[str, tuple[str, str]] = {} for ptop, vp in dupes: ap = djoin(ptop, vp) try: d = links if bos.path.islink(ap) else full d[ap] = (ptop, vp) except: self.log("relink: not found: %r" % (ap,)) # self.log("full:\n" + "\n".join(" {:90}: {}".format(*x) for x in full.items())) # self.log("links:\n" + "\n".join(" {:90}: {}".format(*x) for x in links.items())) if not dabs and not full and links: # deleting final remaining full copy; swap it with a symlink slabs = list(sorted(links.keys()))[0] ptop, rem = links.pop(slabs) self.log("linkswap %r and %r" % (sabs, slabs)) mt = bos.path.getmtime(slabs, False) flags = self.flags.get(ptop) or {} atomic_move(self.log, sabs, slabs, flags) try: bos.utime(slabs, (int(time.time()), int(mt)), False) except: self.log("relink: failed to utime(%r, %s)" % (slabs, mt), 3) self._symlink(slabs, sabs, flags, False, is_mv=True) full[slabs] = (ptop, rem) sabs = slabs if not dabs: dabs = list(sorted(full.keys()))[0] for alink, parts in links.items(): lmod = 0.0 try: faulty = False ldst = alink try: for n in range(40): # MAXSYMLINKS zs = bos.readlink(ldst) ldst = os.path.join(os.path.dirname(ldst), zs) ldst = bos.path.abspath(ldst) if not bos.path.islink(ldst): break if ldst == sabs: t = "relink because level %d would break:" self.log(t % (n,), 6) faulty = True except Exception as ex: self.log("relink because walk failed: %s; %r" % (ex, ex), 3) faulty = True zs = absreal(alink) if ldst != zs: t = "relink because computed != actual destination:\n %r\n %r" self.log(t % (ldst, zs), 3) ldst = zs faulty = True if bos.path.islink(ldst): raise Exception("broken symlink: %s" % (alink,)) if alink != sabs and ldst != sabs and not faulty: continue # original symlink OK; leave it be except Exception as ex: t = "relink because symlink verification failed: %s; %r" self.log(t % (ex, ex), 3) self.log("relinking %r to %r" % (alink, dabs)) flags = self.flags.get(parts[0]) or {} try: lmod = bos.path.getmtime(alink, False) wunlink(self.log, alink, flags) except: pass # this creates a link pointing from dabs to alink; alink may # not exist yet, which becomes problematic if the symlinking # fails and it has to fall back on hardlinking/copying files # (for example a volume with symlinked dupes but no --dedup); # fsrc=sabs is then a source that currently resolves to copy self._symlink( dabs, alink, flags, False, lmod=lmod or 0, fsrc=sabs, is_mv=True ) return len(full) + len(links) def _get_wark(self, cj: dict[str, Any]) -> str: if len(cj["name"]) > 1024 or len(cj["hash"]) > 512 * 1024: # 16TiB raise Pebkac(400, "name or numchunks not according to spec") for k in cj["hash"]: if not self.r_hash.match(k): raise Pebkac( 400, "at least one hash is not according to spec: %r" % (k,) ) # try to use client-provided timestamp, don't care if it fails somehow try: cj["lmod"] = int(cj["lmod"]) except: cj["lmod"] = int(time.time()) if cj["hash"]: wark = up2k_wark_from_hashlist(self.salt, cj["size"], cj["hash"]) else: wark = up2k_wark_from_metadata( self.salt, cj["size"], cj["lmod"], cj["prel"], cj["name"] ) return wark def _hashlist_from_file( self, path: str, prefix: str = "" ) -> tuple[list[str], os.stat_result]: st = bos.stat(path) fsz = st.st_size csz = up2k_chunksize(fsz) ret = [] suffix = " MB, {}".format(path) with open(fsenc(path), "rb", self.args.iobuf) as f: if self.mth and fsz >= 1024 * 512: tlt = self.mth.hash(f, fsz, csz, self.pp, prefix, suffix) ret = [x[0] for x in tlt] fsz = 0 while fsz > 0: # same as `hash_at` except for `imutex` / bufsz if self.stop: return [], st if self.pp: mb = fsz // (1024 * 1024) self.pp.msg = prefix + str(mb) + suffix hashobj = hashlib.sha512() rem = min(csz, fsz) fsz -= rem while rem > 0: buf = f.read(min(rem, 64 * 1024)) if not buf: raise Exception("EOF at " + str(f.tell())) hashobj.update(buf) rem -= len(buf) digest = hashobj.digest()[:33] ret.append(ub64enc(digest).decode("ascii")) return ret, st def _ex_hash(self, ex: Exception, ap: str) -> None: eno = getattr(ex, "errno", 0) if eno in E_FS_MEH: return self.log("hashing failed; %r @ %r" % (ex, ap)) if eno not in E_FS_CRIT: return self.log("hashing failed; %r @ %r\n%s" % (ex, ap, min_ex()), 3) t = "hashing failed; %r @ %r\n%s\nWARNING: This MAY indicate a serious issue with your harddisk or filesystem! Please investigate %sOS-logs\n" t2 = "" if ANYWIN or MACOS else "dmesg and " return self.log(t % (ex, ap, min_ex(), t2), 1) def _new_upload(self, job: dict[str, Any], vfs: VFS, depth: int) -> dict[str, str]: pdir = djoin(job["ptop"], job["prel"]) if not job["size"]: try: inf = bos.stat(djoin(pdir, job["name"])) if stat.S_ISREG(inf.st_mode): job["lmod"] = inf.st_size return {} except: pass vf = self.flags[job["ptop"]] xbu = vf.get("xbu") ap_chk = djoin(pdir, job["name"]) vp_chk = djoin(job["vtop"], job["prel"], job["name"]) if xbu: hr = runhook( self.log, None, self, "xbu.up2k", xbu, ap_chk, vp_chk, job["host"], job["user"], self.vfs.get_perms(vp_chk, job["user"]), job["lmod"], job["size"], job["addr"], job["t0"], None, ) t = hr.get("rejectmsg") or "" if t or hr.get("rc") != 0: if not t: t = "upload blocked by xbu server config: %r" % (vp_chk,) self.log(t, 1) raise Pebkac(403, t) if hr.get("reloc"): x = pathmod(self.vfs, ap_chk, vp_chk, hr["reloc"]) if x: ud1 = (vfs.vpath, job["prel"], job["name"]) pdir, _, job["name"], (vfs, rem) = x job["vcfg"] = vf = vfs.flags job["ptop"] = vfs.realpath job["vtop"] = vfs.vpath job["prel"] = rem job["name"] = sanitize_fn(job["name"]) ud2 = (vfs.vpath, job["prel"], job["name"]) if ud1 != ud2: self.log("xbu reloc2:%d..." % (depth,), 6) return self._handle_json(job, depth + 1) job["name"] = self._untaken(pdir, job, job["t0"]) self.registry[job["ptop"]][job["wark"]] = job tnam = job["name"] + ".PARTIAL" if self.args.dotpart: tnam = "." + tnam if self.args.nw: job["tnam"] = tnam if not job["hash"]: del self.registry[job["ptop"]][job["wark"]] return {} if self.args.plain_ip: dip = job["addr"].replace(":", ".") else: dip = self.hub.iphash.s(job["addr"]) f, job["tnam"] = ren_open( tnam, "wb", fdir=pdir, suffix="-%.6f-%s" % (job["t0"], dip), vf=vf, ) try: abspath = djoin(pdir, job["tnam"]) sprs = job["sprs"] sz = job["size"] relabel = False if ( ANYWIN and sprs and self.args.sparse and self.args.sparse * 1024 * 1024 <= sz ): try: sp.check_call(["fsutil", "sparse", "setflag", abspath]) except: self.log("could not sparse %r" % (abspath,), 3) relabel = True sprs = False if not ANYWIN and sprs and sz > 1024 * 1024: fs, mnt = self.fstab.get(pdir) if fs == "ok": pass elif "nosparse" in vf: t = "volflag 'nosparse' is preventing creation of sparse files for uploads to [%s]" self.log(t % (job["ptop"],)) relabel = True sprs = False elif "sparse" in vf: t = "volflag 'sparse' is forcing creation of sparse files for uploads to [%s]" self.log(t % (job["ptop"],)) relabel = True else: relabel = True f.seek(1024 * 1024 - 1) f.write(b"e") f.flush() try: nblk = bos.stat(abspath).st_blocks sprs = nblk < 2048 except: sprs = False if relabel: t = "sparse files {} on {} filesystem at {}" nv = "ok" if sprs else "ng" self.log(t.format(nv, self.fstab.get(pdir), pdir)) self.fstab.relabel(pdir, nv) job["sprs"] = sprs if job["hash"] and sprs: f.seek(sz - 1) f.write(b"e") finally: f.close() if not job["hash"]: self._finish_upload(job["ptop"], job["wark"]) return {} def _snapshot(self) -> None: slp = self.args.snap_wri if not slp or self.args.no_snap: return while True: time.sleep(slp) if self.pp: slp = 5 else: slp = self.args.snap_wri self.do_snapshot() def do_snapshot(self) -> None: self.fika = "u" with self.mutex, self.reg_mutex: for k, reg in self.registry.items(): self._snap_reg(k, reg) def _snap_reg(self, ptop: str, reg: dict[str, dict[str, Any]]) -> None: now = time.time() histpath = self.vfs.dbpaths.get(ptop) if not histpath: return idrop = self.args.snap_drop * 60 rm = [x for x in reg.values() if x["need"] and now - x["poke"] >= idrop] if self.args.nw: lost = [] else: lost = [ x for x in reg.values() if x["need"] and not bos.path.exists(djoin(x["ptop"], x["prel"], x["name"])) ] if rm or lost: t = "dropping {} abandoned, {} deleted uploads in {}" t = t.format(len(rm), len(lost), ptop) rm.extend(lost) vis = [self._vis_job_progress(x) for x in rm] self.log("\n".join([t] + vis)) for job in rm: del reg[job["wark"]] rsv_cleared = False try: # remove the filename reservation path = djoin(job["ptop"], job["prel"], job["name"]) if bos.path.getsize(path) == 0: bos.unlink(path) rsv_cleared = True except: pass try: if len(job["hash"]) == len(job["need"]) or ( rsv_cleared and "rm_partial" in self.flags[job["ptop"]] ): # PARTIAL is empty (hash==need) or --rm-partial, so delete that too path = djoin(job["ptop"], job["prel"], job["tnam"]) bos.unlink(path) except: pass if self.args.nw or self.args.no_snap: return path = os.path.join(histpath, "up2k.snap") if not reg: if ptop not in self.snap_prev or self.snap_prev[ptop] is not None: self.snap_prev[ptop] = None if bos.path.exists(path): bos.unlink(path) return newest = float( max(x["t0"] if "done" in x else x["poke"] for _, x in reg.items()) if reg else 0 ) etag = (len(reg), newest) if etag == self.snap_prev.get(ptop): return if bos.makedirs(histpath): hidedir(histpath) path2 = "{}.{}".format(path, os.getpid()) body = {"droppable": self.droppable[ptop], "registry": reg} j = json.dumps(body, sort_keys=True, separators=(",\n", ": ")).encode("utf-8") # j = re.sub(r'"(need|hash)": \[\],\n', "", j) # bytes=slow, utf8=hungry j = j.replace(b'"need": [],\n', b"") # surprisingly optimal j = j.replace(b'"hash": [],\n', b"") with gzip.GzipFile(path2, "wb") as f: f.write(j) atomic_move(self.log, path2, path, VF_CAREFUL) self.log("snap: %s |%d| %.2fs" % (path, len(reg), time.time() - now)) self.snap_prev[ptop] = etag def _tagger(self) -> None: with self.mutex: self.n_tagq += 1 assert self.mtag while True: with self.mutex: self.n_tagq -= 1 ptop, wark, rd, fn, sz, ip, at = self.tagq.get() if "e2t" not in self.flags[ptop]: continue # self.log("\n " + repr([ptop, rd, fn])) abspath = djoin(ptop, rd, fn) try: tags = self.mtag.get(abspath, self.flags[ptop]) if sz else {} ntags1 = len(tags) parsers = self._get_parsers(ptop, tags, abspath) if self.args.mtag_vv: t = "parsers({}): {}\n{} {} tags: {}".format( ptop, list(parsers.keys()), ntags1, self.mtag.backend, tags ) self.log(t) if parsers: tags["up_ip"] = ip tags["up_at"] = at tags.update(self.mtag.get_bin(parsers, abspath, tags)) except Exception as ex: self._log_tag_err("", abspath, ex) continue with self.mutex: cur = self.cur[ptop] if not cur: self.log("no cursor to write tags with??", c=1) continue # TODO is undef if vol 404 on startup entags = self.entags.get(ptop) if not entags: self.log("no entags okay.jpg", c=3) continue self._tag_file(cur, entags, wark, abspath, tags) cur.connection.commit() self.log("tagged %r (%d+%d)" % (abspath, ntags1, len(tags) - ntags1)) def _hasher(self) -> None: with self.hashq_mutex: self.n_hashq += 1 while True: with self.hashq_mutex: self.n_hashq -= 1 # self.log("hashq {}".format(self.n_hashq)) task = self.hashq.get() if len(task) != 9: raise Exception("invalid hash task") try: if not self._hash_t(task) and self.stop: return except Exception as ex: self.log("failed to hash %r: %s" % (task, ex), 1) def _hash_t( self, task: tuple[str, str, dict[str, Any], str, str, str, float, str, bool] ) -> bool: ptop, vtop, flags, rd, fn, ip, at, usr, skip_xau = task # self.log("hashq {} pop {}/{}/{}".format(self.n_hashq, ptop, rd, fn)) with self.mutex, self.reg_mutex: if not self.register_vpath(ptop, flags): return True abspath = djoin(ptop, rd, fn) self.log("hashing %r" % (abspath,)) inf = bos.stat(abspath) if not inf.st_size: wark = up2k_wark_from_metadata( self.salt, inf.st_size, int(inf.st_mtime), rd, fn ) else: hashes, _ = self._hashlist_from_file(abspath) if not hashes: return False wark = up2k_wark_from_hashlist(self.salt, inf.st_size, hashes) with self.mutex, self.reg_mutex: self.idx_wark( self.flags[ptop], rd, fn, inf.st_mtime, inf.st_size, ptop, vtop, wark, wark, "", usr, ip, at, skip_xau, ) if at and time.time() - at > 30: with self.rescan_cond: self.rescan_cond.notify_all() if self.fx_backlog: self.do_fx_backlog() return True def hash_file( self, ptop: str, vtop: str, flags: dict[str, Any], rd: str, fn: str, ip: str, at: float, usr: str, skip_xau: bool = False, ) -> None: if "e2d" not in flags: return if self.n_hashq > 1024: t = "%d files in hashq; taking a nap" self.log(t % (self.n_hashq,), 6) for _ in range(self.n_hashq // 1024): time.sleep(0.1) if self.n_hashq < 1024: break zt = (ptop, vtop, flags, rd, fn, ip, at, usr, skip_xau) with self.hashq_mutex: self.hashq.put(zt) self.n_hashq += 1 def do_fx_backlog(self): with self.mutex, self.reg_mutex: todo = self.fx_backlog self.fx_backlog = [] for act, hr, req_vp in todo: self.hook_fx(act, hr, req_vp) def hook_fx(self, act: str, hr: dict[str, str], req_vp: str) -> None: bad = [k for k in hr if k != "vp"] if bad: t = "got unsupported key in %s from hook: %s" raise Exception(t % (act, bad)) for fvp in hr.get("vp") or []: # expect vpath including filename; either absolute # or relative to the client's vpath (request url) if fvp.startswith("/"): fvp, fn = vsplit(fvp[1:]) fvp = "/" + fvp else: fvp, fn = vsplit(fvp) x = pathmod(self.vfs, "", req_vp, {"vp": fvp, "fn": fn}) if not x: t = "hook_fx(%s): failed to resolve %r based on %r" self.log(t % (act, fvp, req_vp)) continue ap, rd, fn, (vn, rem) = x vp = vjoin(rd, fn) if not vp: raise Exception("hook_fx: blank vp from pathmod") if act == "idx": rd = rd[len(vn.vpath) :].strip("/") self.hash_file( vn.realpath, vn.vpath, vn.flags, rd, fn, "", time.time(), "", True ) if act == "del": self._handle_rm(LEELOO_DALLAS, "", vp, [], False, False) def shutdown(self) -> None: self.stop = True self.fika = "f" if self.mth: self.mth.stop = True # in case we're killed early for x in list(self.spools): self._unspool(x) if not self.args.no_snap: self.log("writing snapshot") self.do_snapshot() t0 = time.time() while self.pp: time.sleep(0.1) if time.time() - t0 >= 1: break # if there is time for x in list(self.spools): self._unspool(x) for cur in self.cur.values(): db = cur.connection try: db.interrupt() except: pass cur.close() db.close() if self.mem_cur: db = self.mem_cur.connection self.mem_cur.close() db.close() self.registry = {} def up2k_chunksize(filesize: int) -> int: chunksize = 1024 * 1024 stepsize = 512 * 1024 while True: for mul in [1, 2]: nchunks = math.ceil(filesize * 1.0 / chunksize) if nchunks <= 256 or (chunksize >= 32 * 1024 * 1024 and nchunks <= 4096): return chunksize chunksize += stepsize stepsize *= mul def up2k_wark_from_hashlist(salt: str, filesize: int, hashes: list[str]) -> str: values = [salt, str(filesize)] + hashes vstr = "\n".join(values) wark = hashlib.sha512(vstr.encode("utf-8")).digest()[:33] return ub64enc(wark).decode("ascii") def up2k_wark_from_metadata(salt: str, sz: int, lastmod: int, rd: str, fn: str) -> str: ret = sfsenc("%s\n%d\n%d\n%s\n%s" % (salt, lastmod, sz, rd, fn)) ret = ub64enc(hashlib.sha512(ret).digest()) return ("#%s" % (ret.decode("ascii"),))[:44]
--- +++ @@ -126,6 +126,7 @@ class Mpqe(object): + """pending files to tag-scan""" def __init__( self, @@ -274,6 +275,7 @@ self.reloading = False def _reload(self, rescan_all_vols: bool) -> None: + """mutex(main) me""" self.log("reload #{} scheduled".format(self.gid + 1)) all_vols = self.asrv.vfs.all_vols @@ -531,6 +533,7 @@ def _rescan( self, all_vols: dict[str, VFS], scan_vols: list[str], wait: bool, fscan: bool ) -> str: + """mutex(main) me""" if not wait and self.pp: return "cannot initiate; scan is already in progress" @@ -1127,6 +1130,7 @@ def register_vpath( self, ptop: str, flags: dict[str, Any] ) -> Optional[tuple["sqlite3.Cursor", str]]: + """mutex(main,reg) me""" histpath = self.vfs.dbpaths.get(ptop) if not histpath: self.log("no dbpath for %r" % (ptop,)) @@ -1925,6 +1929,7 @@ return n_rm + n_rm2 def _verify_integrity(self, vol: VFS) -> int: + """expensive; blocks database access until finished""" ptop = vol.realpath assert self.pp @@ -2085,6 +2090,7 @@ return ret def _drop_caches(self) -> None: + """mutex(main,reg) me""" self.log("dropping caches for a full filesystem scan") for vol in self.vfs.all_vols.values(): reg = self.register_vpath(vol.realpath, vol.flags) @@ -2268,6 +2274,7 @@ params: tuple[Any, ...], flt: int, ) -> tuple[tempfile.SpooledTemporaryFile[bytes], int]: + """mutex(main) me""" n = 0 c2 = cur.connection.cursor() tf = tempfile.SpooledTemporaryFile(1024 * 1024 * 8, "w+b", prefix="cpp-tq-") @@ -2608,6 +2615,7 @@ at: float, un: Optional[str], ) -> int: + """will mutex(main)""" assert self.mtag # !rm try: @@ -2642,6 +2650,7 @@ abspath: str, tags: dict[str, Union[str, float]], ) -> int: + """mutex(main) me""" assert self.mtag # !rm if not bos.path.isfile(abspath): @@ -2832,6 +2841,12 @@ def _create_db( self, db_path: str, cur: Optional["sqlite3.Cursor"] ) -> "sqlite3.Cursor": + """ + collision in 2^(n/2) files where n = bits (6 bits/ch) + 10*6/2 = 2^30 = 1'073'741'824, 24.1mb idx 1<<(3*10) + 12*6/2 = 2^36 = 68'719'476'736, 24.8mb idx + 16*6/2 = 2^48 = 281'474'976'710'656, 26.1mb idx + """ if not cur: cur = self._orz(db_path) @@ -3822,6 +3837,7 @@ self.do_fx_backlog() def _finish_upload(self, ptop: str, wark: str) -> None: + """mutex(main,reg) me""" try: job = self.registry[ptop][wark] pdir = djoin(job["ptop"], job["prel"]) @@ -3896,6 +3912,7 @@ cur.connection.commit() def regdrop(self, ptop: str, wark: str) -> None: + """mutex(main,reg) me""" olds = self.droppable[ptop] if wark: olds.append(wark) @@ -4008,6 +4025,7 @@ at: float, skip_xau: bool = False, ) -> None: + """mutex(main) me""" self.db_rm(db, vflags, rd, fn, sz) if not ip: @@ -4411,6 +4429,7 @@ def _cp_file( self, uname: str, ip: str, svp: str, dvp: str, curs: set["sqlite3.Cursor"] ) -> str: + """mutex(main) me; will mutex(reg)""" svn, srem = self.vfs.get(svp, uname, True, False) svn_dbv, srem_dbv = svn.get_dbv(srem) @@ -4664,6 +4683,7 @@ def _mv_file( self, uname: str, ip: str, svp: str, dvp: str, curs: set["sqlite3.Cursor"] ) -> str: + """mutex(main) me; will mutex(reg)""" svn, srem = self.vfs.get(svp, uname, True, False, True) svn, srem = svn.get_dbv(srem) @@ -4897,6 +4917,7 @@ def _copy_tags( self, csrc: "sqlite3.Cursor", cdst: "sqlite3.Cursor", wark: str ) -> None: + """copy all tags for wark from src-db to dst-db""" w = wark[:16] if cdst.execute("select * from mt where w=? limit 1", (w,)).fetchone(): @@ -4945,6 +4966,10 @@ sz: int, xlink: bool, ) -> bool: + """ + mutex(main,reg) me + forgets file in db, fixes symlinks, does not delete + """ srd, sfn = vsplit(vrem) has_dupes = False self.log("forgetting %r" % (vrem,)) @@ -4999,6 +5024,10 @@ vcur: Optional["sqlite3.Cursor"], xlink: bool, ) -> int: + """ + update symlinks from file at svn/srem to dabs (rename), + or to first remaining full if no dabs (delete) + """ dupes = [] sabs = djoin(sptop, srem) @@ -5676,6 +5705,7 @@ def up2k_wark_from_hashlist(salt: str, filesize: int, hashes: list[str]) -> str: + """server-reproducible file identifier, independent of name or location""" values = [salt, str(filesize)] + hashes vstr = "\n".join(values) @@ -5686,4 +5716,4 @@ def up2k_wark_from_metadata(salt: str, sz: int, lastmod: int, rd: str, fn: str) -> str: ret = sfsenc("%s\n%d\n%d\n%s\n%s" % (salt, lastmod, sz, rd, fn)) ret = ub64enc(hashlib.sha512(ret).digest()) - return ("#%s" % (ret.decode("ascii"),))[:44]+ return ("#%s" % (ret.decode("ascii"),))[:44]
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/up2k.py
Add structured docstrings to improve clarity
#!/usr/bin/env python3 # coding: latin-1 from __future__ import print_function, unicode_literals import re, os, sys, time, shutil, signal, tarfile, hashlib, platform, tempfile, traceback import subprocess as sp """ to edit this file, use HxD or "vim -b" (there is compressed stuff at the end) run me with python 2.7 or 3.3+ to unpack and run copyparty there's zero binaries! just plaintext python scripts all the way down so you can easily unpack the archive and inspect it for shady stuff the archive data is attached after the b"\n# eof\n" archive marker, b"?0" decodes to b"\x00" b"?n" decodes to b"\n" b"?r" decodes to b"\r" b"??" decodes to b"?" """ # set by make-sfx.sh VER = None SIZE = None CKSUM = None STAMP = None PY2 = sys.version_info < (3,) PY37 = sys.version_info > (3, 7) WINDOWS = sys.platform in ["win32", "msys"] sys.dont_write_bytecode = True me = os.path.abspath(os.path.realpath(__file__)) def eprint(*a, **ka): ka["file"] = sys.stderr print(*a, **ka) def msg(*a, **ka): if a: a = ["[SFX]", a[0]] + list(a[1:]) eprint(*a, **ka) # skip 1 def testptn1(): import struct buf = b"" for c in range(256): buf += struct.pack("B", c) yield buf def testptn2(): import struct for a in range(256): if a % 16 == 0: msg(a) for b in range(256): buf = b"" for c in range(256): buf += struct.pack("BBBB", a, b, c, b) yield buf def testptn3(): with open("C:/Users/ed/Downloads/python-3.8.1-amd64.exe", "rb", 512 * 1024) as f: while True: buf = f.read(512 * 1024) if not buf: break yield buf testptn = testptn2 def testchk(cdata): import struct cbuf = b"" mbuf = b"" checked = 0 t0 = time.time() mdata = testptn() while True: if not mbuf: try: mbuf += next(mdata) except: break if not cbuf: try: cbuf += next(cdata) except: expect = mbuf[:8] expect = "".join( " {:02x}".format(x) for x in struct.unpack("B" * len(expect), expect) ) raise Exception( "truncated at {}, expected{}".format(checked + len(cbuf), expect) ) ncmp = min(len(cbuf), len(mbuf)) # msg("checking {:x}H bytes, {:x}H ok so far".format(ncmp, checked)) for n in range(ncmp): checked += 1 if cbuf[n] != mbuf[n]: expect = mbuf[n : n + 8] expect = "".join( " {:02x}".format(x) for x in struct.unpack("B" * len(expect), expect) ) cc = struct.unpack(b"B", cbuf[n : n + 1])[0] raise Exception( "byte {:x}H bad, got {:02x}, expected{}".format(checked, cc, expect) ) cbuf = cbuf[ncmp:] mbuf = mbuf[ncmp:] td = time.time() - t0 txt = "all {}d bytes OK in {:.3f} sec, {:.3f} MB/s".format( checked, td, (checked / (1024 * 1024.0)) / td ) msg(txt) def encode(data, size, cksum, ver, ts): nb = 0 nin = 0 nout = 0 skip = False with open(me, "rb") as fi: unpk = "" src = fi.read().replace(b"\r", b"").rstrip(b"\n").decode("utf-8") for ln in src.split("\n"): if ln.endswith("# skip 0"): skip = False nb = 9 continue if ln.endswith("# skip 1") or skip: skip = True continue if ln.strip().startswith("# fmt: "): continue if ln: nb = 0 else: nb += 1 if nb > 2: continue unpk += ln + "\n" for k, v in [ ["VER", '"' + ver + '"'], ["SIZE", size], ["CKSUM", '"' + cksum + '"'], ["STAMP", ts], ]: v1 = "\n{} = None\n".format(k) v2 = "\n{} = {}\n".format(k, v) unpk = unpk.replace(v1, v2) unpk = unpk.replace("\n ", "\n\t") for _ in range(16): unpk = unpk.replace("\t ", "\t\t") with open("sfx.out", "wb") as f: f.write(unpk.encode("utf-8").rstrip(b"\n") + b"\n\n\n# eof") for buf in data: ebuf = ( buf.replace(b"?", b"??") .replace(b"\x00", b"?0") .replace(b"\r", b"?r") .replace(b"\n", b"?n") ) nin += len(buf) nout += len(ebuf) while ebuf: ep = 4090 while True: a = ebuf.rfind(b"?", 0, ep) if a < 0 or ep - a > 2: break ep = a buf = ebuf[:ep] ebuf = ebuf[ep:] f.write(b"\n#" + buf) f.write(b"\n\n") msg("wrote {:x}H bytes ({:x}H after encode)".format(nin, nout)) def makesfx(tar_src, ver, ts): sz = os.path.getsize(tar_src) cksum = hashfile(tar_src) encode(yieldfile(tar_src), sz, cksum, ver, ts) # skip 0 def u8(gen): try: for s in gen: yield s.decode("utf-8", "ignore") except: yield s for s in gen: yield s def yieldfile(fn): s = 64 * 1024 with open(fn, "rb", s * 4) as f: for block in iter(lambda: f.read(s), b""): yield block def hashfile(fn): h = hashlib.sha1() for block in yieldfile(fn): h.update(block) return h.hexdigest()[:24] def unpack(): name = "pe-copyparty" try: name += "." + str(os.geteuid()) except: pass tag = "v" + str(STAMP) top = tempfile.gettempdir() opj = os.path.join ofe = os.path.exists final = opj(top, name) san = opj(final, "copyparty/up2k.py") for suf in range(0, 9001): withpid = "%s.%d.%s" % (name, os.getpid(), suf) mine = opj(top, withpid) if not ofe(mine): break tar = opj(mine, "tar") try: if tag in os.listdir(final) and ofe(san): msg("found early") return final except: pass sz = 0 os.mkdir(mine) with open(tar, "wb") as f: for buf in get_payload(): sz += len(buf) f.write(buf) ck = hashfile(tar) if ck != CKSUM: t = "\n\nexpected %s (%d byte)\nobtained %s (%d byte)\nsfx corrupt" raise Exception(t % (CKSUM, SIZE, ck, sz)) with tarfile.open(tar, "r:bz2") as tf: # this is safe against traversal # skip 1 # since it will never process user-provided data; # the only possible input is a single tar.bz2 # which gets hardcoded into this script at build stage # skip 0 try: tf.extractall(mine, filter="tar") except TypeError: tf.extractall(mine) os.remove(tar) with open(opj(mine, tag), "wb") as f: f.write(b"h\n") try: if tag in os.listdir(final) and ofe(san): msg("found late") return final except: pass try: if os.path.islink(final): os.remove(final) else: shutil.rmtree(final) except: pass for fn in u8(os.listdir(top)): if fn.startswith(name) and fn != withpid: try: old = opj(top, fn) if time.time() - os.path.getmtime(old) > 86400: shutil.rmtree(old) except: pass try: os.symlink(mine, final) except: try: os.rename(mine, final) return final except: msg("reloc fail,", mine) return mine def get_payload(): with open(me, "rb") as f: buf = f.read().rstrip(b"\r\n") ptn = b"\n# eof\n#" a = buf.find(ptn) if a < 0: raise Exception("could not find archive marker") esc = {b"??": b"?", b"?r": b"\r", b"?n": b"\n", b"?0": b"\x00"} buf = buf[a + len(ptn) :].replace(b"\n#", b"") p = 0 while buf: a = buf.find(b"?", p) if a < 0: yield buf[p:] break elif a == p: yield esc[buf[p : p + 2]] p += 2 else: yield buf[p:a] p = a def confirm(rv): msg() msg("retcode", rv if rv else traceback.format_exc()) if WINDOWS: msg("*** hit enter to exit ***") try: raw_input() if PY2 else input() except: pass sys.exit(rv or 1) def run(tmp, j2, ftp): msg("jinja2:", j2 or "bundled") msg("pyftpd:", ftp or "bundled") msg("sfxdir:", tmp) msg() sys.argv.append("--sfx-tpoke=" + tmp) ld = (("", ""), (j2, "j2"), (ftp, "ftp"), (not PY2, "py2"), (PY37, "py37")) ld = [os.path.join(tmp, b) for a, b in ld if not a] # skip 1 # enable this to dynamically remove type hints at startup, # in case a future python version can use them for performance if sys.version_info < (3, 10) and False: sys.path.insert(0, ld[0]) from strip_hints.a import uh uh(tmp + "/copyparty") # skip 0 if any([re.match(r"^-.*j[0-9]", x) for x in sys.argv]): run_s(ld) else: run_i(ld) def run_i(ld): for x in ld: sys.path.insert(0, x) e = os.environ e["PRTY_NO_IMPRESO"] = "1" from copyparty.__main__ import main as p p() def run_s(ld): # fmt: off c = "import sys,runpy;" + "".join(['sys.path.insert(0,r"' + x.replace("\\", "/") + '");' for x in ld]) + 'runpy.run_module("copyparty",run_name="__main__")' c = [str(x) for x in [sys.executable, "-c", c] + list(sys.argv[1:])] # fmt: on msg("\n", c, "\n") p = sp.Popen(c) def bye(*a): p.send_signal(signal.SIGINT) signal.signal(signal.SIGTERM, bye) p.wait() raise SystemExit(p.returncode) def main(): if "--versionb" in sys.argv: return print(VER) sysver = str(sys.version).replace("\n", "\n" + " " * 18) pktime = time.strftime("%Y-%m-%d, %H:%M:%S", time.gmtime(STAMP)) msg() msg(" this is: copyparty", VER) msg(" packed at:", pktime, "UTC,", STAMP) msg("archive is:", me) msg("python bin:", sys.executable) msg("python ver:", platform.python_implementation(), sysver) msg() arg = "" try: arg = sys.argv[1] except: pass # skip 1 if arg == "--sfx-testgen": return encode(testptn(), 1, "x", "x", 1) if arg == "--sfx-testchk": return testchk(get_payload()) if arg == "--sfx-make": tar, ver, ts = sys.argv[2:] return makesfx(tar, ver, ts) # skip 0 tmp = os.path.realpath(unpack()) try: from jinja2 import __version__ as j2 except: j2 = None try: from pyftpdlib.__init__ import __ver__ as ftp except: ftp = None try: run(tmp, j2, ftp) except SystemExit as ex: c = ex.code if c not in [0, -15]: confirm(ex.code) except KeyboardInterrupt: pass except: confirm(0) if __name__ == "__main__": main() # skip 1 # python sfx.py --sfx-testgen && python test.py --sfx-testchk # c:\Python27\python.exe sfx.py --sfx-testgen && c:\Python27\python.exe test.py --sfx-testchk
--- +++ @@ -51,6 +51,7 @@ def testptn1(): + """test: creates a test-pattern for encode()""" import struct buf = b"" @@ -88,6 +89,7 @@ def testchk(cdata): + """test: verifies that `data` yields testptn""" import struct cbuf = b"" @@ -141,6 +143,7 @@ def encode(data, size, cksum, ver, ts): + """creates a new sfx; `data` should yield bufs to attach""" nb = 0 nin = 0 nout = 0 @@ -246,6 +249,7 @@ def unpack(): + """unpacks the tar yielded by `data`""" name = "pe-copyparty" try: name += "." + str(os.geteuid()) @@ -339,6 +343,7 @@ def get_payload(): + """yields the binary data attached to script""" with open(me, "rb") as f: buf = f.read().rstrip(b"\r\n") @@ -496,4 +501,4 @@ # skip 1 # python sfx.py --sfx-testgen && python test.py --sfx-testchk -# c:\Python27\python.exe sfx.py --sfx-testgen && c:\Python27\python.exe test.py --sfx-testchk+# c:\Python27\python.exe sfx.py --sfx-testgen && c:\Python27\python.exe test.py --sfx-testchk
https://raw.githubusercontent.com/9001/copyparty/HEAD/scripts/sfx.py
Write proper docstrings for these functions
# coding: utf-8 from __future__ import print_function, unicode_literals import argparse import base64 import binascii import codecs import errno import hashlib import hmac import json import logging import math import mimetypes import os import platform import re import select import shutil import signal import socket import stat import struct import subprocess as sp # nosec import sys import threading import time import traceback from collections import Counter from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network from queue import Queue try: from zlib_ng import gzip_ng as gzip from zlib_ng import zlib_ng as zlib sys.modules["gzip"] = gzip # sys.modules["zlib"] = zlib # `- somehow makes tarfile 3% slower with default malloc, and barely faster with mimalloc except: import gzip import zlib from .__init__ import ( ANYWIN, EXE, GRAAL, MACOS, PY2, PY36, TYPE_CHECKING, VT100, WINDOWS, EnvParams, unicode, ) from .__version__ import S_BUILD_DT, S_VERSION def noop(*a, **ka): pass try: from datetime import datetime, timezone UTC = timezone.utc except: from datetime import datetime, timedelta, tzinfo TD_ZERO = timedelta(0) class _UTC(tzinfo): def utcoffset(self, dt): return TD_ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return TD_ZERO UTC = _UTC() if PY2: range = xrange # type: ignore from .stolen import surrogateescape surrogateescape.register_surrogateescape() if sys.version_info >= (3, 7) or ( PY36 and platform.python_implementation() == "CPython" ): ODict = dict else: from collections import OrderedDict as ODict def _ens(want: str) -> tuple[int, ...]: ret: list[int] = [] for v in want.split(): try: ret.append(getattr(errno, v)) except: pass return tuple(ret) # WSAECONNRESET - foribly closed by remote # WSAENOTSOCK - no longer a socket # EUNATCH - can't assign requested address (wifi down) E_SCK = _ens("ENOTCONN EUNATCH EBADF WSAENOTSOCK WSAECONNRESET") E_SCK_WR = _ens("EPIPE ESHUTDOWN EBADFD") E_ADDR_NOT_AVAIL = _ens("EADDRNOTAVAIL WSAEADDRNOTAVAIL") E_ADDR_IN_USE = _ens("EADDRINUSE WSAEADDRINUSE") E_ACCESS = _ens("EACCES WSAEACCES") E_UNREACH = _ens("EHOSTUNREACH WSAEHOSTUNREACH ENETUNREACH WSAENETUNREACH") E_FS_MEH = _ens("EPERM EACCES ENOENT ENOTCAPABLE") E_FS_CRIT = _ens("EIO EFAULT EUCLEAN ENOTBLK") IP6ALL = "0:0:0:0:0:0:0:0" IP6_LL = ("fe8", "fe9", "fea", "feb") IP64_LL = ("fe8", "fe9", "fea", "feb", "169.254") UC_CDISP = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._" BC_CDISP = UC_CDISP.encode("ascii") UC_CDISP_SET = set(UC_CDISP) BC_CDISP_SET = set(BC_CDISP) try: import fcntl HAVE_FCNTL = True HAVE_FICLONE = hasattr(fcntl, "FICLONE") except: HAVE_FCNTL = False HAVE_FICLONE = False try: import termios except: pass try: if os.environ.get("PRTY_NO_CTYPES"): raise Exception() import ctypes except: ctypes = None try: wk32 = ctypes.WinDLL(str("kernel32"), use_last_error=True) # type: ignore except: wk32 = None try: if os.environ.get("PRTY_NO_IFADDR"): raise Exception() try: if os.environ.get("PRTY_SYS_ALL") or os.environ.get("PRTY_SYS_IFADDR"): raise ImportError() from .stolen.ifaddr import get_adapters except ImportError: from ifaddr import get_adapters HAVE_IFADDR = True except: HAVE_IFADDR = False def get_adapters(include_unconfigured=False): return [] try: if os.environ.get("PRTY_NO_SQLITE"): raise Exception() HAVE_SQLITE3 = True import sqlite3 assert hasattr(sqlite3, "connect") # graalpy except: HAVE_SQLITE3 = False try: import importlib.util HAVE_ZMQ = bool(importlib.util.find_spec("zmq")) except: HAVE_ZMQ = False try: if os.environ.get("PRTY_NO_PSUTIL"): raise Exception() HAVE_PSUTIL = True import psutil except: HAVE_PSUTIL = False try: if os.environ.get("PRTY_NO_MAGIC") or ( ANYWIN and not os.environ.get("PRTY_FORCE_MAGIC") ): raise Exception() import magic except: pass if os.environ.get("PRTY_MODSPEC"): from inspect import getsourcefile print("PRTY_MODSPEC: ifaddr:", getsourcefile(get_adapters)) if True: # pylint: disable=using-constant-test import types from collections.abc import Callable, Iterable import typing from typing import IO, Any, Generator, Optional, Pattern, Protocol, Union try: from typing import LiteralString except: pass class RootLogger(Protocol): def __call__(self, src: str, msg: str, c: Union[int, str] = 0) -> None: return None class NamedLogger(Protocol): def __call__(self, msg: str, c: Union[int, str] = 0) -> None: return None if TYPE_CHECKING: from .authsrv import VFS from .broker_util import BrokerCli from .up2k import Up2k FAKE_MP = False try: if os.environ.get("PRTY_NO_MP"): raise ImportError() import multiprocessing as mp # import multiprocessing.dummy as mp except ImportError: # support jython mp = None # type: ignore if not PY2: from io import BytesIO else: from StringIO import StringIO as BytesIO # type: ignore try: if os.environ.get("PRTY_NO_IPV6"): raise Exception() socket.inet_pton(socket.AF_INET6, "::1") HAVE_IPV6 = True if GRAAL: try: # --python.PosixModuleBackend=java throws OSError: illegal IP address socket.inet_pton(socket.AF_INET, "127.0.0.1") except: _inet_pton = socket.inet_pton def inet_pton(fam, ip): if fam == socket.AF_INET: return socket.inet_aton(ip) return _inet_pton(fam, ip) socket.inet_pton = inet_pton except: def inet_pton(fam, ip): return socket.inet_aton(ip) socket.inet_pton = inet_pton HAVE_IPV6 = False try: struct.unpack(b">i", b"idgi") spack = struct.pack # type: ignore sunpack = struct.unpack # type: ignore except: def spack(fmt: bytes, *a: Any) -> bytes: return struct.pack(fmt.decode("ascii"), *a) def sunpack(fmt: bytes, a: bytes) -> tuple[Any, ...]: return struct.unpack(fmt.decode("ascii"), a) try: BITNESS = struct.calcsize(b"P") * 8 except: BITNESS = struct.calcsize("P") * 8 CAN_SIGMASK = not (ANYWIN or PY2 or GRAAL) RE_ANSI = re.compile("\033\\[[^mK]*[mK]") RE_HTML_SH = re.compile(r"[<>&$?`\"';]") RE_CTYPE = re.compile(r"^content-type: *([^; ]+)", re.IGNORECASE) RE_CDISP = re.compile(r"^content-disposition: *([^; ]+)", re.IGNORECASE) RE_CDISP_FIELD = re.compile( r'^content-disposition:(?: *|.*; *)name="([^"]+)"', re.IGNORECASE ) RE_CDISP_FILE = re.compile( r'^content-disposition:(?: *|.*; *)filename="(.*)"', re.IGNORECASE ) RE_MEMTOTAL = re.compile("^MemTotal:.* kB") RE_MEMAVAIL = re.compile("^MemAvailable:.* kB") if PY2: def umktrans(s1, s2): return {ord(c1): ord(c2) for c1, c2 in zip(s1, s2)} else: umktrans = str.maketrans FNTL_WIN = umktrans('<>:|?*"\\/', "<>:|?*"\/") VPTL_WIN = umktrans('<>:|?*"\\', "<>:|?*"\") APTL_WIN = umktrans('<>:|?*"/', "<>:|?*"/") FNTL_MAC = VPTL_MAC = APTL_MAC = umktrans(":", ":") FNTL_OS = FNTL_WIN if ANYWIN else FNTL_MAC if MACOS else None VPTL_OS = VPTL_WIN if ANYWIN else VPTL_MAC if MACOS else None APTL_OS = APTL_WIN if ANYWIN else APTL_MAC if MACOS else None BOS_SEP = ("%s" % (os.sep,)).encode("ascii") if WINDOWS and PY2: FS_ENCODING = "utf-8" else: FS_ENCODING = sys.getfilesystemencoding() SYMTIME = PY36 and os.utime in os.supports_follow_symlinks META_NOBOTS = '<meta name="robots" content="noindex, nofollow">\n' # smart enough to understand javascript while also ignoring rel="nofollow" BAD_BOTS = r"Barkrowler|bingbot|BLEXBot|Googlebot|GoogleOther|GPTBot|PetalBot|SeekportBot|SemrushBot|YandexBot" FFMPEG_URL = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z" URL_PRJ = "https://github.com/9001/copyparty" URL_BUG = URL_PRJ + "/issues/new?labels=bug&template=bug_report.md" HTTPCODE = { 200: "OK", 201: "Created", 202: "Accepted", 204: "No Content", 206: "Partial Content", 207: "Multi-Status", 301: "Moved Permanently", 302: "Found", 304: "Not Modified", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 411: "Length Required", 412: "Precondition Failed", 413: "Payload Too Large", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 422: "Unprocessable Entity", 423: "Locked", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 503: "Service Unavailable", 999: "MissingNo", } IMPLICATIONS = [ ["e2dsa", "e2ds"], ["e2ds", "e2d"], ["e2tsr", "e2ts"], ["e2ts", "e2t"], ["e2t", "e2d"], ["e2vu", "e2v"], ["e2vp", "e2v"], ["e2v", "e2d"], ["hardlink_only", "hardlink"], ["hardlink", "dedup"], ["tftpvv", "tftpv"], ["nodupem", "nodupe"], ["no_dupe_m", "no_dupe"], ["nohtml", "noscript"], ["sftpvv", "sftpv"], ["smbw", "smb"], ["smb1", "smb"], ["smbvvv", "smbvv"], ["smbvv", "smbv"], ["smbv", "smb"], ["zv", "zmv"], ["zv", "zsv"], ["z", "zm"], ["z", "zs"], ["zmvv", "zmv"], ["zm4", "zm"], ["zm6", "zm"], ["zmv", "zm"], ["zms", "zm"], ["zsv", "zs"], ] if ANYWIN: IMPLICATIONS.extend([["z", "zm4"]]) UNPLICATIONS = [["no_dav", "daw"]] DAV_ALLPROP_L = [ "contentclass", "creationdate", "defaultdocument", "displayname", "getcontentlanguage", "getcontentlength", "getcontenttype", "getlastmodified", "href", "iscollection", "ishidden", "isreadonly", "isroot", "isstructureddocument", "lastaccessed", "name", "parentname", "resourcetype", "supportedlock", ] DAV_ALLPROPS = set(DAV_ALLPROP_L) FAVICON_MIMES = { "gif": "image/gif", "png": "image/png", "svg": "image/svg+xml", } MIMES = { "opus": "audio/ogg; codecs=opus", "owa": "audio/webm; codecs=opus", } def _add_mimes() -> set[str]: # `mimetypes` is woefully unpopulated on windows # but will be used as fallback on linux for ln in """text css html csv application json wasm xml pdf rtf zip jar fits wasm image webp jpeg png gif bmp jxl jp2 jxs jxr tiff bpg heic heif avif audio aac ogg wav flac ape amr video webm mp4 mpeg font woff woff2 otf ttf """.splitlines(): k, vs = ln.split(" ", 1) for v in vs.strip().split(): MIMES[v] = "{}/{}".format(k, v) for ln in """text md=plain txt=plain js=javascript application 7z=x-7z-compressed tar=x-tar bz2=x-bzip2 gz=gzip rar=x-rar-compressed zst=zstd xz=x-xz lz=lzip cpio=x-cpio application msi=x-ms-installer cab=vnd.ms-cab-compressed rpm=x-rpm crx=x-chrome-extension application epub=epub+zip mobi=x-mobipocket-ebook lit=x-ms-reader rss=rss+xml atom=atom+xml torrent=x-bittorrent application p7s=pkcs7-signature dcm=dicom shx=vnd.shx shp=vnd.shp dbf=x-dbf gml=gml+xml gpx=gpx+xml amf=x-amf application swf=x-shockwave-flash m3u=vnd.apple.mpegurl db3=vnd.sqlite3 sqlite=vnd.sqlite3 text ass=plain ssa=plain image jpg=jpeg xpm=x-xpixmap psd=vnd.adobe.photoshop jpf=jpx tif=tiff ico=x-icon djvu=vnd.djvu image heics=heic-sequence heifs=heif-sequence hdr=vnd.radiance svg=svg+xml image arw=x-sony-arw cr2=x-canon-cr2 crw=x-canon-crw dcr=x-kodak-dcr dng=x-adobe-dng erf=x-epson-erf image k25=x-kodak-k25 kdc=x-kodak-kdc mrw=x-minolta-mrw nef=x-nikon-nef orf=x-olympus-orf image pef=x-pentax-pef raf=x-fuji-raf raw=x-panasonic-raw sr2=x-sony-sr2 srf=x-sony-srf x3f=x-sigma-x3f audio caf=x-caf mp3=mpeg m4a=mp4 m4b=mp4 m4r=mp4 mid=midi mpc=musepack aif=aiff au=basic qcp=qcelp video mkv=x-matroska mov=quicktime avi=x-msvideo m4v=x-m4v ts=mp2t video asf=x-ms-asf flv=x-flv 3gp=3gpp 3g2=3gpp2 rmvb=vnd.rn-realmedia-vbr font ttc=collection """.splitlines(): k, ems = ln.split(" ", 1) for em in ems.strip().split(): ext, mime = em.split("=") MIMES[ext] = "{}/{}".format(k, mime) ptn = re.compile("html|script|tension|wasm|xml") return {x for x in MIMES.values() if not ptn.search(x)} SAFE_MIMES = _add_mimes() EXTS: dict[str, str] = {v: k for k, v in MIMES.items()} EXTS["vnd.mozilla.apng"] = "png" MAGIC_MAP = {"jpeg": "jpg"} DEF_EXP = "self.ip self.ua self.uname self.host cfg.name cfg.logout vf.scan vf.thsize hdr.cf-ipcountry srv.itime srv.htime" DEF_MTE = ".files,circle,album,.tn,artist,title,tdate,.bpm,key,.dur,.q,.vq,.aq,vc,ac,fmt,res,.fps,ahash,vhash" DEF_MTH = "tdate,.vq,.aq,vc,ac,fmt,res,.fps" REKOBO_KEY = { v: ln.split(" ", 1)[0] for ln in """ 1B 6d B 2B 7d Gb F# 3B 8d Db C# 4B 9d Ab G# 5B 10d Eb D# 6B 11d Bb A# 7B 12d F 8B 1d C 9B 2d G 10B 3d D 11B 4d A 12B 5d E 1A 6m Abm G#m 2A 7m Ebm D#m 3A 8m Bbm A#m 4A 9m Fm 5A 10m Cm 6A 11m Gm 7A 12m Dm 8A 1m Am 9A 2m Em 10A 3m Bm 11A 4m Gbm F#m 12A 5m Dbm C#m """.strip().split( "\n" ) for v in ln.strip().split(" ")[1:] if v } REKOBO_LKEY = {k.lower(): v for k, v in REKOBO_KEY.items()} _exestr = "python3 python ffmpeg ffprobe cfssl cfssljson cfssl-certinfo" CMD_EXEB = set(_exestr.encode("utf-8").split()) CMD_EXES = set(_exestr.split()) # mostly from https://github.com/github/gitignore/blob/main/Global/macOS.gitignore APPLESAN_TXT = r"/(__MACOS|Icon\r\r)|/\.(_|DS_Store|AppleDouble|LSOverride|DocumentRevisions-|fseventsd|Spotlight-|TemporaryItems|Trashes|VolumeIcon\.icns|com\.apple\.timemachine\.donotpresent|AppleDB|AppleDesktop|apdisk)" APPLESAN_RE = re.compile(APPLESAN_TXT) HUMANSIZE_UNITS = ("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB") UNHUMANIZE_UNITS = { "b": 1, "k": 1024, "m": 1024 * 1024, "g": 1024 * 1024 * 1024, "t": 1024 * 1024 * 1024 * 1024, "p": 1024 * 1024 * 1024 * 1024 * 1024, "e": 1024 * 1024 * 1024 * 1024 * 1024 * 1024, } VF_CAREFUL = {"mv_re_t": 5, "rm_re_t": 5, "mv_re_r": 0.1, "rm_re_r": 0.1} FN_EMB = set([".prologue.html", ".epilogue.html", "readme.md", "preadme.md"]) def read_ram() -> tuple[float, float]: # NOTE: apparently no need to consider /sys/fs/cgroup/memory.max # (cgroups2) since the limit is synced to /proc/meminfo a = b = 0 try: with open("/proc/meminfo", "rb", 0x10000) as f: zsl = f.read(0x10000).decode("ascii", "replace").split("\n") p = RE_MEMTOTAL zs = next((x for x in zsl if p.match(x))) a = int((int(zs.split()[1]) / 0x100000) * 100) / 100 p = RE_MEMAVAIL zs = next((x for x in zsl if p.match(x))) b = int((int(zs.split()[1]) / 0x100000) * 100) / 100 except: pass return a, b RAM_TOTAL, RAM_AVAIL = read_ram() pybin = sys.executable or "" if EXE: pybin = "" for zsg in "python3 python".split(): try: if ANYWIN: zsg += ".exe" zsg = shutil.which(zsg) if zsg: pybin = zsg break except: pass def py_desc() -> str: interp = platform.python_implementation() py_ver = ".".join([str(x) for x in sys.version_info]) ofs = py_ver.find(".final.") if ofs > 0: py_ver = py_ver[:ofs] if "free-threading" in sys.version: py_ver += "t" host_os = platform.system() compiler = platform.python_compiler().split("http")[0] m = re.search(r"([0-9]+\.[0-9\.]+)", platform.version()) os_ver = m.group(1) if m else "" return "{:>9} v{} on {}{} {} [{}]".format( interp, py_ver, host_os, BITNESS, os_ver, compiler ) def expat_ver() -> str: try: import pyexpat return ".".join([str(x) for x in pyexpat.version_info]) except: return "?" def _sqlite_ver() -> str: assert sqlite3 # type: ignore # !rm try: co = sqlite3.connect(":memory:") cur = co.cursor() try: vs = cur.execute("select * from pragma_compile_options").fetchall() except: vs = cur.execute("pragma compile_options").fetchall() v = next(x[0].split("=")[1] for x in vs if x[0].startswith("THREADSAFE=")) cur.close() co.close() except: v = "W" return "{}*{}".format(sqlite3.sqlite_version, v) try: SQLITE_VER = _sqlite_ver() except: SQLITE_VER = "(None)" try: from jinja2 import __version__ as JINJA_VER except: JINJA_VER = "(None)" try: if os.environ.get("PRTY_NO_PYFTPD"): raise Exception() from pyftpdlib.__init__ import __ver__ as PYFTPD_VER except: PYFTPD_VER = "(None)" try: if os.environ.get("PRTY_NO_PARTFTPY"): raise Exception() from partftpy.__init__ import __version__ as PARTFTPY_VER except: PARTFTPY_VER = "(None)" try: if os.environ.get("PRTY_NO_PARAMIKO"): raise Exception() from paramiko import __version__ as MIKO_VER except: MIKO_VER = "(None)" PY_DESC = py_desc() VERSIONS = "copyparty v{} ({})\n{}\n sqlite {} | jinja {} | pyftpd {} | tftp {} | miko {}".format( S_VERSION, S_BUILD_DT, PY_DESC, SQLITE_VER, JINJA_VER, PYFTPD_VER, PARTFTPY_VER, MIKO_VER, ) try: _b64_enc_tl = bytes.maketrans(b"+/", b"-_") _b64_dec_tl = bytes.maketrans(b"-_", b"+/") def ub64enc(bs: bytes) -> bytes: x = binascii.b2a_base64(bs, newline=False) return x.translate(_b64_enc_tl) def ub64dec(bs: bytes) -> bytes: bs = bs.translate(_b64_dec_tl) return binascii.a2b_base64(bs) def b64enc(bs: bytes) -> bytes: return binascii.b2a_base64(bs, newline=False) def b64dec(bs: bytes) -> bytes: return binascii.a2b_base64(bs) zb = b">>>????" zb2 = base64.urlsafe_b64encode(zb) if zb2 != ub64enc(zb) or zb != ub64dec(zb2): raise Exception("bad smoke") except Exception as ex: ub64enc = base64.urlsafe_b64encode # type: ignore ub64dec = base64.urlsafe_b64decode # type: ignore b64enc = base64.b64encode # type: ignore b64dec = base64.b64decode # type: ignore if PY36: print("using fallback base64 codec due to %r" % (ex,)) class NotUTF8(Exception): pass def read_utf8(log: Optional["NamedLogger"], ap: Union[str, bytes], strict: bool) -> str: with open(ap, "rb") as f: buf = f.read() if buf.startswith(b"\xef\xbb\xbf"): buf = buf[3:] try: return buf.decode("utf-8", "strict") except UnicodeDecodeError as ex: eo = ex.start eb = buf[eo : eo + 1] if not strict: t = "WARNING: The file [%s] is not using the UTF-8 character encoding; some characters in the file will be skipped/ignored. The first unreadable character was byte %r at offset %d. Please convert this file to UTF-8 by opening the file in your text-editor and saving it as UTF-8." t = t % (ap, eb, eo) if log: log(t, 3) else: print(t) return buf.decode("utf-8", "replace") t = "ERROR: The file [%s] is not using the UTF-8 character encoding, and cannot be loaded. The first unreadable character was byte %r at offset %d. Please convert this file to UTF-8 by opening the file in your text-editor and saving it as UTF-8." t = t % (ap, eb, eo) if log: log(t, 3) else: print(t) raise NotUTF8(t) class Daemon(threading.Thread): def __init__( self, target: Any, name: Optional[str] = None, a: Optional[Iterable[Any]] = None, r: bool = True, ka: Optional[dict[Any, Any]] = None, ) -> None: threading.Thread.__init__(self, name=name) self.a = a or () self.ka = ka or {} self.fun = target self.daemon = True if r: self.start() def run(self): if CAN_SIGMASK: signal.pthread_sigmask( signal.SIG_BLOCK, [signal.SIGINT, signal.SIGTERM, signal.SIGUSR1] ) self.fun(*self.a, **self.ka) class Netdev(object): def __init__(self, ip: str, idx: int, name: str, desc: str): self.ip = ip self.idx = idx self.name = name self.desc = desc def __str__(self): return "{}-{}{}".format(self.idx, self.name, self.desc) def __repr__(self): return "'{}-{}'".format(self.idx, self.name) def __lt__(self, rhs): return str(self) < str(rhs) def __eq__(self, rhs): return str(self) == str(rhs) class Cooldown(object): def __init__(self, maxage: float) -> None: self.maxage = maxage self.mutex = threading.Lock() self.hist: dict[str, float] = {} self.oldest = 0.0 def poke(self, key: str) -> bool: with self.mutex: now = time.time() ret = False pv: float = self.hist.get(key, 0) if now - pv > self.maxage: self.hist[key] = now ret = True if self.oldest - now > self.maxage * 2: self.hist = { k: v for k, v in self.hist.items() if now - v < self.maxage } self.oldest = sorted(self.hist.values())[0] return ret class HLog(logging.Handler): def __init__(self, log_func: "RootLogger") -> None: logging.Handler.__init__(self) self.log_func = log_func self.ptn_ftp = re.compile(r"^([0-9a-f:\.]+:[0-9]{1,5})-\[") self.ptn_smb_ign = re.compile(r"^(Callback added|Config file parsed)") def __repr__(self) -> str: level = logging.getLevelName(self.level) return "<%s cpp(%s)>" % (self.__class__.__name__, level) def flush(self) -> None: pass def emit(self, record: logging.LogRecord) -> None: msg = self.format(record) lv = record.levelno if lv < logging.INFO: c = 6 elif lv < logging.WARNING: c = 0 elif lv < logging.ERROR: c = 3 else: c = 1 if record.name == "pyftpdlib": m = self.ptn_ftp.match(msg) if m: ip = m.group(1) msg = msg[len(ip) + 1 :] if ip.startswith("::ffff:"): record.name = ip[7:] else: record.name = ip elif record.name.startswith("impacket"): if self.ptn_smb_ign.match(msg): return elif record.name.startswith("partftpy."): record.name = record.name[9:] self.log_func(record.name[-21:], msg, c) class NetMap(object): def __init__( self, ips: list[str], cidrs: list[str], keep_lo=False, strict_cidr=False, defer_mutex=False, ) -> None: # fails multiprocessing; defer assignment self.mutex: Optional[threading.Lock] = None if defer_mutex else threading.Lock() if "::" in ips: ips = [x for x in ips if x != "::"] + list( [x.split("/")[0] for x in cidrs if ":" in x] ) ips.append("0.0.0.0") if "0.0.0.0" in ips: ips = [x for x in ips if x != "0.0.0.0"] + list( [x.split("/")[0] for x in cidrs if ":" not in x] ) if not keep_lo: ips = [x for x in ips if x not in ("::1", "127.0.0.1")] ips = find_prefix(ips, cidrs) self.cache: dict[str, str] = {} self.b2sip: dict[bytes, str] = {} self.b2net: dict[bytes, Union[IPv4Network, IPv6Network]] = {} self.bip: list[bytes] = [] for ip in ips: v6 = ":" in ip fam = socket.AF_INET6 if v6 else socket.AF_INET bip = socket.inet_pton(fam, ip.split("/")[0]) self.bip.append(bip) self.b2sip[bip] = ip.split("/")[0] self.b2net[bip] = (IPv6Network if v6 else IPv4Network)(ip, strict_cidr) self.bip.sort(reverse=True) def map(self, ip: str) -> str: if ip.startswith("::ffff:"): ip = ip[7:] try: return self.cache[ip] except: # intentionally crash the calling thread if unset: assert self.mutex # type: ignore # !rm with self.mutex: return self._map(ip) def _map(self, ip: str) -> str: v6 = ":" in ip ci = IPv6Address(ip) if v6 else IPv4Address(ip) bip = next((x for x in self.bip if ci in self.b2net[x]), None) ret = self.b2sip[bip] if bip else "" if len(self.cache) > 9000: self.cache = {} self.cache[ip] = ret return ret class UnrecvEOF(OSError): pass class _Unrecv(object): def __init__(self, s: socket.socket, log: Optional["NamedLogger"]) -> None: self.s = s self.log = log self.buf: bytes = b"" self.nb = 0 self.te = 0 def recv(self, nbytes: int, spins: int = 1) -> bytes: if self.buf: ret = self.buf[:nbytes] self.buf = self.buf[nbytes:] self.nb += len(ret) return ret while True: try: ret = self.s.recv(nbytes) break except socket.timeout: spins -= 1 if spins <= 0: ret = b"" break continue except: ret = b"" break if not ret: raise UnrecvEOF("client stopped sending data") self.nb += len(ret) return ret def recv_ex(self, nbytes: int, raise_on_trunc: bool = True) -> bytes: ret = b"" try: while nbytes > len(ret): ret += self.recv(nbytes - len(ret)) except OSError: t = "client stopped sending data; expected at least %d more bytes" if not ret: t = t % (nbytes,) else: t += ", only got %d" t = t % (nbytes, len(ret)) if len(ret) <= 16: t += "; %r" % (ret,) if raise_on_trunc: raise UnrecvEOF(5, t) elif self.log: self.log(t, 3) return ret def unrecv(self, buf: bytes) -> None: self.buf = buf + self.buf self.nb -= len(buf) # !rm.yes> class _LUnrecv(object): def __init__(self, s: socket.socket, log: Optional["NamedLogger"]) -> None: self.s = s self.log = log self.buf = b"" self.nb = 0 def recv(self, nbytes: int, spins: int) -> bytes: if self.buf: ret = self.buf[:nbytes] self.buf = self.buf[nbytes:] t = "\033[0;7mur:pop:\033[0;1;32m {}\n\033[0;7mur:rem:\033[0;1;35m {}\033[0m" print(t.format(ret, self.buf)) self.nb += len(ret) return ret ret = self.s.recv(nbytes) t = "\033[0;7mur:recv\033[0;1;33m {}\033[0m" print(t.format(ret)) if not ret: raise UnrecvEOF("client stopped sending data") self.nb += len(ret) return ret def recv_ex(self, nbytes: int, raise_on_trunc: bool = True) -> bytes: try: ret = self.recv(nbytes, 1) err = False except: ret = b"" err = True while not err and len(ret) < nbytes: try: ret += self.recv(nbytes - len(ret), 1) except OSError: err = True if err: t = "client only sent {} of {} expected bytes".format(len(ret), nbytes) if raise_on_trunc: raise UnrecvEOF(t) elif self.log: self.log(t, 3) return ret def unrecv(self, buf: bytes) -> None: self.buf = buf + self.buf self.nb -= len(buf) t = "\033[0;7mur:push\033[0;1;31m {}\n\033[0;7mur:rem:\033[0;1;35m {}\033[0m" print(t.format(buf, self.buf)) # !rm.no> Unrecv = _Unrecv class CachedSet(object): def __init__(self, maxage: float) -> None: self.c: dict[Any, float] = {} self.maxage = maxage self.oldest = 0.0 def add(self, v: Any) -> None: self.c[v] = time.time() def cln(self) -> None: now = time.time() if now - self.oldest < self.maxage: return c = self.c = {k: v for k, v in self.c.items() if now - v < self.maxage} try: self.oldest = c[min(c, key=c.get)] # type: ignore except: self.oldest = now class CachedDict(object): def __init__(self, maxage: float) -> None: self.c: dict[str, tuple[float, Any]] = {} self.maxage = maxage self.oldest = 0.0 def set(self, k: str, v: Any) -> None: now = time.time() self.c[k] = (now, v) if now - self.oldest < self.maxage: return c = self.c = {k: v for k, v in self.c.items() if now - v[0] < self.maxage} try: self.oldest = min([x[0] for x in c.values()]) except: self.oldest = now def get(self, k: str) -> Optional[tuple[str, Any]]: try: ts, ret = self.c[k] now = time.time() if now - ts > self.maxage: del self.c[k] return None return ret except: return None class FHC(object): class CE(object): def __init__(self, fh: typing.BinaryIO) -> None: self.ts: float = 0 self.fhs = [fh] self.all_fhs = set([fh]) def __init__(self) -> None: self.cache: dict[str, FHC.CE] = {} self.aps: dict[str, int] = {} def close(self, path: str) -> None: try: ce = self.cache[path] except: return for fh in ce.fhs: fh.close() del self.cache[path] del self.aps[path] def clean(self) -> None: if not self.cache: return keep = {} now = time.time() for path, ce in self.cache.items(): if now < ce.ts + 5: keep[path] = ce else: for fh in ce.fhs: fh.close() self.cache = keep def pop(self, path: str) -> typing.BinaryIO: return self.cache[path].fhs.pop() def put(self, path: str, fh: typing.BinaryIO) -> None: if path not in self.aps: self.aps[path] = 0 try: ce = self.cache[path] ce.all_fhs.add(fh) ce.fhs.append(fh) except: ce = self.CE(fh) self.cache[path] = ce ce.ts = time.time() class ProgressPrinter(threading.Thread): def __init__(self, log: "NamedLogger", args: argparse.Namespace) -> None: threading.Thread.__init__(self, name="pp") self.daemon = True self.log = log self.args = args self.msg = "" self.end = False self.n = -1 def run(self) -> None: sigblock() tp = 0 msg = None slp_pr = self.args.scan_pr_r slp_ps = min(slp_pr, self.args.scan_st_r) no_stdout = self.args.q or slp_pr == slp_ps fmt = " {}\033[K\r" if VT100 else " {} $\r" while not self.end: time.sleep(slp_ps) if msg == self.msg or self.end: continue msg = self.msg now = time.time() if msg and now - tp >= slp_pr: tp = now self.log("progress: %r" % (msg,), 6) if no_stdout: continue uprint(fmt.format(msg)) if PY2: sys.stdout.flush() if no_stdout: return if VT100: print("\033[K", end="") elif msg: print("------------------------") sys.stdout.flush() # necessary on win10 even w/ stderr btw class MTHash(object): def __init__(self, cores: int): self.pp: Optional[ProgressPrinter] = None self.f: Optional[typing.BinaryIO] = None self.sz = 0 self.csz = 0 self.stop = False self.readsz = 1024 * 1024 * (2 if (RAM_AVAIL or 2) < 1 else 12) self.omutex = threading.Lock() self.imutex = threading.Lock() self.work_q: Queue[int] = Queue() self.done_q: Queue[tuple[int, str, int, int]] = Queue() self.thrs = [] for n in range(cores): t = Daemon(self.worker, "mth-" + str(n)) self.thrs.append(t) def hash( self, f: typing.BinaryIO, fsz: int, chunksz: int, pp: Optional[ProgressPrinter] = None, prefix: str = "", suffix: str = "", ) -> list[tuple[str, int, int]]: with self.omutex: self.f = f self.sz = fsz self.csz = chunksz chunks: dict[int, tuple[str, int, int]] = {} nchunks = int(math.ceil(fsz / chunksz)) for nch in range(nchunks): self.work_q.put(nch) ex: Optional[Exception] = None for nch in range(nchunks): qe = self.done_q.get() try: nch, dig, ofs, csz = qe chunks[nch] = (dig, ofs, csz) except: ex = ex or qe # type: ignore if pp: mb = (fsz - nch * chunksz) // (1024 * 1024) pp.msg = prefix + str(mb) + suffix if ex: raise ex ret = [] for n in range(nchunks): ret.append(chunks[n]) self.f = None self.csz = 0 self.sz = 0 return ret def worker(self) -> None: while True: ofs = self.work_q.get() try: v = self.hash_at(ofs) except Exception as ex: v = ex # type: ignore self.done_q.put(v) def hash_at(self, nch: int) -> tuple[int, str, int, int]: f = self.f ofs = ofs0 = nch * self.csz chunk_sz = chunk_rem = min(self.csz, self.sz - ofs) if self.stop: return nch, "", ofs0, chunk_sz assert f # !rm hashobj = hashlib.sha512() while chunk_rem > 0: with self.imutex: f.seek(ofs) buf = f.read(min(chunk_rem, self.readsz)) if not buf: raise Exception("EOF at " + str(ofs)) hashobj.update(buf) chunk_rem -= len(buf) ofs += len(buf) bdig = hashobj.digest()[:33] udig = ub64enc(bdig).decode("ascii") return nch, udig, ofs0, chunk_sz class HMaccas(object): def __init__(self, keypath: str, retlen: int) -> None: self.retlen = retlen self.cache: dict[bytes, str] = {} try: with open(keypath, "rb") as f: self.key = f.read() if len(self.key) != 64: raise Exception() except: self.key = os.urandom(64) with open(keypath, "wb") as f: f.write(self.key) def b(self, msg: bytes) -> str: try: return self.cache[msg] except: if len(self.cache) > 9000: self.cache = {} zb = hmac.new(self.key, msg, hashlib.sha512).digest() zs = ub64enc(zb)[: self.retlen].decode("ascii") self.cache[msg] = zs return zs def s(self, msg: str) -> str: return self.b(msg.encode("utf-8", "replace")) class Magician(object): def __init__(self) -> None: self.bad_magic = False self.mutex = threading.Lock() self.magic: Optional["magic.Magic"] = None def ext(self, fpath: str) -> str: try: if self.bad_magic: raise Exception() if not self.magic: try: with self.mutex: if not self.magic: self.magic = magic.Magic(uncompress=False, extension=True) except: self.bad_magic = True raise with self.mutex: ret = self.magic.from_file(fpath) except: ret = "?" ret = ret.split("/")[0] ret = MAGIC_MAP.get(ret, ret) if "?" not in ret: return ret mime = magic.from_file(fpath, mime=True) mime = re.split("[; ]", mime, maxsplit=1)[0] try: return EXTS[mime] except: pass mg = mimetypes.guess_extension(mime) if mg: return mg[1:] else: raise Exception() class Garda(object): def __init__(self, cfg: str, uniq: bool = True) -> None: self.uniq = uniq try: a, b, c = cfg.strip().split(",") self.lim = int(a) self.win = int(b) * 60 self.pen = int(c) * 60 except: self.lim = self.win = self.pen = 0 self.ct: dict[str, list[int]] = {} self.prev: dict[str, str] = {} self.last_cln = 0 def cln(self, ip: str) -> None: n = 0 ok = int(time.time() - self.win) for v in self.ct[ip]: if v < ok: n += 1 else: break if n: te = self.ct[ip][n:] if te: self.ct[ip] = te else: del self.ct[ip] try: del self.prev[ip] except: pass def allcln(self) -> None: for k in list(self.ct): self.cln(k) self.last_cln = int(time.time()) def bonk(self, ip: str, prev: str) -> tuple[int, str]: if not self.lim: return 0, ip if ":" in ip: # assume /64 clients; drop 4 groups ip = IPv6Address(ip).exploded[:-20] if prev and self.uniq: if self.prev.get(ip) == prev: return 0, ip self.prev[ip] = prev now = int(time.time()) try: self.ct[ip].append(now) except: self.ct[ip] = [now] if now - self.last_cln > 300: self.allcln() else: self.cln(ip) if len(self.ct[ip]) >= self.lim: return now + self.pen, ip else: return 0, ip if WINDOWS and sys.version_info < (3, 8): _popen = sp.Popen def _spopen(c, *a, **ka): enc = sys.getfilesystemencoding() c = [x.decode(enc, "replace") if hasattr(x, "decode") else x for x in c] return _popen(c, *a, **ka) sp.Popen = _spopen def uprint(msg: str) -> None: try: print(msg, end="") except UnicodeEncodeError: try: print(msg.encode("utf-8", "replace").decode(), end="") except: print(msg.encode("ascii", "replace").decode(), end="") def nuprint(msg: str) -> None: uprint("%s\n" % (msg,)) def dedent(txt: str) -> str: pad = 64 lns = txt.replace("\r", "").split("\n") for ln in lns: zs = ln.lstrip() pad2 = len(ln) - len(zs) if zs and pad > pad2: pad = pad2 return "\n".join([ln[pad:] for ln in lns]) def rice_tid() -> str: tid = threading.current_thread().ident c = sunpack(b"B" * 5, spack(b">Q", tid)[-5:]) return "".join("\033[1;37;48;5;{0}m{0:02x}".format(x) for x in c) + "\033[0m" def trace(*args: Any, **kwargs: Any) -> None: t = time.time() stack = "".join( "\033[36m%s\033[33m%s" % (x[0].split(os.sep)[-1][:-3], x[1]) for x in traceback.extract_stack()[3:-1] ) parts = ["%.6f" % (t,), rice_tid(), stack] if args: parts.append(repr(args)) if kwargs: parts.append(repr(kwargs)) msg = "\033[0m ".join(parts) # _tracebuf.append(msg) nuprint(msg) def alltrace(verbose: bool = True) -> str: threads: dict[str, types.FrameType] = {} names = dict([(t.ident, t.name) for t in threading.enumerate()]) for tid, stack in sys._current_frames().items(): if verbose: name = "%s (%x)" % (names.get(tid), tid) else: name = str(names.get(tid)) threads[name] = stack rret: list[str] = [] bret: list[str] = [] np = -3 if verbose else -2 for name, stack in sorted(threads.items()): ret = ["\n\n# %s" % (name,)] pad = None for fn, lno, name, line in traceback.extract_stack(stack): fn = os.sep.join(fn.split(os.sep)[np:]) ret.append('File: "%s", line %d, in %s' % (fn, lno, name)) if line: ret.append(" " + str(line.strip())) if "self.not_empty.wait()" in line: pad = " " * 4 if pad: bret += [ret[0]] + [pad + x for x in ret[1:]] else: rret.extend(ret) return "\n".join(rret + bret) + "\n" def start_stackmon(arg_str: str, nid: int) -> None: suffix = "-{}".format(nid) if nid else "" fp, f = arg_str.rsplit(",", 1) zi = int(f) Daemon(stackmon, "stackmon" + suffix, (fp, zi, suffix)) def stackmon(fp: str, ival: float, suffix: str) -> None: ctr = 0 fp0 = fp while True: ctr += 1 fp = fp0 time.sleep(ival) st = "{}, {}\n{}".format(ctr, time.time(), alltrace()) buf = st.encode("utf-8", "replace") if fp.endswith(".gz"): # 2459b 2304b 2241b 2202b 2194b 2191b lv3..8 # 0.06s 0.08s 0.11s 0.13s 0.16s 0.19s buf = gzip.compress(buf, compresslevel=6) elif fp.endswith(".xz"): import lzma # 2276b 2216b 2200b 2192b 2168b lv0..4 # 0.04s 0.10s 0.22s 0.41s 0.70s buf = lzma.compress(buf, preset=0) if "%" in fp: dt = datetime.now(UTC) for fs in "YmdHMS": fs = "%" + fs if fs in fp: fp = fp.replace(fs, dt.strftime(fs)) if "/" in fp: try: os.makedirs(fp.rsplit("/", 1)[0]) except: pass with open(fp + suffix, "wb") as f: f.write(buf) def start_log_thrs( logger: Callable[[str, str, int], None], ival: float, nid: int ) -> None: ival = float(ival) tname = lname = "log-thrs" if nid: tname = "logthr-n{}-i{:x}".format(nid, os.getpid()) lname = tname[3:] Daemon(log_thrs, tname, (logger, ival, lname)) def log_thrs(log: Callable[[str, str, int], None], ival: float, name: str) -> None: while True: time.sleep(ival) tv = [x.name for x in threading.enumerate()] tv = [ x.split("-")[0] if x.split("-")[0] in ["httpconn", "thumb", "tagger"] else "listen" if "-listen-" in x else x for x in tv if not x.startswith("pydevd.") ] tv = ["{}\033[36m{}".format(v, k) for k, v in sorted(Counter(tv).items())] log(name, "\033[0m \033[33m".join(tv), 3) def _sigblock(): signal.pthread_sigmask( signal.SIG_BLOCK, [signal.SIGINT, signal.SIGTERM, signal.SIGUSR1] ) sigblock = _sigblock if CAN_SIGMASK else noop def vol_san(vols: list["VFS"], txt: bytes) -> bytes: txt0 = txt for vol in vols: bap = vol.realpath.encode("utf-8") bhp = vol.histpath.encode("utf-8") bvp = vol.vpath.encode("utf-8") bvph = b"$hist(/" + bvp + b")" if bap: txt = txt.replace(bap, bvp) txt = txt.replace(bap.replace(b"\\", b"\\\\"), bvp) if bhp: txt = txt.replace(bhp, bvph) txt = txt.replace(bhp.replace(b"\\", b"\\\\"), bvph) if vol.histpath != vol.dbpath: bdp = vol.dbpath.encode("utf-8") bdph = b"$db(/" + bvp + b")" txt = txt.replace(bdp, bdph) txt = txt.replace(bdp.replace(b"\\", b"\\\\"), bdph) if txt != txt0: txt += b"\r\nNOTE: filepaths sanitized; see serverlog for correct values" return txt def min_ex(max_lines: int = 8, reverse: bool = False) -> str: et, ev, tb = sys.exc_info() stb = traceback.extract_tb(tb) if tb else traceback.extract_stack()[:-1] fmt = "%s:%d <%s>: %s" ex = [fmt % (fp.split(os.sep)[-1], ln, fun, txt) for fp, ln, fun, txt in stb] if et or ev or tb: ex.append("[%s] %s" % (et.__name__ if et else "(anonymous)", ev)) return "\n".join(ex[-max_lines:][:: -1 if reverse else 1]) def ren_open(fname: str, *args: Any, **kwargs: Any) -> tuple[typing.IO[Any], str]: fun = kwargs.pop("fun", open) fdir = kwargs.pop("fdir", None) suffix = kwargs.pop("suffix", None) vf = kwargs.pop("vf", None) fperms = vf and "fperms" in vf if fname == os.devnull: return fun(fname, *args, **kwargs), fname if suffix: ext = fname.split(".")[-1] if len(ext) < 7: suffix += "." + ext orig_name = fname bname = fname ext = "" while True: ofs = bname.rfind(".") if ofs < 0 or ofs < len(bname) - 7: # doesn't look like an extension anymore break ext = bname[ofs:] + ext bname = bname[:ofs] asciified = False b64 = "" while True: f = None try: if fdir: fpath = os.path.join(fdir, fname) else: fpath = fname if suffix and os.path.lexists(fsenc(fpath)): fpath += suffix fname += suffix ext += suffix f = fun(fsenc(fpath), *args, **kwargs) if b64: assert fdir # !rm fp2 = "fn-trunc.%s.txt" % (b64,) fp2 = os.path.join(fdir, fp2) with open(fsenc(fp2), "wb") as f2: f2.write(orig_name.encode("utf-8")) if fperms: set_fperms(f2, vf) if fperms: set_fperms(f, vf) return f, fname except OSError as ex_: ex = ex_ if f: f.close() # EPERM: android13 if ex.errno in (errno.EINVAL, errno.EPERM) and not asciified: asciified = True zsl = [] for zs in (bname, fname): zs = zs.encode("ascii", "replace").decode("ascii") zs = re.sub(r"[^][a-zA-Z0-9(){}.,+=!-]", "_", zs) zsl.append(zs) bname, fname = zsl continue # ENOTSUP: zfs on ubuntu 20.04 if ex.errno not in (errno.ENAMETOOLONG, errno.ENOSR, errno.ENOTSUP) and ( not WINDOWS or ex.errno != errno.EINVAL ): raise if not b64: zs = ("%s\n%s" % (orig_name, suffix)).encode("utf-8", "replace") b64 = ub64enc(hashlib.sha512(zs).digest()[:12]).decode("ascii") badlen = len(fname) while len(fname) >= badlen: if len(bname) < 8: raise ex if len(bname) > len(ext): # drop the last letter of the filename bname = bname[:-1] else: try: # drop the leftmost sub-extension _, ext = ext.split(".", 1) except: # okay do the first letter then ext = "." + ext[2:] fname = "%s~%s%s" % (bname, b64, ext) class MultipartParser(object): def __init__( self, log_func: "NamedLogger", args: argparse.Namespace, sr: Unrecv, http_headers: dict[str, str], ): self.sr = sr self.log = log_func self.args = args self.headers = http_headers try: self.clen = int(http_headers["content-length"]) sr.nb = 0 except: self.clen = 0 self.re_ctype = RE_CTYPE self.re_cdisp = RE_CDISP self.re_cdisp_field = RE_CDISP_FIELD self.re_cdisp_file = RE_CDISP_FILE self.boundary = b"" self.gen: Optional[ Generator[ tuple[str, Optional[str], Generator[bytes, None, None]], None, None ] ] = None def _read_header(self) -> tuple[str, Optional[str]]: for ln in read_header(self.sr, 2, 2592000): self.log(repr(ln)) m = self.re_ctype.match(ln) if m: if m.group(1).lower() == "multipart/mixed": # rfc-7578 overrides rfc-2388 so this is not-impl # (opera >=9 <11.10 is the only thing i've ever seen use it) raise Pebkac( 400, "you can't use that browser to upload multiple files at once", ) continue # the only other header we care about is content-disposition m = self.re_cdisp.match(ln) if not m: continue if m.group(1).lower() != "form-data": raise Pebkac(400, "not form-data: %r" % (ln,)) try: field = self.re_cdisp_field.match(ln).group(1) # type: ignore except: raise Pebkac(400, "missing field name: %r" % (ln,)) try: fn = self.re_cdisp_file.match(ln).group(1) # type: ignore except: # this is not a file upload, we're done return field, None try: is_webkit = "applewebkit" in self.headers["user-agent"].lower() except: is_webkit = False # chromes ignore the spec and makes this real easy if is_webkit: # quotes become %22 but they don't escape the % # so unescaping the quotes could turn messi return field, fn.split('"')[0] # also ez if filename doesn't contain " if not fn.split('"')[0].endswith("\\"): return field, fn.split('"')[0] # this breaks on firefox uploads that contain \" # since firefox escapes " but forgets to escape \ # so it'll truncate after the \ ret = "" esc = False for ch in fn: if esc: esc = False if ch not in ['"', "\\"]: ret += "\\" ret += ch elif ch == "\\": esc = True elif ch == '"': break else: ret += ch return field, ret raise Pebkac(400, "server expected a multipart header but you never sent one") def _read_data(self) -> Generator[bytes, None, None]: blen = len(self.boundary) bufsz = self.args.s_rd_sz while True: try: buf = self.sr.recv(bufsz) except: # abort: client disconnected raise Pebkac(400, "client d/c during multipart post") while True: ofs = buf.find(self.boundary) if ofs != -1: self.sr.unrecv(buf[ofs + blen :]) yield buf[:ofs] return d = len(buf) - blen if d > 0: # buffer growing large; yield everything except # the part at the end (maybe start of boundary) yield buf[:d] buf = buf[d:] # look for boundary near the end of the buffer n = 0 for n in range(1, len(buf) + 1): if not buf[-n:] in self.boundary: n -= 1 break if n == 0 or not self.boundary.startswith(buf[-n:]): # no boundary contents near the buffer edge break if blen == n: # EOF: found boundary yield buf[:-n] return try: buf += self.sr.recv(bufsz) except: # abort: client disconnected raise Pebkac(400, "client d/c during multipart post") yield buf def _run_gen( self, ) -> Generator[tuple[str, Optional[str], Generator[bytes, None, None]], None, None]: run = True while run: fieldname, filename = self._read_header() yield (fieldname, filename, self._read_data()) tail = self.sr.recv_ex(2, False) if tail == b"--": # EOF indicated by this immediately after final boundary if self.clen == self.sr.nb: tail = b"\r\n" # dillo doesn't terminate with trailing \r\n else: tail = self.sr.recv_ex(2, False) run = False if tail != b"\r\n": t = "protocol error after field value: want b'\\r\\n', got {!r}" raise Pebkac(400, t.format(tail)) def _read_value(self, iterable: Iterable[bytes], max_len: int) -> bytes: ret = b"" for buf in iterable: ret += buf if len(ret) > max_len: raise Pebkac(422, "field length is too long") return ret def parse(self) -> None: boundary = get_boundary(self.headers) if boundary.startswith('"') and boundary.endswith('"'): boundary = boundary[1:-1] # dillo uses quotes self.log("boundary=%r" % (boundary,)) # spec says there might be junk before the first boundary, # can't have the leading \r\n if that's not the case self.boundary = b"--" + boundary.encode("utf-8") # discard junk before the first boundary for junk in self._read_data(): if not junk: continue jtxt = junk.decode("utf-8", "replace") self.log("discarding preamble |%d| %r" % (len(junk), jtxt)) # nice, now make it fast self.boundary = b"\r\n" + self.boundary self.gen = self._run_gen() def require(self, field_name: str, max_len: int) -> str: assert self.gen # !rm p_field, p_fname, p_data = next(self.gen) if p_field != field_name: raise WrongPostKey(field_name, p_field, p_fname, p_data) return self._read_value(p_data, max_len).decode("utf-8", "surrogateescape") def drop(self) -> None: assert self.gen # !rm for _, _, data in self.gen: for _ in data: pass def get_boundary(headers: dict[str, str]) -> str: # boundaries contain a-z A-Z 0-9 ' ( ) + _ , - . / : = ? # (whitespace allowed except as the last char) ptn = r"^multipart/form-data *; *(.*; *)?boundary=([^;]+)" ct = headers["content-type"] m = re.match(ptn, ct, re.IGNORECASE) if not m: raise Pebkac(400, "invalid content-type for a multipart post: %r" % (ct,)) return m.group(2) def read_header(sr: Unrecv, t_idle: int, t_tot: int) -> list[str]: t0 = time.time() ret = b"" while True: if time.time() - t0 >= t_tot: return [] try: ret += sr.recv(1024, t_idle // 2) except: if not ret: return [] raise Pebkac( 400, "protocol error while reading headers", log=ret.decode("utf-8", "replace"), ) ofs = ret.find(b"\r\n\r\n") if ofs < 0: if len(ret) > 1024 * 32: raise Pebkac(400, "header 2big") else: continue if len(ret) > ofs + 4: sr.unrecv(ret[ofs + 4 :]) return ret[:ofs].decode("utf-8", "surrogateescape").lstrip("\r\n").split("\r\n") def rand_name(fdir: str, fn: str, rnd: int) -> str: ok = False try: ext = "." + fn.rsplit(".", 1)[1] except: ext = "" for extra in range(16): for _ in range(16): if ok: break nc = rnd + extra nb = (6 + 6 * nc) // 8 zb = ub64enc(os.urandom(nb)) fn = zb[:nc].decode("ascii") + ext ok = not os.path.exists(fsenc(os.path.join(fdir, fn))) return fn def _gen_filekey(alg: int, salt: str, fspath: str, fsize: int, inode: int) -> str: if alg == 1: zs = "%s %s %s %s" % (salt, fspath, fsize, inode) else: zs = "%s %s" % (salt, fspath) zb = zs.encode("utf-8", "replace") return ub64enc(hashlib.sha512(zb).digest()).decode("ascii") def _gen_filekey_w(alg: int, salt: str, fspath: str, fsize: int, inode: int) -> str: return _gen_filekey(alg, salt, fspath.replace("/", "\\"), fsize, inode) gen_filekey = _gen_filekey_w if ANYWIN else _gen_filekey def gen_filekey_dbg( alg: int, salt: str, fspath: str, fsize: int, inode: int, log: "NamedLogger", log_ptn: Optional[Pattern[str]], ) -> str: ret = gen_filekey(alg, salt, fspath, fsize, inode) assert log_ptn # !rm if log_ptn.search(fspath): try: import inspect ctx = ",".join(inspect.stack()[n].function for n in range(2, 5)) except: ctx = "" p2 = "a" try: p2 = absreal(fspath) if p2 != fspath: raise Exception() except: t = "maybe wrong abspath for filekey;\norig: %r\nreal: %r" log(t % (fspath, p2), 1) t = "fk(%s) salt(%s) size(%d) inode(%d) fspath(%r) at(%s)" log(t % (ret[:8], salt, fsize, inode, fspath, ctx), 5) return ret WKDAYS = "Mon Tue Wed Thu Fri Sat Sun".split() MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split() RFC2822 = "%s, %02d %s %04d %02d:%02d:%02d GMT" def formatdate(ts: Optional[float] = None) -> str: # gmtime ~= datetime.fromtimestamp(ts, UTC).timetuple() y, mo, d, h, mi, s, wd, _, _ = time.gmtime(ts) return RFC2822 % (WKDAYS[wd], d, MONTHS[mo - 1], y, h, mi, s) def gencookie( k: str, v: str, r: str, lax: bool, tls: bool, dur: int = 0, txt: str = "" ) -> str: v = v.replace("%", "%25").replace(";", "%3B") if dur: exp = formatdate(time.time() + dur) else: exp = "Fri, 15 Aug 1997 01:00:00 GMT" t = "%s=%s; Path=/%s; Expires=%s%s%s; SameSite=%s" return t % ( k, v, r, exp, "; Secure" if tls else "", txt, "Lax" if lax else "Strict", ) def gen_content_disposition(fn: str) -> str: safe = UC_CDISP_SET bsafe = BC_CDISP_SET fn = fn.replace("/", "_").replace("\\", "_") zb = fn.encode("utf-8", "xmlcharrefreplace") if not PY2: zbl = [ chr(x).encode("utf-8") if x in bsafe else "%{:02X}".format(x).encode("ascii") for x in zb ] else: zbl = [unicode(x) if x in bsafe else "%{:02X}".format(ord(x)) for x in zb] ufn = b"".join(zbl).decode("ascii") afn = "".join([x if x in safe else "_" for x in fn]).lstrip(".") while ".." in afn: afn = afn.replace("..", ".") return "attachment; filename=\"%s\"; filename*=UTF-8''%s" % (afn, ufn) def humansize(sz: float, terse: bool = False) -> str: for unit in HUMANSIZE_UNITS: if sz < 1024: break sz /= 1024.0 assert unit # type: ignore # !rm if terse: return "%s%s" % (str(sz)[:4].rstrip("."), unit[:1]) else: return "%s %s" % (str(sz)[:4].rstrip("."), unit) def unhumanize(sz: str) -> int: try: return int(sz) except: pass mc = sz[-1:].lower() mi = UNHUMANIZE_UNITS.get(mc, 1) return int(float(sz[:-1]) * mi) def get_spd(nbyte: int, t0: float, t: Optional[float] = None) -> str: if t is None: t = time.time() bps = nbyte / ((t - t0) or 0.001) s1 = humansize(nbyte).replace(" ", "\033[33m").replace("iB", "") s2 = humansize(bps).replace(" ", "\033[35m").replace("iB", "") return "%s \033[0m%s/s\033[0m" % (s1, s2) def s2hms(s: float, optional_h: bool = False) -> str: s = int(s) h, s = divmod(s, 3600) m, s = divmod(s, 60) if not h and optional_h: return "%d:%02d" % (m, s) return "%d:%02d:%02d" % (h, m, s) def djoin(*paths: str) -> str: return os.path.join(*[x for x in paths if x]) def uncyg(path: str) -> str: if len(path) < 2 or not path.startswith("/"): return path if len(path) > 2 and path[2] != "/": return path return "%s:\\%s" % (path[1], path[3:]) def undot(path: str) -> str: ret: list[str] = [] for node in path.split("/"): if node == "." or not node: continue if node == "..": if ret: ret.pop() continue ret.append(node) return "/".join(ret) def sanitize_fn(fn: str) -> str: fn = fn.replace("\\", "/").split("/")[-1] if APTL_OS: fn = sanitize_to(fn, APTL_OS) return fn.strip() def sanitize_to(fn: str, tl: dict[int, int]) -> str: fn = fn.translate(tl) if ANYWIN: bad = ["con", "prn", "aux", "nul"] for n in range(1, 10): bad += ("com%s lpt%s" % (n, n)).split(" ") if fn.lower().split(".")[0] in bad: fn = "_" + fn return fn def sanitize_vpath(vp: str) -> str: if not APTL_OS: return vp parts = vp.replace(os.sep, "/").split("/") ret = [sanitize_to(x, APTL_OS) for x in parts] return "/".join(ret) def relchk(rp: str) -> str: if "\x00" in rp: return "[nul]" if ANYWIN: if "\n" in rp or "\r" in rp: return "x\nx" p = re.sub(r'[\\:*?"<>|]', "", rp) if p != rp: return "[{}]".format(p) return "" def absreal(fpath: str) -> str: try: return fsdec(os.path.abspath(os.path.realpath(afsenc(fpath)))) except: if not WINDOWS: raise # cpython bug introduced in 3.8, still exists in 3.9.1, # some win7sp1 and win10:20H2 boxes cannot realpath a # networked drive letter such as b"n:" or b"n:\\" return os.path.abspath(os.path.realpath(fpath)) def u8safe(txt: str) -> str: try: return txt.encode("utf-8", "xmlcharrefreplace").decode("utf-8", "replace") except: return txt.encode("utf-8", "replace").decode("utf-8", "replace") def exclude_dotfiles(filepaths: list[str]) -> list[str]: return [x for x in filepaths if not x.split("/")[-1].startswith(".")] def exclude_dotfiles_ls( vfs_ls: list[tuple[str, os.stat_result]] ) -> list[tuple[str, os.stat_result]]: return [x for x in vfs_ls if not x[0].split("/")[-1].startswith(".")] def odfusion( base: Union[ODict[str, bool], ODict["LiteralString", bool]], oth: str ) -> ODict[str, bool]: # merge an "ordered set" (just a dict really) with another list of keys words0 = [x for x in oth.split(",") if x] words1 = [x for x in oth[1:].split(",") if x] ret = base.copy() if oth.startswith("+"): for k in words1: ret[k] = True # type: ignore elif oth[:1] in ("-", "/"): for k in words1: ret.pop(k, None) # type: ignore else: ret = ODict.fromkeys(words0, True) return ret # type: ignore def ipnorm(ip: str) -> str: if ":" in ip: # assume /64 clients; drop 4 groups return IPv6Address(ip).exploded[:-20] return ip def find_prefix(ips: list[str], cidrs: list[str]) -> list[str]: ret = [] for ip in ips: hit = next((x for x in cidrs if x.startswith(ip + "/") or ip == x), None) if hit: ret.append(hit) return ret def html_sh_esc(s: str) -> str: s = re.sub(RE_HTML_SH, "_", s).replace(" ", "%20") s = s.replace("\r", "_").replace("\n", "_") return s def json_hesc(s: str) -> str: return s.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") def html_escape(s: str, quot: bool = False, crlf: bool = False) -> str: s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if quot: s = s.replace('"', "&quot;").replace("'", "&#x27;") if crlf: s = s.replace("\r", "&#13;").replace("\n", "&#10;") return s def html_bescape(s: bytes, quot: bool = False, crlf: bool = False) -> bytes: s = s.replace(b"&", b"&amp;").replace(b"<", b"&lt;").replace(b">", b"&gt;") if quot: s = s.replace(b'"', b"&quot;").replace(b"'", b"&#x27;") if crlf: s = s.replace(b"\r", b"&#13;").replace(b"\n", b"&#10;") return s def _quotep2(txt: str) -> str: if not txt: return "" btxt = w8enc(txt) quot = quote(btxt, safe=b"/") return w8dec(quot.replace(b" ", b"+")) # type: ignore def _quotep3(txt: str) -> str: if not txt: return "" btxt = w8enc(txt) quot = quote(btxt, safe=b"/").encode("utf-8") return w8dec(quot.replace(b" ", b"+")) if not PY2: _uqsb = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-~/" _uqtl = { n: ("%%%02X" % (n,) if n not in _uqsb else chr(n)).encode("utf-8") for n in range(256) } _uqtl[b" "] = b"+" def _quotep3b(txt: str) -> str: if not txt: return "" btxt = w8enc(txt) if btxt.rstrip(_uqsb): lut = _uqtl btxt = b"".join([lut[ch] for ch in btxt]) return w8dec(btxt) quotep = _quotep3b _hexd = "0123456789ABCDEFabcdef" _hex2b = {(a + b).encode(): bytes.fromhex(a + b) for a in _hexd for b in _hexd} def unquote(btxt: bytes) -> bytes: h2b = _hex2b parts = iter(btxt.split(b"%")) ret = [next(parts)] for item in parts: c = h2b.get(item[:2]) if c is None: ret.append(b"%") ret.append(item) else: ret.append(c) ret.append(item[2:]) return b"".join(ret) from urllib.parse import quote_from_bytes as quote else: from urllib import quote # type: ignore # pylint: disable=no-name-in-module from urllib import unquote # type: ignore # pylint: disable=no-name-in-module quotep = _quotep2 def unquotep(txt: str) -> str: btxt = w8enc(txt) unq2 = unquote(btxt) return w8dec(unq2) def vroots(vp1: str, vp2: str) -> tuple[str, str]: while vp1 and vp2: zt1 = vp1.rsplit("/", 1) if "/" in vp1 else ("", vp1) zt2 = vp2.rsplit("/", 1) if "/" in vp2 else ("", vp2) if zt1[1] != zt2[1]: break vp1 = zt1[0] vp2 = zt2[0] return ( "/%s/" % (vp1,) if vp1 else "/", "/%s/" % (vp2,) if vp2 else "/", ) def vsplit(vpath: str) -> tuple[str, str]: if "/" not in vpath: return "", vpath return vpath.rsplit("/", 1) # type: ignore # vpath-join def vjoin(rd: str, fn: str) -> str: if rd and fn: return rd + "/" + fn else: return rd or fn # url-join def ujoin(rd: str, fn: str) -> str: if rd and fn: return rd.rstrip("/") + "/" + fn.lstrip("/") else: return rd or fn def str_anchor(txt) -> tuple[int, str]: if not txt: return 0, "" txt = txt.lower() a = txt.startswith("^") b = txt.endswith("$") if not b: if not a: return 1, txt # ~ return 2, txt[1:] # ^ if not a: return 3, txt[:-1] # $ return 4, txt[1:-1] # ^$ def log_reloc( log: "NamedLogger", re: dict[str, str], pm: tuple[str, str, str, tuple["VFS", str]], ap: str, vp: str, fn: str, vn: "VFS", rem: str, ) -> None: nap, nvp, nfn, (nvn, nrem) = pm t = "reloc %s:\nold ap %r\nnew ap %r\033[36m/%r\033[0m\nold vp %r\nnew vp %r\033[36m/%r\033[0m\nold fn %r\nnew fn %r\nold vfs %r\nnew vfs %r\nold rem %r\nnew rem %r" log(t % (re, ap, nap, nfn, vp, nvp, nfn, fn, nfn, vn.vpath, nvn.vpath, rem, nrem)) def pathmod( vfs: "VFS", ap: str, vp: str, mod: dict[str, str] ) -> Optional[tuple[str, str, str, tuple["VFS", str]]]: # vfs: authsrv.vfs # ap: original abspath to a file # vp: original urlpath to a file # mod: modification (ap/vp/fn) nvp = "\n" # new vpath ap = os.path.dirname(ap) vp, fn = vsplit(vp) if mod.get("fn"): fn = mod["fn"] nvp = vp for ref, k in ((ap, "ap"), (vp, "vp")): if k not in mod: continue ms = mod[k].replace(os.sep, "/") if ms.startswith("/"): np = ms elif k == "vp": np = undot(vjoin(ref, ms)) else: np = os.path.abspath(os.path.join(ref, ms)) if k == "vp": nvp = np.lstrip("/") continue # try to map abspath to vpath np = np.replace("/", os.sep) for vn_ap, vns in vfs.all_aps: if not np.startswith(vn_ap): continue zs = np[len(vn_ap) :].replace(os.sep, "/") nvp = vjoin(vns[0].vpath, zs) break if nvp == "\n": return None vn, rem = vfs.get(nvp, "*", False, False) if not vn.realpath: raise Exception("unmapped vfs") ap = vn.canonical(rem) return ap, nvp, fn, (vn, rem) def _w8dec2(txt: bytes) -> str: return surrogateescape.decodefilename(txt) # type: ignore def _w8enc2(txt: str) -> bytes: return surrogateescape.encodefilename(txt) # type: ignore def _w8dec3(txt: bytes) -> str: return txt.decode(FS_ENCODING, "surrogateescape") def _w8enc3(txt: str) -> bytes: return txt.encode(FS_ENCODING, "surrogateescape") def _msdec(txt: bytes) -> str: ret = txt.decode(FS_ENCODING, "surrogateescape") return ret[4:] if ret.startswith("\\\\?\\") else ret def _msaenc(txt: str) -> bytes: return txt.replace("/", "\\").encode(FS_ENCODING, "surrogateescape") def _uncify(txt: str) -> str: txt = txt.replace("/", "\\") if ":" not in txt and not txt.startswith("\\\\"): txt = absreal(txt) return txt if txt.startswith("\\\\") else "\\\\?\\" + txt def _msenc(txt: str) -> bytes: txt = txt.replace("/", "\\") if ":" not in txt and not txt.startswith("\\\\"): txt = absreal(txt) ret = txt.encode(FS_ENCODING, "surrogateescape") return ret if ret.startswith(b"\\\\") else b"\\\\?\\" + ret w8dec = _w8dec3 if not PY2 else _w8dec2 w8enc = _w8enc3 if not PY2 else _w8enc2 def w8b64dec(txt: str) -> str: return w8dec(ub64dec(txt.encode("ascii"))) def w8b64enc(txt: str) -> str: return ub64enc(w8enc(txt)).decode("ascii") if not PY2 and WINDOWS: sfsenc = w8enc afsenc = _msaenc fsenc = _msenc fsdec = _msdec uncify = _uncify elif not PY2 or not WINDOWS: fsenc = afsenc = sfsenc = w8enc fsdec = w8dec uncify = str else: # moonrunes become \x3f with bytestrings, # losing mojibake support is worth def _not_actually_mbcs_enc(txt: str) -> bytes: return txt # type: ignore def _not_actually_mbcs_dec(txt: bytes) -> str: return txt # type: ignore fsenc = afsenc = sfsenc = _not_actually_mbcs_enc fsdec = _not_actually_mbcs_dec uncify = str def s3enc(mem_cur: "sqlite3.Cursor", rd: str, fn: str) -> tuple[str, str]: ret: list[str] = [] for v in [rd, fn]: try: mem_cur.execute("select * from a where b = ?", (v,)) ret.append(v) except: ret.append("//" + w8b64enc(v)) # self.log("mojien [{}] {}".format(v, ret[-1][2:])) return ret[0], ret[1] def s3dec(rd: str, fn: str) -> tuple[str, str]: return ( w8b64dec(rd[2:]) if rd.startswith("//") else rd, w8b64dec(fn[2:]) if fn.startswith("//") else fn, ) def db_ex_chk(log: "NamedLogger", ex: Exception, db_path: str) -> bool: if str(ex) != "database is locked": return False Daemon(lsof, "dbex", (log, db_path)) return True def lsof(log: "NamedLogger", abspath: str) -> None: try: rc, so, se = runcmd([b"lsof", b"-R", fsenc(abspath)], timeout=45) zs = (so.strip() + "\n" + se.strip()).strip() log("lsof %r = %s\n%s" % (abspath, rc, zs), 3) except: log("lsof failed; " + min_ex(), 3) def set_fperms(f: Union[typing.BinaryIO, typing.IO[Any]], vf: dict[str, Any]) -> None: fno = f.fileno() if "chmod_f" in vf: os.fchmod(fno, vf["chmod_f"]) if "chown" in vf: os.fchown(fno, vf["uid"], vf["gid"]) def set_ap_perms(ap: str, vf: dict[str, Any]) -> None: zb = fsenc(ap) if "chmod_f" in vf: os.chmod(zb, vf["chmod_f"]) if "chown" in vf: os.chown(zb, vf["uid"], vf["gid"]) def trystat_shutil_copy2(log: "NamedLogger", src: bytes, dst: bytes) -> bytes: try: return shutil.copy2(src, dst) except: # ignore failed mtime on linux+ntfs; for example: # shutil.py:437 <copy2>: copystat(src, dst, follow_symlinks=follow_symlinks) # shutil.py:376 <copystat>: lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns), # [PermissionError] [Errno 1] Operation not permitted, '/windows/_videos' _, _, tb = sys.exc_info() for _, _, fun, _ in traceback.extract_tb(tb): if fun == "copystat": if log: t = "warning: failed to retain some file attributes (timestamp and/or permissions) during copy from %r to %r:\n%s" log(t % (src, dst, min_ex()), 3) return dst # close enough raise def _fs_mvrm( log: "NamedLogger", src: str, dst: str, atomic: bool, flags: dict[str, Any] ) -> bool: bsrc = fsenc(src) bdst = fsenc(dst) if atomic: k = "mv_re_" act = "atomic-rename" osfun = os.replace args = [bsrc, bdst] elif dst: k = "mv_re_" act = "rename" osfun = os.rename args = [bsrc, bdst] else: k = "rm_re_" act = "delete" osfun = os.unlink args = [bsrc] maxtime = flags.get(k + "t", 0.0) chill = flags.get(k + "r", 0.0) if chill < 0.001: chill = 0.1 ino = 0 t0 = now = time.time() for attempt in range(90210): try: if ino and os.stat(bsrc).st_ino != ino: t = "src inode changed; aborting %s %r" log(t % (act, src), 1) return False if (dst and not atomic) and os.path.exists(bdst): t = "something appeared at dst; aborting rename %r ==> %r" log(t % (src, dst), 1) return False osfun(*args) # type: ignore if attempt: now = time.time() t = "%sd in %.2f sec, attempt %d: %r" log(t % (act, now - t0, attempt + 1, src)) return True except OSError as ex: now = time.time() if ex.errno == errno.ENOENT: return False if not attempt and ex.errno == errno.EXDEV: t = "using copy+delete (%s)\n %s\n %s" log(t % (ex.strerror, src, dst)) osfun = shutil.move continue if now - t0 > maxtime or attempt == 90209: raise if not attempt: if not PY2: ino = os.stat(bsrc).st_ino t = "%s failed (err.%d); retrying for %d sec: %r" log(t % (act, ex.errno, maxtime + 0.99, src)) time.sleep(chill) return False # makes pylance happy def atomic_move(log: "NamedLogger", src: str, dst: str, flags: dict[str, Any]) -> None: bsrc = fsenc(src) bdst = fsenc(dst) if PY2: if os.path.exists(bdst): _fs_mvrm(log, dst, "", False, flags) # unlink _fs_mvrm(log, src, dst, False, flags) # rename elif flags.get("mv_re_t"): _fs_mvrm(log, src, dst, True, flags) else: try: os.replace(bsrc, bdst) except OSError as ex: if ex.errno != errno.EXDEV: raise t = "using copy+delete (%s);\n %s\n %s" log(t % (ex.strerror, src, dst)) try: os.unlink(bdst) except: pass shutil.move(bsrc, bdst) # type: ignore def wunlink(log: "NamedLogger", abspath: str, flags: dict[str, Any]) -> bool: if not flags.get("rm_re_t"): os.unlink(fsenc(abspath)) return True return _fs_mvrm(log, abspath, "", False, flags) def get_df(abspath: str, prune: bool) -> tuple[int, int, str]: try: ap = fsenc(abspath) while prune and not os.path.isdir(ap) and BOS_SEP in ap: # strip leafs until it hits an existing folder ap = ap.rsplit(BOS_SEP, 1)[0] if ANYWIN: assert ctypes # type: ignore # !rm abspath = fsdec(ap) bfree = ctypes.c_ulonglong(0) btotal = ctypes.c_ulonglong(0) bavail = ctypes.c_ulonglong(0) wk32.GetDiskFreeSpaceExW( # type: ignore ctypes.c_wchar_p(abspath), ctypes.pointer(bavail), ctypes.pointer(btotal), ctypes.pointer(bfree), ) return (bavail.value, btotal.value, "") else: sv = os.statvfs(ap) free = sv.f_frsize * sv.f_bavail total = sv.f_frsize * sv.f_blocks return (free, total, "") except Exception as ex: return (0, 0, repr(ex)) if not ANYWIN and not MACOS: def siocoutq(sck: socket.socket) -> int: assert fcntl # type: ignore # !rm assert termios # type: ignore # !rm # SIOCOUTQ^sockios.h == TIOCOUTQ^ioctl.h try: zb = fcntl.ioctl(sck.fileno(), termios.TIOCOUTQ, b"AAAA") return sunpack(b"I", zb)[0] # type: ignore except: return 1 else: # macos: getsockopt(fd, SOL_SOCKET, SO_NWRITE, ...) # windows: TcpConnectionEstatsSendBuff def siocoutq(sck: socket.socket) -> int: return 1 def shut_socket(log: "NamedLogger", sck: socket.socket, timeout: int = 3) -> None: t0 = time.time() fd = sck.fileno() if fd == -1: sck.close() return try: sck.settimeout(timeout) sck.shutdown(socket.SHUT_WR) try: while time.time() - t0 < timeout: if not siocoutq(sck): # kernel says tx queue empty, we good break # on windows in particular, drain rx until client shuts if not sck.recv(32 * 1024): break sck.shutdown(socket.SHUT_RDWR) except: pass except OSError as ex: log("shut(%d): ok; client has already disconnected; %s" % (fd, ex.errno), "90") except Exception as ex: log("shut({}): {}".format(fd, ex), "90") finally: td = time.time() - t0 if td >= 1: log("shut({}) in {:.3f} sec".format(fd, td), "90") sck.close() def read_socket( sr: Unrecv, bufsz: int, total_size: int ) -> Generator[bytes, None, None]: remains = total_size while remains > 0: if bufsz > remains: bufsz = remains try: buf = sr.recv(bufsz) except OSError: t = "client d/c during binary post after {} bytes, {} bytes remaining" raise Pebkac(400, t.format(total_size - remains, remains)) remains -= len(buf) yield buf def read_socket_unbounded(sr: Unrecv, bufsz: int) -> Generator[bytes, None, None]: try: while True: yield sr.recv(bufsz) except: return def read_socket_chunked( sr: Unrecv, bufsz: int, log: Optional["NamedLogger"] = None ) -> Generator[bytes, None, None]: err = "upload aborted: expected chunk length, got [{}] |{}| instead" while True: buf = b"" while b"\r" not in buf: try: buf += sr.recv(2) if len(buf) > 16: raise Exception() except: err = err.format(buf.decode("utf-8", "replace"), len(buf)) raise Pebkac(400, err) if not buf.endswith(b"\n"): sr.recv(1) try: chunklen = int(buf.rstrip(b"\r\n"), 16) except: err = err.format(buf.decode("utf-8", "replace"), len(buf)) raise Pebkac(400, err) if chunklen == 0: x = sr.recv_ex(2, False) if x == b"\r\n": sr.te = 2 return t = "protocol error after final chunk: want b'\\r\\n', got {!r}" raise Pebkac(400, t.format(x)) if log: log("receiving %d byte chunk" % (chunklen,)) for chunk in read_socket(sr, bufsz, chunklen): yield chunk x = sr.recv_ex(2, False) if x != b"\r\n": t = "protocol error in chunk separator: want b'\\r\\n', got {!r}" raise Pebkac(400, t.format(x)) def list_ips() -> list[str]: ret: set[str] = set() for nic in get_adapters(): for ipo in nic.ips: if len(ipo.ip) < 7: ret.add(ipo.ip[0]) # ipv6 is (ip,0,0) else: ret.add(ipo.ip) return list(ret) def build_netmap(csv: str, defer_mutex: bool = False): csv = csv.lower().strip() if csv in ("any", "all", "no", ",", ""): return None srcs = [x.strip() for x in csv.split(",") if x.strip()] expanded_shorthands = False for shorthand in ("lan", "local", "private", "prvt"): if shorthand in srcs: if not expanded_shorthands: srcs += [ # lan: "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fd00::/8", # link-local: "169.254.0.0/16", "fe80::/10", # loopback: "127.0.0.0/8", "::1/128", ] expanded_shorthands = True srcs.remove(shorthand) if not HAVE_IPV6: srcs = [x for x in srcs if ":" not in x] cidrs = [] for zs in srcs: if not zs.endswith("."): cidrs.append(zs) continue # translate old syntax "172.19." => "172.19.0.0/16" words = len(zs.rstrip(".").split(".")) if words == 1: zs += "0.0.0/8" elif words == 2: zs += "0.0/16" elif words == 3: zs += "0/24" else: raise Exception("invalid config value [%s]" % (zs,)) cidrs.append(zs) ips = [x.split("/")[0] for x in cidrs] return NetMap(ips, cidrs, True, False, defer_mutex) def load_ipu( log: "RootLogger", ipus: list[str], defer_mutex: bool = False ) -> tuple[dict[str, str], NetMap]: ip_u = {"": "*"} cidr_u = {} for ipu in ipus: try: cidr, uname = ipu.split("=") cip, csz = cidr.split("/") except: t = "\n invalid value %r for argument --ipu; must be CIDR=UNAME (192.168.0.0/16=amelia)" raise Exception(t % (ipu,)) uname2 = cidr_u.get(cidr) if uname2 is not None: t = "\n invalid value %r for argument --ipu; cidr %s already mapped to %r" raise Exception(t % (ipu, cidr, uname2)) cidr_u[cidr] = uname ip_u[cip] = uname try: nm = NetMap(["::"], list(cidr_u.keys()), True, True, defer_mutex) except Exception as ex: t = "failed to translate --ipu into netmap, probably due to invalid config: %r" log("root", t % (ex,), 1) raise return ip_u, nm def load_ipr( log: "RootLogger", iprs: list[str], defer_mutex: bool = False ) -> dict[str, NetMap]: ret = {} for ipr in iprs: try: zs, uname = ipr.split("=") cidrs = zs.split(",") except: t = "\n invalid value %r for argument --ipr; must be CIDR[,CIDR[,...]]=UNAME (192.168.0.0/16=amelia)" raise Exception(t % (ipr,)) try: nm = NetMap(["::"], cidrs, True, True, defer_mutex) except Exception as ex: t = "failed to translate --ipr into netmap, probably due to invalid config: %r" log("root", t % (ex,), 1) raise ret[uname] = nm return ret def yieldfile(fn: str, bufsz: int) -> Generator[bytes, None, None]: readsz = min(bufsz, 128 * 1024) with open(fsenc(fn), "rb", bufsz) as f: while True: buf = f.read(readsz) if not buf: break yield buf def justcopy( fin: Generator[bytes, None, None], fout: Union[typing.BinaryIO, typing.IO[Any]], hashobj: Optional["hashlib._Hash"], max_sz: int, slp: float, ) -> tuple[int, str, str]: tlen = 0 for buf in fin: tlen += len(buf) if max_sz and tlen > max_sz: continue fout.write(buf) if slp: time.sleep(slp) return tlen, "checksum-disabled", "checksum-disabled" def eol_conv( fin: Generator[bytes, None, None], conv: str ) -> Generator[bytes, None, None]: crlf = conv.lower() == "crlf" for buf in fin: buf = buf.replace(b"\r", b"") if crlf: buf = buf.replace(b"\n", b"\r\n") yield buf def hashcopy( fin: Generator[bytes, None, None], fout: Union[typing.BinaryIO, typing.IO[Any]], hashobj: Optional["hashlib._Hash"], max_sz: int, slp: float, ) -> tuple[int, str, str]: if not hashobj: hashobj = hashlib.sha512() tlen = 0 for buf in fin: tlen += len(buf) if max_sz and tlen > max_sz: continue hashobj.update(buf) fout.write(buf) if slp: time.sleep(slp) digest_b64 = ub64enc(hashobj.digest()[:33]).decode("ascii") return tlen, hashobj.hexdigest(), digest_b64 def sendfile_py( log: "NamedLogger", lower: int, upper: int, f: typing.BinaryIO, s: socket.socket, bufsz: int, slp: float, use_poll: bool, dls: dict[str, tuple[float, int]], dl_id: str, ) -> int: sent = 0 remains = upper - lower f.seek(lower) while remains > 0: if slp: time.sleep(slp) buf = f.read(min(bufsz, remains)) if not buf: return remains try: s.sendall(buf) remains -= len(buf) except: return remains if dl_id: sent += len(buf) dls[dl_id] = (time.time(), sent) return 0 def sendfile_kern( log: "NamedLogger", lower: int, upper: int, f: typing.BinaryIO, s: socket.socket, bufsz: int, slp: float, use_poll: bool, dls: dict[str, tuple[float, int]], dl_id: str, ) -> int: out_fd = s.fileno() in_fd = f.fileno() ofs = lower stuck = 0.0 if use_poll: poll = select.poll() poll.register(out_fd, select.POLLOUT) while ofs < upper: stuck = stuck or time.time() try: req = min(0x2000000, upper - ofs) # 32 MiB if use_poll: poll.poll(10000) # type: ignore else: select.select([], [out_fd], [], 10) n = os.sendfile(out_fd, in_fd, ofs, req) stuck = 0 except OSError as ex: # client stopped reading; do another select d = time.time() - stuck if d < 3600 and ex.errno == errno.EWOULDBLOCK: time.sleep(0.02) continue n = 0 except Exception as ex: n = 0 d = time.time() - stuck log("sendfile failed after {:.3f} sec: {!r}".format(d, ex)) if n <= 0: return upper - ofs ofs += n if dl_id: dls[dl_id] = (time.time(), ofs - lower) # print("sendfile: ok, sent {} now, {} total, {} remains".format(n, ofs - lower, upper - ofs)) return 0 def statdir( logger: Optional["RootLogger"], scandir: bool, lstat: bool, top: str, throw: bool ) -> Generator[tuple[str, os.stat_result], None, None]: if lstat and ANYWIN: lstat = False if lstat and (PY2 or os.stat not in os.supports_follow_symlinks): scandir = False src = "statdir" try: btop = fsenc(top) if scandir and hasattr(os, "scandir"): src = "scandir" with os.scandir(btop) as dh: for fh in dh: try: yield (fsdec(fh.name), fh.stat(follow_symlinks=not lstat)) except Exception as ex: if not logger: continue logger(src, "[s] {} @ {}".format(repr(ex), fsdec(fh.path)), 6) else: src = "listdir" fun: Any = os.lstat if lstat else os.stat btop_ = os.path.join(btop, b"") for name in os.listdir(btop): abspath = btop_ + name try: yield (fsdec(name), fun(abspath)) except Exception as ex: if not logger: continue logger(src, "[s] {} @ {}".format(repr(ex), fsdec(abspath)), 6) except Exception as ex: if throw: zi = getattr(ex, "errno", 0) if zi == errno.ENOENT: raise Pebkac(404, str(ex)) raise t = "{} @ {}".format(repr(ex), top) if logger: logger(src, t, 1) else: print(t) def dir_is_empty(logger: "RootLogger", scandir: bool, top: str): for _ in statdir(logger, scandir, False, top, False): return False return True def rmdirs( logger: "RootLogger", scandir: bool, lstat: bool, top: str, depth: int ) -> tuple[list[str], list[str]]: if not os.path.isdir(fsenc(top)): top = os.path.dirname(top) depth -= 1 stats = statdir(logger, scandir, lstat, top, False) dirs = [x[0] for x in stats if stat.S_ISDIR(x[1].st_mode)] if dirs: top_ = os.path.join(top, "") dirs = [top_ + x for x in dirs] ok = [] ng = [] for d in reversed(dirs): a, b = rmdirs(logger, scandir, lstat, d, depth + 1) ok += a ng += b if depth: try: os.rmdir(fsenc(top)) ok.append(top) except: ng.append(top) return ok, ng def rmdirs_up(top: str, stop: str) -> tuple[list[str], list[str]]: if top == stop: return [], [top] try: os.rmdir(fsenc(top)) except: return [], [top] par = os.path.dirname(top) if not par or par == stop: return [top], [] ok, ng = rmdirs_up(par, stop) return [top] + ok, ng def unescape_cookie(orig: str, name: str) -> str: # mw=idk; doot=qwe%2Crty%3Basd+fgh%2Bjkl%25zxc%26vbn # qwe,rty;asd fgh+jkl%zxc&vbn if not name.startswith("cppw"): orig = orig[:3] ret = [] esc = "" for ch in orig: if ch == "%": if esc: ret.append(esc) esc = ch elif esc: esc += ch if len(esc) == 3: try: ret.append(chr(int(esc[1:], 16))) except: ret.append(esc) esc = "" else: ret.append(ch) if esc: ret.append(esc) return "".join(ret) def guess_mime( url: str, path: str = "", fallback: str = "application/octet-stream" ) -> str: try: ext = url.rsplit(".", 1)[1].lower() except: ext = "" ret = MIMES.get(ext) if not ret: x = mimetypes.guess_type(url) ret = "application/{}".format(x[1]) if x[1] else x[0] if not ret and path: try: with open(fsenc(path), "rb", 0) as f: ret = magic.from_buffer(f.read(4096), mime=True) if ret.startswith("text/htm"): # avoid serving up HTML content unless there was actually a .html extension ret = "text/plain" except Exception as ex: pass if not ret: ret = fallback if ";" not in ret: if ret.startswith("text/") or ret.endswith("/javascript"): ret += "; charset=utf-8" return ret def safe_mime(mime: str) -> str: if "text/" in mime or "xml" in mime: return "text/plain; charset=utf-8" else: return "application/octet-stream" def getalive(pids: list[int], pgid: int) -> list[int]: alive = [] for pid in pids: try: if pgid: # check if still one of ours if os.getpgid(pid) == pgid: alive.append(pid) else: # windows doesn't have pgroups; assume assert psutil # type: ignore # !rm psutil.Process(pid) alive.append(pid) except: pass return alive def killtree(root: int) -> None: try: # limit the damage where possible (unixes) pgid = os.getpgid(os.getpid()) except: pgid = 0 if HAVE_PSUTIL: assert psutil # type: ignore # !rm pids = [root] parent = psutil.Process(root) for child in parent.children(recursive=True): pids.append(child.pid) child.terminate() parent.terminate() parent = None elif pgid: # linux-only pids = [] chk = [root] while chk: pid = chk[0] chk = chk[1:] pids.append(pid) _, t, _ = runcmd(["pgrep", "-P", str(pid)]) chk += [int(x) for x in t.strip().split("\n") if x] pids = getalive(pids, pgid) # filter to our pgroup for pid in pids: os.kill(pid, signal.SIGTERM) else: # windows gets minimal effort sorry os.kill(root, signal.SIGTERM) return for n in range(10): time.sleep(0.1) pids = getalive(pids, pgid) if not pids or n > 3 and pids == [root]: break for pid in pids: try: os.kill(pid, signal.SIGKILL) except: pass def _find_nice() -> str: if WINDOWS: return "" # use creationflags try: zs = shutil.which("nice") if zs: return zs except: pass # busted PATHs and/or py2 for zs in ("/bin", "/sbin", "/usr/bin", "/usr/sbin"): zs += "/nice" if os.path.exists(zs): return zs return "" NICES = _find_nice() NICEB = NICES.encode("utf-8") def runcmd( argv: Union[list[bytes], list[str], list["LiteralString"]], timeout: Optional[float] = None, **ka: Any ) -> tuple[int, str, str]: isbytes = isinstance(argv[0], (bytes, bytearray)) oom = ka.pop("oom", 0) # 0..1000 kill = ka.pop("kill", "t") # [t]ree [m]ain [n]one capture = ka.pop("capture", 3) # 0=none 1=stdout 2=stderr 3=both sin: Optional[bytes] = ka.pop("sin", None) if sin: ka["stdin"] = sp.PIPE cout = sp.PIPE if capture in [1, 3] else None cerr = sp.PIPE if capture in [2, 3] else None bout: bytes berr: bytes if ANYWIN: if isbytes: if argv[0] in CMD_EXEB: argv[0] += b".exe" # type: ignore else: if argv[0] in CMD_EXES: argv[0] += ".exe" # type: ignore if ka.pop("nice", None): if WINDOWS: ka["creationflags"] = 0x4000 elif NICEB: if isbytes: argv = [NICEB] + argv # type: ignore else: argv = [NICES] + argv # type: ignore p = sp.Popen(argv, stdout=cout, stderr=cerr, **ka) if oom and not ANYWIN and not MACOS: try: with open("/proc/%d/oom_score_adj" % (p.pid,), "wb") as f: f.write(("%d\n" % (oom,)).encode("utf-8")) except: pass if not timeout or PY2: bout, berr = p.communicate(sin) # type: ignore else: try: bout, berr = p.communicate(sin, timeout=timeout) # type: ignore except sp.TimeoutExpired: if kill == "n": return -18, "", "" # SIGCONT; leave it be elif kill == "m": p.kill() else: killtree(p.pid) try: bout, berr = p.communicate(timeout=1) # type: ignore except: bout = b"" berr = b"" stdout = bout.decode("utf-8", "replace") if cout else "" stderr = berr.decode("utf-8", "replace") if cerr else "" rc: int = p.returncode if rc is None: rc = -14 # SIGALRM; failed to kill return rc, stdout, stderr def chkcmd(argv: Union[list[bytes], list[str]], **ka: Any) -> tuple[str, str]: ok, sout, serr = runcmd(argv, **ka) if ok != 0: retchk(ok, argv, serr) raise Exception(serr) return sout, serr def mchkcmd(argv: Union[list[bytes], list[str]], timeout: float = 10) -> None: if PY2: with open(os.devnull, "wb") as f: rv = sp.call(argv, stdout=f, stderr=f) else: rv = sp.call(argv, stdout=sp.DEVNULL, stderr=sp.DEVNULL, timeout=timeout) if rv: raise sp.CalledProcessError(rv, (argv[0], b"...", argv[-1])) def retchk( rc: int, cmd: Union[list[bytes], list[str]], serr: str, logger: Optional["NamedLogger"] = None, color: Union[int, str] = 0, verbose: bool = False, ) -> None: if rc < 0: rc = 128 - rc if not rc or rc < 126 and not verbose: return s = None if rc > 128: try: s = str(signal.Signals(rc - 128)) except: pass elif rc == 126: s = "invalid program" elif rc == 127: s = "program not found" elif verbose: s = "unknown" else: s = "invalid retcode" if s: t = "{} <{}>".format(rc, s) else: t = str(rc) try: c = " ".join([fsdec(x) for x in cmd]) # type: ignore except: c = str(cmd) t = "error {} from [{}]".format(t, c) if serr: if len(serr) > 8192: zs = "%s\n[ ...TRUNCATED... ]\n%s\n[ NOTE: full msg was %d chars ]" serr = zs % (serr[:4096], serr[-4096:].rstrip(), len(serr)) serr = serr.replace("\n", "\nstderr: ") t += "\nstderr: " + serr if logger: logger(t, color) else: raise Exception(t) def _parsehook( log: Optional["NamedLogger"], cmd: str ) -> tuple[str, bool, bool, bool, bool, bool, float, dict[str, Any], list[str]]: areq = "" chk = False fork = False jtxt = False imp = False sin = False wait = 0.0 tout = 0.0 kill = "t" cap = 0 ocmd = cmd while "," in cmd[:6]: arg, cmd = cmd.split(",", 1) if arg == "c": chk = True elif arg == "f": fork = True elif arg == "j": jtxt = True elif arg == "I": imp = True elif arg == "s": sin = True elif arg.startswith("w"): wait = float(arg[1:]) elif arg.startswith("t"): tout = float(arg[1:]) elif arg.startswith("c"): cap = int(arg[1:]) # 0=none 1=stdout 2=stderr 3=both elif arg.startswith("k"): kill = arg[1:] # [t]ree [m]ain [n]one elif arg.startswith("a"): areq = arg[1:] # required perms elif arg.startswith("i"): pass elif not arg: break else: t = "hook: invalid flag {} in {}" (log or print)(t.format(arg, ocmd)) env = os.environ.copy() try: if EXE: raise Exception() pypath = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) zsl = [str(pypath)] + [str(x) for x in sys.path if x] pypath = str(os.pathsep.join(zsl)) env["PYTHONPATH"] = pypath except: if not EXE: raise sp_ka = { "env": env, "nice": True, "oom": 300, "timeout": tout, "kill": kill, "capture": cap, } argv = cmd.split(",") if "," in cmd else [cmd] argv[0] = os.path.expandvars(os.path.expanduser(argv[0])) return areq, chk, imp, fork, sin, jtxt, wait, sp_ka, argv def runihook( log: Optional["NamedLogger"], verbose: bool, cmd: str, vol: "VFS", ups: list[tuple[str, int, int, str, str, str, int, str]], ) -> bool: _, chk, _, fork, _, jtxt, wait, sp_ka, acmd = _parsehook(log, cmd) bcmd = [sfsenc(x) for x in acmd] if acmd[0].endswith(".py"): bcmd = [sfsenc(pybin)] + bcmd vps = [vjoin(*list(s3dec(x[3], x[4]))) for x in ups] aps = [djoin(vol.realpath, x) for x in vps] if jtxt: # 0w 1mt 2sz 3rd 4fn 5ip 6at ja = [ { "ap": uncify(ap), # utf8 for json "vp": vp, "wark": x[0][:16], "mt": x[1], "sz": x[2], "ip": x[5], "at": x[6], } for x, vp, ap in zip(ups, vps, aps) ] sp_ka["sin"] = json.dumps(ja).encode("utf-8", "replace") else: sp_ka["sin"] = b"\n".join(fsenc(x) for x in aps) if acmd[0].startswith("zmq:"): try: msg = sp_ka["sin"].decode("utf-8", "replace") _zmq_hook(log, verbose, "xiu", acmd[0][4:].lower(), msg, wait, sp_ka) if verbose and log: log("hook(xiu) %r OK" % (cmd,), 6) except Exception as ex: if log: log("zeromq failed: %r" % (ex,)) return True t0 = time.time() if fork: Daemon(runcmd, cmd, bcmd, ka=sp_ka) else: rc, v, err = runcmd(bcmd, **sp_ka) # type: ignore if chk and rc: retchk(rc, bcmd, err, log, 5) return False if wait: wait -= time.time() - t0 if wait > 0: time.sleep(wait) return True ZMQ = {} ZMQ_DESC = { "pub": "fire-and-forget to all/any connected SUB-clients", "push": "fire-and-forget to one of the connected PULL-clients", "req": "send messages to a REP-server and blocking-wait for ack", } def _zmq_hook( log: Optional["NamedLogger"], verbose: bool, src: str, cmd: str, msg: str, wait: float, sp_ka: dict[str, Any], ) -> tuple[int, str]: import zmq try: mtx = ZMQ["mtx"] except: ZMQ["mtx"] = threading.Lock() time.sleep(0.1) mtx = ZMQ["mtx"] ret = "" nret = 0 t0 = time.time() if verbose and log: log("hook(%s) %r entering zmq-main-lock" % (src, cmd), 6) with mtx: try: mode, sck, mtx = ZMQ[cmd] except: mode, uri = cmd.split(":", 1) try: desc = ZMQ_DESC[mode] if log: t = "libzmq(%s) pyzmq(%s) init(%s); %s" log(t % (zmq.zmq_version(), zmq.__version__, cmd, desc)) except: raise Exception("the only supported ZMQ modes are REQ PUB PUSH") try: ctx = ZMQ["ctx"] except: ctx = ZMQ["ctx"] = zmq.Context() timeout = sp_ka["timeout"] if mode == "pub": sck = ctx.socket(zmq.PUB) sck.setsockopt(zmq.LINGER, 0) sck.bind(uri) time.sleep(1) # give clients time to connect; avoids losing first msg elif mode == "push": sck = ctx.socket(zmq.PUSH) if timeout: sck.SNDTIMEO = int(timeout * 1000) sck.setsockopt(zmq.LINGER, 0) sck.bind(uri) elif mode == "req": sck = ctx.socket(zmq.REQ) if timeout: sck.RCVTIMEO = int(timeout * 1000) sck.setsockopt(zmq.LINGER, 0) sck.connect(uri) else: raise Exception() mtx = threading.Lock() ZMQ[cmd] = (mode, sck, mtx) if verbose and log: log("hook(%s) %r entering socket-lock" % (src, cmd), 6) with mtx: if verbose and log: log("hook(%s) %r sending |%d|" % (src, cmd, len(msg)), 6) sck.send_string(msg) # PUSH can safely timeout here if mode == "req": if verbose and log: log("hook(%s) %r awaiting ack from req" % (src, cmd), 6) try: ret = sck.recv().decode("utf-8", "replace") if ret.startswith("return "): m = re.search("^return ([0-9]+)", ret[:12]) if m: nret = int(m.group(1)) except: sck.close() del ZMQ[cmd] # bad state; must reset raise Exception("ack timeout; zmq socket killed") if ret and log: log("hook(%s) %r ACK: %r" % (src, cmd, ret), 6) if wait: wait -= time.time() - t0 if wait > 0: time.sleep(wait) return nret, ret def _runhook( log: Optional["NamedLogger"], verbose: bool, src: str, cmd: str, ap: str, vp: str, host: str, uname: str, perms: str, mt: float, sz: int, ip: str, at: float, txt: Optional[list[str]], ) -> dict[str, Any]: ret = {"rc": 0} areq, chk, imp, fork, sin, jtxt, wait, sp_ka, acmd = _parsehook(log, cmd) if areq: for ch in areq: if ch not in perms: t = "user %s not allowed to run hook %s; need perms %s, have %s" if log: log(t % (uname, cmd, areq, perms)) return ret # fallthrough to next hook if imp or jtxt: ja = { "ap": ap, "vp": vp, "mt": mt, "sz": sz, "ip": ip, "at": at or time.time(), "host": host, "user": uname, "perms": perms, "src": src, } if txt: ja["txt"] = txt[0] ja["body"] = txt[1] if imp: ja["log"] = log mod = loadpy(acmd[0], False) return mod.main(ja) arg = json.dumps(ja) else: arg = txt[0] if txt else ap if acmd[0].startswith("zmq:"): zi, zs = _zmq_hook(log, verbose, src, acmd[0][4:].lower(), arg, wait, sp_ka) if zi: raise Exception("zmq says %d" % (zi,)) try: ret = json.loads(zs) if "rc" not in ret: ret["rc"] = 0 return ret except: return {"rc": 0, "stdout": zs} if sin: sp_ka["sin"] = (arg + "\n").encode("utf-8", "replace") else: acmd += [arg] if acmd[0].endswith(".py"): acmd = [pybin] + acmd bcmd = [fsenc(x) if x == ap else sfsenc(x) for x in acmd] t0 = time.time() if fork: Daemon(runcmd, cmd, [bcmd], ka=sp_ka) else: rc, v, err = runcmd(bcmd, **sp_ka) # type: ignore if chk and rc: ret["rc"] = rc zi = 0 if rc == 100 else rc retchk(zi, bcmd, err, log, 5) else: try: ret = json.loads(v) except: pass try: if "stdout" not in ret: ret["stdout"] = v if "stderr" not in ret: ret["stderr"] = err if "rc" not in ret: ret["rc"] = rc except: ret = {"rc": rc, "stdout": v, "stderr": err} if wait: wait -= time.time() - t0 if wait > 0: time.sleep(wait) return ret def runhook( log: Optional["NamedLogger"], broker: Optional["BrokerCli"], up2k: Optional["Up2k"], src: str, cmds: list[str], ap: str, vp: str, host: str, uname: str, perms: str, mt: float, sz: int, ip: str, at: float, txt: Optional[list[str]], ) -> dict[str, Any]: assert broker or up2k # !rm args = (broker or up2k).args # type: ignore verbose = args.hook_v vp = vp.replace("\\", "/") ret = {"rc": 0} stop = False for cmd in cmds: try: hr = _runhook( log, verbose, src, cmd, ap, vp, host, uname, perms, mt, sz, ip, at, txt ) if verbose and log: log("hook(%s) %r => \033[32m%s" % (src, cmd, hr), 6) for k, v in hr.items(): if k in ("idx", "del") and v: if broker: broker.say("up2k.hook_fx", k, v, vp) else: assert up2k # !rm up2k.fx_backlog.append((k, v, vp)) elif k == "reloc" and v: # idk, just take the last one ig ret["reloc"] = v elif k == "rc" and v: stop = True ret[k] = 0 if v == 100 else v elif k in ret: if k == "stdout" and v and not ret[k]: ret[k] = v else: ret[k] = v except Exception as ex: (log or print)("hook: %r, %s" % (ex, ex)) if ",c," in "," + cmd: return {"rc": 1} break if stop: break return ret def loadpy(ap: str, hot: bool) -> Any: ap = os.path.expandvars(os.path.expanduser(ap)) mdir, mfile = os.path.split(absreal(ap)) mname = mfile.rsplit(".", 1)[0] sys.path.insert(0, mdir) if PY2: mod = __import__(mname) if hot: reload(mod) # type: ignore else: import importlib mod = importlib.import_module(mname) if hot: importlib.reload(mod) sys.path.remove(mdir) return mod def gzip_orig_sz(fn: str) -> int: with open(fsenc(fn), "rb") as f: return gzip_file_orig_sz(f) def gzip_file_orig_sz(f) -> int: start = f.tell() f.seek(-4, 2) rv = f.read(4) f.seek(start, 0) return sunpack(b"I", rv)[0] # type: ignore def align_tab(lines: list[str]) -> list[str]: rows = [] ncols = 0 for ln in lines: row = [x for x in ln.split(" ") if x] ncols = max(ncols, len(row)) rows.append(row) lens = [0] * ncols for row in rows: for n, col in enumerate(row): lens[n] = max(lens[n], len(col)) return ["".join(x.ljust(y + 2) for x, y in zip(row, lens)) for row in rows] def visual_length(txt: str) -> int: # from r0c eoc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" clen = 0 pend = None counting = True for ch in txt: # escape sequences can never contain ESC; # treat pend as regular text if so if ch == "\033" and pend: clen += len(pend) counting = True pend = None if not counting: if ch in eoc: counting = True else: if pend: pend += ch if pend.startswith("\033["): counting = False else: clen += len(pend) counting = True pend = None else: if ch == "\033": pend = "%s" % (ch,) else: co = ord(ch) # the safe parts of latin1 and cp437 (no greek stuff) if ( co < 0x100 # ascii + lower half of latin1 or (co >= 0x2500 and co <= 0x25A0) # box drawings or (co >= 0x2800 and co <= 0x28FF) # braille ): clen += 1 else: # assume moonrunes or other double-width clen += 2 return clen def wrap(txt: str, maxlen: int, maxlen2: int) -> list[str]: # from r0c words = re.sub(r"([, ])", r"\1\n", txt.rstrip()).split("\n") pad = maxlen - maxlen2 ret = [] for word in words: if len(word) * 2 < maxlen or visual_length(word) < maxlen: ret.append(word) else: while visual_length(word) >= maxlen: ret.append(word[: maxlen - 1] + "-") word = word[maxlen - 1 :] if word: ret.append(word) words = ret ret = [] ln = "" spent = 0 for word in words: wl = visual_length(word) if spent + wl > maxlen: ret.append(ln) maxlen = maxlen2 spent = 0 ln = " " * pad ln += word spent += wl if ln: ret.append(ln) return ret def termsize() -> tuple[int, int]: try: w, h = os.get_terminal_size() return w, h except: pass env = os.environ def ioctl_GWINSZ(fd: int) -> Optional[tuple[int, int]]: assert fcntl # type: ignore # !rm assert termios # type: ignore # !rm try: cr = sunpack(b"hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, b"AAAA")) return cr[::-1] except: return None cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = ioctl_GWINSZ(fd) os.close(fd) except: pass try: return cr or (int(env["COLUMNS"]), int(env["LINES"])) except: return 80, 25 def hidedir(dp) -> None: if ANYWIN: try: assert wk32 # type: ignore # !rm k32 = wk32 attrs = k32.GetFileAttributesW(dp) if attrs >= 0: k32.SetFileAttributesW(dp, attrs | 2) except: pass _flocks = {} def _lock_file_noop(ap: str) -> bool: return True def _lock_file_ioctl(ap: str) -> bool: assert fcntl # type: ignore # !rm try: fd = _flocks.pop(ap) os.close(fd) except: pass fd = os.open(ap, os.O_RDWR | os.O_CREAT, 438) # NOTE: the fcntl.lockf identifier is (pid,node); # the lock will be dropped if os.close(os.open(ap)) # is performed anywhere else in this thread try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) _flocks[ap] = fd return True except Exception as ex: eno = getattr(ex, "errno", -1) try: os.close(fd) except: pass if eno in (errno.EAGAIN, errno.EACCES): return False print("WARNING: unexpected errno %d from fcntl.lockf; %r" % (eno, ex)) return True def _lock_file_windows(ap: str) -> bool: try: import msvcrt try: fd = _flocks.pop(ap) os.close(fd) except: pass fd = os.open(ap, os.O_RDWR | os.O_CREAT, 438) msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) return True except Exception as ex: eno = getattr(ex, "errno", -1) if eno == errno.EACCES: return False print("WARNING: unexpected errno %d from msvcrt.locking; %r" % (eno, ex)) return True if os.environ.get("PRTY_NO_DB_LOCK"): lock_file = _lock_file_noop elif ANYWIN: lock_file = _lock_file_windows elif HAVE_FCNTL: lock_file = _lock_file_ioctl else: lock_file = _lock_file_noop def _open_nolock_windows(bap: Union[str, bytes], *a, **ka) -> typing.BinaryIO: assert ctypes # !rm assert wk32 # !rm import msvcrt try: ap = bap.decode("utf-8", "replace") # type: ignore except: ap = bap fh = wk32.CreateFileW(ap, 0x80000000, 7, None, 3, 0x80, None) # `-ap, GENERIC_READ, FILE_SHARE_READ|WRITE|DELETE, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None if fh == -1: ec = ctypes.get_last_error() # type: ignore raise ctypes.WinError(ec) # type: ignore fd = msvcrt.open_osfhandle(fh, os.O_RDONLY) # type: ignore return os.fdopen(fd, "rb") if ANYWIN: open_nolock = _open_nolock_windows else: open_nolock = open try: if sys.version_info < (3, 10) or os.environ.get("PRTY_NO_IMPRESO"): # py3.8 doesn't have .files # py3.9 has broken .is_file raise ImportError() import importlib.resources as impresources except ImportError: try: import importlib_resources as impresources except ImportError: impresources = None try: if sys.version_info > (3, 10): raise ImportError() import pkg_resources except ImportError: pkg_resources = None def _pkg_resource_exists(pkg: str, name: str) -> bool: if not pkg_resources: return False try: return pkg_resources.resource_exists(pkg, name) except NotImplementedError: return False def stat_resource(E: EnvParams, name: str): path = E.mod_ + name if os.path.exists(path): return os.stat(fsenc(path)) return None def _find_impresource(pkg: types.ModuleType, name: str): assert impresources # !rm try: files = impresources.files(pkg) except ImportError: return None return files.joinpath(name) _rescache_has = {} def _has_resource(name: str): try: return _rescache_has[name] except: pass if len(_rescache_has) > 999: _rescache_has.clear() assert __package__ # !rm pkg = sys.modules[__package__] if impresources: res = _find_impresource(pkg, name) if res and res.is_file(): _rescache_has[name] = True return True if pkg_resources: if _pkg_resource_exists(pkg.__name__, name): _rescache_has[name] = True return True _rescache_has[name] = False return False def has_resource(E: EnvParams, name: str): return _has_resource(name) or os.path.exists(E.mod_ + name) def load_resource(E: EnvParams, name: str, mode="rb") -> IO[bytes]: enc = None if "b" in mode else "utf-8" if impresources: assert __package__ # !rm res = _find_impresource(sys.modules[__package__], name) if res and res.is_file(): if enc: return res.open(mode, encoding=enc) else: # throws if encoding= is mentioned at all return res.open(mode) if pkg_resources: assert __package__ # !rm pkg = sys.modules[__package__] if _pkg_resource_exists(pkg.__name__, name): stream = pkg_resources.resource_stream(pkg.__name__, name) if enc: stream = codecs.getreader(enc)(stream) return stream ap = E.mod_ + name if PY2: return codecs.open(ap, "r", encoding=enc) # type: ignore return open(ap, mode, encoding=enc) class Pebkac(Exception): def __init__( self, code: int, msg: Optional[str] = None, log: Optional[str] = None ) -> None: super(Pebkac, self).__init__(msg or HTTPCODE[code]) self.code = code self.log = log def __repr__(self) -> str: return "Pebkac({}, {})".format(self.code, repr(self.args)) class WrongPostKey(Pebkac): def __init__( self, expected: str, got: str, fname: Optional[str], datagen: Generator[bytes, None, None], ) -> None: msg = 'expected field "{}", got "{}"'.format(expected, got) super(WrongPostKey, self).__init__(422, msg) self.expected = expected self.got = got self.fname = fname self.datagen = datagen _: Any = ( gzip, mp, zlib, BytesIO, quote, unquote, SQLITE_VER, JINJA_VER, PYFTPD_VER, PARTFTPY_VER, ) __all__ = [ "gzip", "mp", "zlib", "BytesIO", "quote", "unquote", "SQLITE_VER", "JINJA_VER", "PYFTPD_VER", "PARTFTPY_VER", ]
--- +++ @@ -925,6 +925,10 @@ strict_cidr=False, defer_mutex=False, ) -> None: + """ + ips: list of plain ipv4/ipv6 IPs, not cidr + cidrs: list of cidr-notation IPs (ip/prefix) + """ # fails multiprocessing; defer assignment self.mutex: Optional[threading.Lock] = None if defer_mutex else threading.Lock() @@ -988,6 +992,9 @@ class _Unrecv(object): + """ + undo any number of socket recv ops + """ def __init__(self, s: socket.socket, log: Optional["NamedLogger"]) -> None: self.s = s @@ -1024,6 +1031,7 @@ return ret def recv_ex(self, nbytes: int, raise_on_trunc: bool = True) -> bytes: + """read an exact number of bytes""" ret = b"" try: while nbytes > len(ret): @@ -1052,6 +1060,9 @@ # !rm.yes> class _LUnrecv(object): + """ + with expensive debug logging + """ def __init__(self, s: socket.socket, log: Optional["NamedLogger"]) -> None: self.s = s @@ -1078,6 +1089,7 @@ return ret def recv_ex(self, nbytes: int, raise_on_trunc: bool = True) -> bytes: + """read an exact number of bytes""" try: ret = self.recv(nbytes, 1) err = False @@ -1221,6 +1233,9 @@ class ProgressPrinter(threading.Thread): + """ + periodically print progress info without linefeeds + """ def __init__(self, log: "NamedLogger", args: argparse.Namespace) -> None: threading.Thread.__init__(self, name="pp") @@ -1440,6 +1455,7 @@ class Garda(object): + """ban clients for repeated offenses""" def __init__(self, cfg: str, uniq: bool = True) -> None: self.uniq = uniq @@ -1858,6 +1874,12 @@ ] = None def _read_header(self) -> tuple[str, Optional[str]]: + """ + returns [fieldname, filename] after eating a block of multipart headers + while doing a decent job at dealing with the absolute mess that is + rfc1341/rfc1521/rfc2047/rfc2231/rfc2388/rfc6266/the-real-world + (only the fallback non-js uploader relies on these filenames) + """ for ln in read_header(self.sr, 2, 2592000): self.log(repr(ln)) @@ -1980,6 +2002,10 @@ def _run_gen( self, ) -> Generator[tuple[str, Optional[str], Generator[bytes, None, None]], None, None]: + """ + yields [fieldname, unsanitized_filename, fieldvalue] + where fieldvalue yields chunks of data + """ run = True while run: fieldname, filename = self._read_header() @@ -2031,6 +2057,10 @@ self.gen = self._run_gen() def require(self, field_name: str, max_len: int) -> str: + """ + returns the value of the next field in the multipart body, + raises if the field name is not as expected + """ assert self.gen # !rm p_field, p_fname, p_data = next(self.gen) if p_field != field_name: @@ -2039,6 +2069,7 @@ return self._read_value(p_data, max_len).decode("utf-8", "surrogateescape") def drop(self) -> None: + """discards the remaining multipart body""" assert self.gen # !rm for _, _, data in self.gen: for _ in data: @@ -2263,6 +2294,7 @@ def djoin(*paths: str) -> str: + """joins without adding a trailing slash on blank args""" return os.path.join(*[x for x in paths if x]) @@ -2412,6 +2444,7 @@ def html_escape(s: str, quot: bool = False, crlf: bool = False) -> str: + """html.escape but also newlines""" s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if quot: s = s.replace('"', "&quot;").replace("'", "&#x27;") @@ -2422,6 +2455,7 @@ def html_bescape(s: bytes, quot: bool = False, crlf: bool = False) -> bytes: + """html.escape but bytestrings""" s = s.replace(b"&", b"&amp;").replace(b"<", b"&lt;").replace(b">", b"&gt;") if quot: s = s.replace(b'"', b"&quot;").replace(b"'", b"&#x27;") @@ -2432,6 +2466,7 @@ def _quotep2(txt: str) -> str: + """url quoter which deals with bytes correctly""" if not txt: return "" btxt = w8enc(txt) @@ -2440,6 +2475,7 @@ def _quotep3(txt: str) -> str: + """url quoter which deals with bytes correctly""" if not txt: return "" btxt = w8enc(txt) @@ -2456,6 +2492,7 @@ _uqtl[b" "] = b"+" def _quotep3b(txt: str) -> str: + """url quoter which deals with bytes correctly""" if not txt: return "" btxt = w8enc(txt) @@ -2492,12 +2529,16 @@ def unquotep(txt: str) -> str: + """url unquoter which deals with bytes correctly""" btxt = w8enc(txt) unq2 = unquote(btxt) return w8dec(unq2) def vroots(vp1: str, vp2: str) -> tuple[str, str]: + """ + input("q/w/e/r","a/s/d/e/r") output("/q/w/","/a/s/d/") + """ while vp1 and vp2: zt1 = vp1.rsplit("/", 1) if "/" in vp1 else ("", vp1) zt2 = vp2.rsplit("/", 1) if "/" in vp2 else ("", vp2) @@ -2616,18 +2657,22 @@ def _w8dec2(txt: bytes) -> str: + """decodes filesystem-bytes to wtf8""" return surrogateescape.decodefilename(txt) # type: ignore def _w8enc2(txt: str) -> bytes: + """encodes wtf8 to filesystem-bytes""" return surrogateescape.encodefilename(txt) # type: ignore def _w8dec3(txt: bytes) -> str: + """decodes filesystem-bytes to wtf8""" return txt.decode(FS_ENCODING, "surrogateescape") def _w8enc3(txt: str) -> bytes: + """encodes wtf8 to filesystem-bytes""" return txt.encode(FS_ENCODING, "surrogateescape") @@ -2662,10 +2707,12 @@ def w8b64dec(txt: str) -> str: + """decodes base64(filesystem-bytes) to wtf8""" return w8dec(ub64dec(txt.encode("ascii"))) def w8b64enc(txt: str) -> str: + """encodes wtf8 to base64(filesystem-bytes)""" return ub64enc(w8enc(txt)).decode("ascii") @@ -3351,6 +3398,7 @@ def rmdirs( logger: "RootLogger", scandir: bool, lstat: bool, top: str, depth: int ) -> tuple[list[str], list[str]]: + """rmdir all descendants, then self""" if not os.path.isdir(fsenc(top)): top = os.path.dirname(top) depth -= 1 @@ -3378,6 +3426,7 @@ def rmdirs_up(top: str, stop: str) -> tuple[list[str], list[str]]: + """rmdir on self, then all parents""" if top == stop: return [], [top] @@ -3485,6 +3534,7 @@ def killtree(root: int) -> None: + """still racy but i tried""" try: # limit the damage where possible (unixes) pgid = os.getpgid(os.getpid()) @@ -4109,6 +4159,11 @@ def loadpy(ap: str, hot: bool) -> Any: + """ + a nice can of worms capable of causing all sorts of bugs + depending on what other inconveniently named files happen + to be in the same folder + """ ap = os.path.expandvars(os.path.expanduser(ap)) mdir, mfile = os.path.split(absreal(ap)) mname = mfile.rsplit(".", 1)[0] @@ -4535,4 +4590,4 @@ "JINJA_VER", "PYFTPD_VER", "PARTFTPY_VER", -]+]
https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/util.py
Write docstrings describing each step
from typing import Union class Node: pass class A(Node): pass class B(Node): pass class C(A, B): pass class Visitor: def visit(self, node: Union[A, C, B], *args, **kwargs) -> None: meth = None for cls in node.__class__.__mro__: meth_name = "visit_" + cls.__name__ meth = getattr(self, meth_name, None) if meth: break if not meth: meth = self.generic_visit return meth(node, *args, **kwargs) def generic_visit(self, node: A, *args, **kwargs) -> None: print("generic_visit " + node.__class__.__name__) def visit_B(self, node: Union[C, B], *args, **kwargs) -> None: print("visit_B " + node.__class__.__name__) def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,19 @@+""" +http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html + +*TL;DR +Separates an algorithm from an object structure on which it operates. + +An interesting recipe could be found in +Brian Jones, David Beazley "Python Cookbook" (2013): +- "8.21. Implementing the Visitor Pattern" +- "8.22. Implementing the Visitor Pattern Without Recursion" + +*Examples in Python ecosystem: +- Python's ast.NodeVisitor: https://github.com/python/cpython/blob/master/Lib/ast.py#L250 +which is then being used e.g. in tools like `pyflakes`. +- `Black` formatter tool implements it's own: https://github.com/ambv/black/blob/master/black.py#L718 +""" from typing import Union @@ -38,9 +54,22 @@ def main(): + """ + >>> a, b, c = A(), B(), C() + >>> visitor = Visitor() + + >>> visitor.visit(a) + 'generic_visit A' + + >>> visitor.visit(b) + 'visit_B B' + + >>> visitor.visit(c) + 'visit_B C' + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/visitor.py
Add verbose docstrings with examples
class UnsupportedMessageType(BaseException): pass class UnsupportedState(BaseException): pass class UnsupportedTransition(BaseException): pass class HierachicalStateMachine: def __init__(self): self._active_state = Active(self) # Unit.Inservice.Active() self._standby_state = Standby(self) # Unit.Inservice.Standby() self._suspect_state = Suspect(self) # Unit.OutOfService.Suspect() self._failed_state = Failed(self) # Unit.OutOfService.Failed() self._current_state = self._standby_state self.states = { "active": self._active_state, "standby": self._standby_state, "suspect": self._suspect_state, "failed": self._failed_state, } self.message_types = { "fault trigger": self._current_state.on_fault_trigger, "switchover": self._current_state.on_switchover, "diagnostics passed": self._current_state.on_diagnostics_passed, "diagnostics failed": self._current_state.on_diagnostics_failed, "operator inservice": self._current_state.on_operator_inservice, } def _next_state(self, state): try: self._current_state = self.states[state] except KeyError: raise UnsupportedState def _send_diagnostics_request(self): return "send diagnostic request" def _raise_alarm(self): return "raise alarm" def _clear_alarm(self): return "clear alarm" def _perform_switchover(self): return "perform switchover" def _send_switchover_response(self): return "send switchover response" def _send_operator_inservice_response(self): return "send operator inservice response" def _send_diagnostics_failure_report(self): return "send diagnostics failure report" def _send_diagnostics_pass_report(self): return "send diagnostics pass report" def _abort_diagnostics(self): return "abort diagnostics" def _check_mate_status(self): return "check mate status" def on_message(self, message_type): # message ignored if message_type in self.message_types.keys(): self.message_types[message_type]() else: raise UnsupportedMessageType class Unit: def __init__(self, HierachicalStateMachine): self.hsm = HierachicalStateMachine def on_switchover(self): raise UnsupportedTransition def on_fault_trigger(self): raise UnsupportedTransition def on_diagnostics_failed(self): raise UnsupportedTransition def on_diagnostics_passed(self): raise UnsupportedTransition def on_operator_inservice(self): raise UnsupportedTransition class Inservice(Unit): def __init__(self, HierachicalStateMachine): self._hsm = HierachicalStateMachine def on_fault_trigger(self): self._hsm._next_state("suspect") self._hsm._send_diagnostics_request() self._hsm._raise_alarm() def on_switchover(self): self._hsm._perform_switchover() self._hsm._check_mate_status() self._hsm._send_switchover_response() class Active(Inservice): def __init__(self, HierachicalStateMachine): self._hsm = HierachicalStateMachine def on_fault_trigger(self): super().perform_switchover() super().on_fault_trigger() def on_switchover(self): self._hsm.on_switchover() # message ignored self._hsm.next_state("standby") class Standby(Inservice): def __init__(self, HierachicalStateMachine): self._hsm = HierachicalStateMachine def on_switchover(self): super().on_switchover() # message ignored self._hsm._next_state("active") class OutOfService(Unit): def __init__(self, HierachicalStateMachine): self._hsm = HierachicalStateMachine def on_operator_inservice(self): self._hsm.on_switchover() # message ignored self._hsm.send_operator_inservice_response() self._hsm.next_state("suspect") class Suspect(OutOfService): def __init__(self, HierachicalStateMachine): self._hsm = HierachicalStateMachine def on_diagnostics_failed(self): super().send_diagnostics_failure_report() super().next_state("failed") def on_diagnostics_passed(self): super().send_diagnostics_pass_report() super().clear_alarm() # loss of redundancy alarm super().next_state("standby") def on_operator_inservice(self): super().abort_diagnostics() super().on_operator_inservice() # message ignored class Failed(OutOfService): def __init__(self, HierachicalStateMachine): self._hsm = HierachicalStateMachine
--- +++ @@ -1,3 +1,12 @@+""" +Implementation of the HSM (hierarchical state machine) or +NFSM (nested finite state machine) C++ example from +http://www.eventhelix.com/RealtimeMantra/HierarchicalStateMachine.htm#.VwqLVEL950w +in Python + +- single source 'message type' for state transition changes +- message type considered, messages (comment) not considered to avoid complexity +""" class UnsupportedMessageType(BaseException): @@ -162,6 +171,7 @@ class Failed(OutOfService): + """No need to override any method.""" def __init__(self, HierachicalStateMachine): - self._hsm = HierachicalStateMachine+ self._hsm = HierachicalStateMachine
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/other/hsm/hsm.py
Add docstrings that explain inputs and outputs
import random from typing import Type class Pet: def __init__(self, name: str) -> None: self.name = name def speak(self) -> None: raise NotImplementedError def __str__(self) -> str: raise NotImplementedError class Dog(Pet): def speak(self) -> None: print("woof") def __str__(self) -> str: return f"Dog<{self.name}>" class Cat(Pet): def speak(self) -> None: print("meow") def __str__(self) -> str: return f"Cat<{self.name}>" class PetShop: def __init__(self, animal_factory: Type[Pet]) -> None: self.pet_factory = animal_factory def buy_pet(self, name: str) -> Pet: pet = self.pet_factory(name) print(f"Here is your lovely {pet}") return pet # Show pets with various factories def main() -> None: if __name__ == "__main__": animals = [Dog, Cat] random_animal: Type[Pet] = random.choice(animals) shop = PetShop(random_animal) import doctest doctest.testmod()
--- +++ @@ -1,3 +1,34 @@+""" +*What is this pattern about? + +In Java and other languages, the Abstract Factory Pattern serves to provide an interface for +creating related/dependent objects without need to specify their +actual class. + +The idea is to abstract the creation of objects depending on business +logic, platform choice, etc. + +In Python, the interface we use is simply a callable, which is "builtin" interface +in Python, and in normal circumstances we can simply use the class itself as +that callable, because classes are first class objects in Python. + +*What does this example do? +This particular implementation abstracts the creation of a pet and +does so depending on the factory we chose (Dog or Cat, or random_animal) +This works because both Dog/Cat and random_animal respect a common +interface (callable for creation and .speak()). +Now my application can create pets abstractly and decide later, +based on my own criteria, dogs over cats. + +*Where is the pattern used practically? + +*References: +https://sourcemaking.com/design_patterns/abstract_factory +http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/ + +*TL;DR +Provides a way to encapsulate a group of individual factories. +""" import random from typing import Type @@ -31,12 +62,15 @@ class PetShop: + """A pet shop""" def __init__(self, animal_factory: Type[Pet]) -> None: + """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def buy_pet(self, name: str) -> Pet: + """Creates and shows a pet using the abstract factory""" pet = self.pet_factory(name) print(f"Here is your lovely {pet}") @@ -45,6 +79,14 @@ # Show pets with various factories def main() -> None: + """ + # A Shop that sells only cats + >>> cat_shop = PetShop(Cat) + >>> pet = cat_shop.buy_pet("Lucy") + Here is your lovely Cat<Lucy> + >>> pet.speak() + meow + """ if __name__ == "__main__": @@ -54,4 +96,4 @@ shop = PetShop(random_animal) import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/abstract_factory.py
Add docstrings to improve collaboration
from __future__ import annotations from typing import Any class Prototype: def __init__(self, value: str = "default", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> Prototype: # Python in Practice, Mark Summerfield # copy.deepcopy can be used instead of next line. obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) -> dict[str, Prototype]: return self._objects def register_object(self, name: str, obj: Prototype) -> None: self._objects[name] = obj def unregister_object(self, name: str) -> None: del self._objects[name] def main() -> None: if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,25 @@+""" +*What is this pattern about? +This patterns aims to reduce the number of classes required by an +application. Instead of relying on subclasses it creates objects by +copying a prototypical instance at run-time. + +This is useful as it makes it easier to derive new kinds of objects, +when instances of the class have only a few different combinations of +state, and when instantiation is expensive. + +*What does this example do? +When the number of prototypes in an application can vary, it can be +useful to keep a Dispatcher (aka, Registry or Manager). This allows +clients to query the Dispatcher for a prototype before cloning a new +instance. + +Below provides an example of such Dispatcher, which contains three +copies of the prototype: 'default', 'objecta' and 'objectb'. + +*TL;DR +Creates new object instances by cloning prototype. +""" from __future__ import annotations @@ -10,6 +32,7 @@ self.__dict__.update(attrs) def clone(self, **attrs: Any) -> Prototype: + """Clone a prototype and update inner attributes dictionary""" # Python in Practice, Mark Summerfield # copy.deepcopy can be used instead of next line. obj = self.__class__(**self.__dict__) @@ -22,19 +45,39 @@ self._objects = {} def get_objects(self) -> dict[str, Prototype]: + """Get all objects""" return self._objects def register_object(self, name: str, obj: Prototype) -> None: + """Register an object""" self._objects[name] = obj def unregister_object(self, name: str) -> None: + """Unregister an object""" del self._objects[name] def main() -> None: + """ + >>> dispatcher = PrototypeDispatcher() + >>> prototype = Prototype() + + >>> d = prototype.clone() + >>> a = prototype.clone(value='a-value', category='a') + >>> b = a.clone(value='b-value', is_checked=True) + >>> dispatcher.register_object('objecta', a) + >>> dispatcher.register_object('objectb', b) + >>> dispatcher.register_object('default', d) + + >>> [{n: p.value} for n, p in dispatcher.get_objects().items()] + [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] + + >>> print(b.category, b.is_checked) + a True + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/prototype.py
Document this script properly
from typing import Dict class Borg: _shared_state: Dict[str, str] = {} def __init__(self) -> None: self.__dict__ = self._shared_state class YourBorg(Borg): def __init__(self, state: str = None) -> None: super().__init__() if state: self.state = state else: # initiate the first instance with default state if not hasattr(self, "state"): self.state = "Init" def __str__(self) -> str: return self.state def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,37 @@+""" +*What is this pattern about? +The Borg pattern (also known as the Monostate pattern) is a way to +implement singleton behavior, but instead of having only one instance +of a class, there are multiple instances that share the same state. In +other words, the focus is on sharing state instead of sharing instance +identity. + +*What does this example do? +To understand the implementation of this pattern in Python, it is +important to know that, in Python, instance attributes are stored in a +attribute dictionary called __dict__. Usually, each instance will have +its own dictionary, but the Borg pattern modifies this so that all +instances have the same dictionary. +In this example, the __shared_state attribute will be the dictionary +shared between all instances, and this is ensured by assigning +__shared_state to the __dict__ variable when initializing a new +instance (i.e., in the __init__ method). Other attributes are usually +added to the instance's attribute dictionary, but, since the attribute +dictionary itself is shared (which is __shared_state), all other +attributes will also be shared. + +*Where is the pattern used practically? +Sharing state is useful in applications like managing database connections: +https://github.com/onetwopunch/pythonDbTemplate/blob/master/database.py + +*References: +- https://fkromer.github.io/python-pattern-references/design/#singleton +- https://learning.oreilly.com/library/view/python-cookbook/0596001673/ch05s23.html +- http://www.aleax.it/5ep.html + +*TL;DR +Provides singleton-like behavior sharing state between instances. +""" from typing import Dict @@ -24,9 +58,54 @@ def main(): + """ + >>> rm1 = YourBorg() + >>> rm2 = YourBorg() + + >>> rm1.state = 'Idle' + >>> rm2.state = 'Running' + + >>> print('rm1: {0}'.format(rm1)) + rm1: Running + >>> print('rm2: {0}'.format(rm2)) + rm2: Running + + # When the `state` attribute is modified from instance `rm2`, + # the value of `state` in instance `rm1` also changes + >>> rm2.state = 'Zombie' + + >>> print('rm1: {0}'.format(rm1)) + rm1: Zombie + >>> print('rm2: {0}'.format(rm2)) + rm2: Zombie + + # Even though `rm1` and `rm2` share attributes, the instances are not the same + >>> rm1 is rm2 + False + + # New instances also get the same shared state + >>> rm3 = YourBorg() + + >>> print('rm1: {0}'.format(rm1)) + rm1: Zombie + >>> print('rm2: {0}'.format(rm2)) + rm2: Zombie + >>> print('rm3: {0}'.format(rm3)) + rm3: Zombie + + # A new instance can explicitly change the state during creation + >>> rm4 = YourBorg('Running') + + >>> print('rm4: {0}'.format(rm4)) + rm4: Running + + # Existing instances reflect that change as well + >>> print('rm3: {0}'.format(rm3)) + rm3: Running + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/borg.py
Add professional docstrings to my codebase
from __future__ import annotations class Provider: def __init__(self) -> None: self.msg_queue = [] self.subscribers = {} def notify(self, msg: str) -> None: self.msg_queue.append(msg) def subscribe(self, msg: str, subscriber: Subscriber) -> None: self.subscribers.setdefault(msg, []).append(subscriber) def unsubscribe(self, msg: str, subscriber: Subscriber) -> None: self.subscribers[msg].remove(subscriber) def update(self) -> None: for msg in self.msg_queue: for sub in self.subscribers.get(msg, []): sub.run(msg) self.msg_queue = [] class Publisher: def __init__(self, msg_center: Provider) -> None: self.provider = msg_center def publish(self, msg: str) -> None: self.provider.notify(msg) class Subscriber: def __init__(self, name: str, msg_center: Provider) -> None: self.name = name self.provider = msg_center def subscribe(self, msg: str) -> None: self.provider.subscribe(msg, self) def unsubscribe(self, msg: str) -> None: self.provider.unsubscribe(msg, self) def run(self, msg: str) -> None: print(f"{self.name} got {msg}") def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,8 @@+""" +Reference: +http://www.slideshare.net/ishraqabd/publish-subscribe-model-overview-13368808 +Author: https://github.com/HanWenfang +""" from __future__ import annotations @@ -47,9 +52,44 @@ def main(): + """ + >>> message_center = Provider() + + >>> fftv = Publisher(message_center) + + >>> jim = Subscriber("jim", message_center) + >>> jim.subscribe("cartoon") + >>> jack = Subscriber("jack", message_center) + >>> jack.subscribe("music") + >>> gee = Subscriber("gee", message_center) + >>> gee.subscribe("movie") + >>> vani = Subscriber("vani", message_center) + >>> vani.subscribe("movie") + >>> vani.unsubscribe("movie") + + # Note that no one subscribed to `ads` + # and that vani changed their mind + + >>> fftv.publish("cartoon") + >>> fftv.publish("music") + >>> fftv.publish("ads") + >>> fftv.publish("movie") + >>> fftv.publish("cartoon") + >>> fftv.publish("cartoon") + >>> fftv.publish("movie") + >>> fftv.publish("blank") + + >>> message_center.update() + jim got cartoon + jack got music + gee got movie + jim got cartoon + jim got cartoon + gee got movie + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/publish_subscribe.py
Improve my code by adding docstrings
import datetime from typing import Callable class ConstructorInjection: def __init__(self, time_provider: Callable) -> None: self.time_provider = time_provider def get_current_time_as_html_fragment(self) -> str: current_time = self.time_provider() current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format( current_time ) return current_time_as_html_fragment class ParameterInjection: def __init__(self) -> None: pass def get_current_time_as_html_fragment(self, time_provider: Callable) -> str: current_time = time_provider() current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format( current_time ) return current_time_as_html_fragment class SetterInjection: def __init__(self): pass def set_time_provider(self, time_provider: Callable): self.time_provider = time_provider def get_current_time_as_html_fragment(self): current_time = self.time_provider() current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format( current_time ) return current_time_as_html_fragment def production_code_time_provider() -> str: current_time = datetime.datetime.now() current_time_formatted = f"{current_time.hour}:{current_time.minute}" return current_time_formatted def midnight_time_provider() -> str: return "24:01" def main(): if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
--- +++ @@ -1,3 +1,27 @@+""" +Dependency Injection (DI) is a technique whereby one object supplies the dependencies (services) +to another object (client). +It allows to decouple objects: no need to change client code simply because an object it depends on +needs to be changed to a different one. (Open/Closed principle) + +Port of the Java example of Dependency Injection" in +"xUnit Test Patterns - Refactoring Test Code" by Gerard Meszaros +(ISBN-10: 0131495054, ISBN-13: 978-0131495050) + +In the following example `time_provider` (service) is embedded into TimeDisplay (client). +If such service performed an expensive operation you would like to substitute or mock it in tests. + +class TimeDisplay(object): + + def __init__(self): + self.time_provider = datetime.datetime.now + + def get_current_time_as_html_fragment(self): + current_time = self.time_provider() + current_time_as_html_fragment = "<span class=\"tinyBoldText\">{}</span>".format(current_time) + return current_time_as_html_fragment + +""" import datetime from typing import Callable @@ -28,6 +52,7 @@ class SetterInjection: + """Setter Injection""" def __init__(self): pass @@ -44,19 +69,48 @@ def production_code_time_provider() -> str: + """ + Production code version of the time provider (just a wrapper for formatting + datetime for this example). + """ current_time = datetime.datetime.now() current_time_formatted = f"{current_time.hour}:{current_time.minute}" return current_time_formatted def midnight_time_provider() -> str: + """Hard-coded stub""" return "24:01" def main(): + """ + >>> time_with_ci1 = ConstructorInjection(midnight_time_provider) + >>> time_with_ci1.get_current_time_as_html_fragment() + '<span class="tinyBoldText">24:01</span>' + + >>> time_with_ci2 = ConstructorInjection(production_code_time_provider) + >>> time_with_ci2.get_current_time_as_html_fragment() + '<span class="tinyBoldText">...</span>' + + >>> time_with_pi = ParameterInjection() + >>> time_with_pi.get_current_time_as_html_fragment(midnight_time_provider) + '<span class="tinyBoldText">24:01</span>' + + >>> time_with_si = SetterInjection() + + >>> time_with_si.get_current_time_as_html_fragment() + Traceback (most recent call last): + ... + AttributeError: 'SetterInjection' object has no attribute 'time_provider' + + >>> time_with_si.set_time_provider(midnight_time_provider) + >>> time_with_si.get_current_time_as_html_fragment() + '<span class="tinyBoldText">24:01</span>' + """ if __name__ == "__main__": import doctest - doctest.testmod(optionflags=doctest.ELLIPSIS)+ doctest.testmod(optionflags=doctest.ELLIPSIS)
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/dependency_injection.py
Add concise docstrings to each method
from typing import Callable, TypeVar, Any, Dict T = TypeVar("T") class Dog: def __init__(self) -> None: self.name = "Dog" def bark(self) -> str: return "woof!" class Cat: def __init__(self) -> None: self.name = "Cat" def meow(self) -> str: return "meow!" class Human: def __init__(self) -> None: self.name = "Human" def speak(self) -> str: return "'hello'" class Car: def __init__(self) -> None: self.name = "Car" def make_noise(self, octane_level: int) -> str: return f"vroom{'!' * octane_level}" class Adapter: def __init__(self, obj: T, **adapted_methods: Callable[..., Any]) -> None: self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr: str) -> Any: return getattr(self.obj, attr) def original_dict(self) -> Dict[str, Any]: return self.obj.__dict__ def main(): if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
--- +++ @@ -1,3 +1,32 @@+""" +*What is this pattern about? +The Adapter pattern provides a different interface for a class. We can +think about it as a cable adapter that allows you to charge a phone +somewhere that has outlets in a different shape. Following this idea, +the Adapter pattern is useful to integrate classes that couldn't be +integrated due to their incompatible interfaces. + +*What does this example do? + +The example has classes that represent entities (Dog, Cat, Human, Car) +that make different noises. The Adapter class provides a different +interface to the original methods that make such noises. So the +original interfaces (e.g., bark and meow) are available under a +different name: make_noise. + +*Where is the pattern used practically? +The Grok framework uses adapters to make objects work with a +particular API without modifying the objects themselves: +http://grok.zope.org/doc/current/grok_overview.html#adapters + +*References: +http://ginstrom.com/scribbles/2008/11/06/generic-adapter-class-in-python/ +https://sourcemaking.com/design_patterns/adapter +http://python-3-patterns-idioms-test.readthedocs.io/en/latest/ChangeInterface.html#adapter + +*TL;DR +Allows the interface of an existing class to be used as another interface. +""" from typing import Callable, TypeVar, Any, Dict @@ -37,22 +66,60 @@ class Adapter: + """Adapts an object by replacing methods. + + Usage + ------ + dog = Dog() + dog = Adapter(dog, make_noise=dog.bark) + """ def __init__(self, obj: T, **adapted_methods: Callable[..., Any]) -> None: + """We set the adapted methods in the object's dict.""" self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr: str) -> Any: + """All non-adapted calls are passed to the object.""" return getattr(self.obj, attr) def original_dict(self) -> Dict[str, Any]: + """Print original object dict.""" return self.obj.__dict__ def main(): + """ + >>> objects = [] + >>> dog = Dog() + >>> print(dog.__dict__) + {'name': 'Dog'} + + >>> objects.append(Adapter(dog, make_noise=dog.bark)) + + >>> objects[0].__dict__['obj'], objects[0].__dict__['make_noise'] + (<...Dog object at 0x...>, <bound method Dog.bark of <...Dog object at 0x...>>) + + >>> print(objects[0].original_dict()) + {'name': 'Dog'} + + >>> cat = Cat() + >>> objects.append(Adapter(cat, make_noise=cat.meow)) + >>> human = Human() + >>> objects.append(Adapter(human, make_noise=human.speak)) + >>> car = Car() + >>> objects.append(Adapter(car, make_noise=lambda: car.make_noise(3))) + + >>> for obj in objects: + ... print("A {0} goes {1}".format(obj.name, obj.make_noise())) + A Dog goes woof! + A Cat goes meow! + A Human goes 'hello' + A Car goes vroom!!! + """ if __name__ == "__main__": import doctest - doctest.testmod(optionflags=doctest.ELLIPSIS)+ doctest.testmod(optionflags=doctest.ELLIPSIS)
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/adapter.py
Can you add docstrings to this Python file?
from typing import Union # ConcreteImplementor 1/2 class DrawingAPI1: def draw_circle(self, x: int, y: int, radius: float) -> None: print(f"API1.circle at {x}:{y} radius {radius}") # ConcreteImplementor 2/2 class DrawingAPI2: def draw_circle(self, x: int, y: int, radius: float) -> None: print(f"API2.circle at {x}:{y} radius {radius}") # Refined Abstraction class CircleShape: def __init__( self, x: int, y: int, radius: int, drawing_api: Union[DrawingAPI2, DrawingAPI1] ) -> None: self._x = x self._y = y self._radius = radius self._drawing_api = drawing_api # low-level i.e. Implementation specific def draw(self) -> None: self._drawing_api.draw_circle(self._x, self._y, self._radius) # high-level i.e. Abstraction specific def scale(self, pct: float) -> None: self._radius *= pct def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,10 @@+""" +*References: +http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python + +*TL;DR +Decouples an abstraction from its implementation. +""" from typing import Union @@ -33,9 +40,18 @@ def main(): + """ + >>> shapes = (CircleShape(1, 2, 3, DrawingAPI1()), CircleShape(5, 7, 11, DrawingAPI2())) + + >>> for shape in shapes: + ... shape.scale(2.5) + ... shape.draw() + API1.circle at 1:2 radius 7.5 + API2.circle at 5:7 radius 27.5 + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/bridge.py
Write reusable docstrings
from __future__ import annotations class State: def scan(self) -> None: self.pos += 1 if self.pos == len(self.stations): self.pos = 0 print(f"Scanning... Station is {self.stations[self.pos]} {self.name}") class AmState(State): def __init__(self, radio: Radio) -> None: self.radio = radio self.stations = ["1250", "1380", "1510"] self.pos = 0 self.name = "AM" def toggle_amfm(self) -> None: print("Switching to FM") self.radio.state = self.radio.fmstate class FmState(State): def __init__(self, radio: Radio) -> None: self.radio = radio self.stations = ["81.3", "89.1", "103.9"] self.pos = 0 self.name = "FM" def toggle_amfm(self) -> None: print("Switching to AM") self.radio.state = self.radio.amstate class Radio: def __init__(self) -> None: self.amstate = AmState(self) self.fmstate = FmState(self) self.state = self.amstate def toggle_amfm(self) -> None: self.state.toggle_amfm() def scan(self) -> None: self.state.scan() def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,10 +1,21 @@+""" +Implementation of the state pattern + +http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/ + +*TL;DR +Implements state as a derived class of the state pattern interface. +Implements state transitions by invoking methods from the pattern's superclass. +""" from __future__ import annotations class State: + """Base state. This is to share functionality""" def scan(self) -> None: + """Scan the dial to the next station""" self.pos += 1 if self.pos == len(self.stations): self.pos = 0 @@ -36,8 +47,10 @@ class Radio: + """A radio. It has a scan button, and an AM/FM toggle switch.""" def __init__(self) -> None: + """We have an AM state and an FM state""" self.amstate = AmState(self) self.fmstate = FmState(self) self.state = self.amstate @@ -50,9 +63,27 @@ def main(): + """ + >>> radio = Radio() + >>> actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2 + >>> actions *= 2 + + >>> for action in actions: + ... action() + Scanning... Station is 1380 AM + Scanning... Station is 1510 AM + Switching to FM + Scanning... Station is 89.1 FM + Scanning... Station is 103.9 FM + Scanning... Station is 81.3 FM + Scanning... Station is 89.1 FM + Switching to AM + Scanning... Station is 1250 AM + Scanning... Station is 1380 AM + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/state.py
Add documentation for all methods
from abc import ABC, abstractmethod from typing import Optional, Tuple class Handler(ABC): def __init__(self, successor: Optional["Handler"] = None): self.successor = successor def handle(self, request: int) -> None: res = self.check_range(request) if not res and self.successor: self.successor.handle(request) @abstractmethod def check_range(self, request: int) -> Optional[bool]: class ConcreteHandler0(Handler): @staticmethod def check_range(request: int) -> Optional[bool]: if 0 <= request < 10: print(f"request {request} handled in handler 0") return True return None class ConcreteHandler1(Handler): start, end = 10, 20 def check_range(self, request: int) -> Optional[bool]: if self.start <= request < self.end: print(f"request {request} handled in handler 1") return True return None class ConcreteHandler2(Handler): def check_range(self, request: int) -> Optional[bool]: start, end = self.get_interval_from_db() if start <= request < end: print(f"request {request} handled in handler 2") return True return None @staticmethod def get_interval_from_db() -> Tuple[int, int]: return (20, 30) class FallbackHandler(Handler): @staticmethod def check_range(request: int) -> Optional[bool]: print(f"end of chain, no handler for {request}") return False def main(): if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
--- +++ @@ -1,3 +1,26 @@+""" +*What is this pattern about? + +The Chain of responsibility is an object oriented version of the +`if ... elif ... elif ... else ...` idiom, with the +benefit that the condition–action blocks can be dynamically rearranged +and reconfigured at runtime. + +This pattern aims to decouple the senders of a request from its +receivers by allowing request to move through chained +receivers until it is handled. + +Request receiver in simple form keeps a reference to a single successor. +As a variation some receivers may be capable of sending requests out +in several directions, forming a `tree of responsibility`. + +*Examples in Python ecosystem: +Django Middleware: https://docs.djangoproject.com/en/stable/topics/http/middleware/ +The middleware components act as a chain where each processes the request/response. + +*TL;DR +Allow a request to pass down a chain of receivers until it is handled. +""" from abc import ABC, abstractmethod from typing import Optional, Tuple @@ -8,15 +31,26 @@ self.successor = successor def handle(self, request: int) -> None: + """ + Handle request and stop. + If can't - call next handler in chain. + + As an alternative you might even in case of success + call the next handler. + """ res = self.check_range(request) if not res and self.successor: self.successor.handle(request) @abstractmethod def check_range(self, request: int) -> Optional[bool]: + """Compare passed value to predefined interval""" class ConcreteHandler0(Handler): + """Each handler can be different. + Be simple and static... + """ @staticmethod def check_range(request: int) -> Optional[bool]: @@ -27,6 +61,7 @@ class ConcreteHandler1(Handler): + """... With it's own internal state""" start, end = 10, 20 @@ -38,6 +73,7 @@ class ConcreteHandler2(Handler): + """... With helper methods.""" def check_range(self, request: int) -> Optional[bool]: start, end = self.get_interval_from_db() @@ -59,9 +95,29 @@ def main(): + """ + >>> h0 = ConcreteHandler0() + >>> h1 = ConcreteHandler1() + >>> h2 = ConcreteHandler2(FallbackHandler()) + >>> h0.successor = h1 + >>> h1.successor = h2 + + >>> requests = [2, 5, 14, 22, 18, 3, 35, 27, 20] + >>> for request in requests: + ... h0.handle(request) + request 2 handled in handler 0 + request 5 handled in handler 0 + request 14 handled in handler 1 + request 22 handled in handler 2 + request 18 handled in handler 1 + request 3 handled in handler 0 + end of chain, no handler for 35 + request 27 handled in handler 2 + request 20 handled in handler 2 + """ if __name__ == "__main__": import doctest - doctest.testmod(optionflags=doctest.ELLIPSIS)+ doctest.testmod(optionflags=doctest.ELLIPSIS)
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/chain_of_responsibility.py
Write docstrings including parameters and return values
from abc import ABC, abstractmethod import random class AbstractExpert(ABC): @abstractmethod def __init__(self, blackboard) -> None: self.blackboard = blackboard @property @abstractmethod def is_eager_to_contribute(self) -> int: raise NotImplementedError("Must provide implementation in subclass.") @abstractmethod def contribute(self) -> None: raise NotImplementedError("Must provide implementation in subclass.") class Blackboard: def __init__(self) -> None: self.experts: list = [] self.common_state = { "problems": 0, "suggestions": 0, "contributions": [], "progress": 0, # percentage, if 100 -> task is finished } def add_expert(self, expert: AbstractExpert) -> None: self.experts.append(expert) class Controller: def __init__(self, blackboard: Blackboard) -> None: self.blackboard = blackboard def run_loop(self): while self.blackboard.common_state["progress"] < 100: for expert in self.blackboard.experts: if expert.is_eager_to_contribute: expert.contribute() return self.blackboard.common_state["contributions"] class Student(AbstractExpert): def __init__(self, blackboard) -> None: super().__init__(blackboard) @property def is_eager_to_contribute(self) -> bool: return True def contribute(self) -> None: self.blackboard.common_state["problems"] += random.randint(1, 10) self.blackboard.common_state["suggestions"] += random.randint(1, 10) self.blackboard.common_state["contributions"] += [self.__class__.__name__] self.blackboard.common_state["progress"] += random.randint(1, 2) class Scientist(AbstractExpert): def __init__(self, blackboard) -> None: super().__init__(blackboard) @property def is_eager_to_contribute(self) -> int: return random.randint(0, 1) def contribute(self) -> None: self.blackboard.common_state["problems"] += random.randint(10, 20) self.blackboard.common_state["suggestions"] += random.randint(10, 20) self.blackboard.common_state["contributions"] += [self.__class__.__name__] self.blackboard.common_state["progress"] += random.randint(10, 30) class Professor(AbstractExpert): def __init__(self, blackboard) -> None: super().__init__(blackboard) @property def is_eager_to_contribute(self) -> bool: return True if self.blackboard.common_state["problems"] > 100 else False def contribute(self) -> None: self.blackboard.common_state["problems"] += random.randint(1, 2) self.blackboard.common_state["suggestions"] += random.randint(10, 20) self.blackboard.common_state["contributions"] += [self.__class__.__name__] self.blackboard.common_state["progress"] += random.randint(10, 100) def main(): if __name__ == "__main__": random.seed(1234) # for deterministic doctest outputs import doctest doctest.testmod()
--- +++ @@ -1,9 +1,20 @@+""" +@author: Eugene Duboviy <eugene.dubovoy@gmail.com> | github.com/duboviy + +In Blackboard pattern several specialised sub-systems (knowledge sources) +assemble their knowledge to build a possibly partial or approximate solution. +In this way, the sub-systems work together to solve the problem, +where the solution is the sum of its parts. + +https://en.wikipedia.org/wiki/Blackboard_system +""" from abc import ABC, abstractmethod import random class AbstractExpert(ABC): + """Abstract class for experts in the blackboard system.""" @abstractmethod def __init__(self, blackboard) -> None: @@ -20,6 +31,7 @@ class Blackboard: + """The blackboard system that holds the common state.""" def __init__(self) -> None: self.experts: list = [] @@ -35,11 +47,16 @@ class Controller: + """The controller that manages the blackboard system.""" def __init__(self, blackboard: Blackboard) -> None: self.blackboard = blackboard def run_loop(self): + """ + This function is a loop that runs until the progress reaches 100. + It checks if an expert is eager to contribute and then calls its contribute method. + """ while self.blackboard.common_state["progress"] < 100: for expert in self.blackboard.experts: if expert.is_eager_to_contribute: @@ -48,6 +65,7 @@ class Student(AbstractExpert): + """Concrete class for a student expert.""" def __init__(self, blackboard) -> None: super().__init__(blackboard) @@ -64,6 +82,7 @@ class Scientist(AbstractExpert): + """Concrete class for a scientist expert.""" def __init__(self, blackboard) -> None: super().__init__(blackboard) @@ -95,10 +114,29 @@ def main(): + """ + >>> blackboard = Blackboard() + >>> blackboard.add_expert(Student(blackboard)) + >>> blackboard.add_expert(Scientist(blackboard)) + >>> blackboard.add_expert(Professor(blackboard)) + + >>> c = Controller(blackboard) + >>> contributions = c.run_loop() + + >>> from pprint import pprint + >>> pprint(contributions) + ['Student', + 'Scientist', + 'Student', + 'Scientist', + 'Student', + 'Scientist', + 'Professor'] + """ if __name__ == "__main__": random.seed(1234) # for deterministic doctest outputs import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/other/blackboard.py
Add detailed docstrings explaining each function
from copy import copy, deepcopy from typing import Any, Callable, List, Type def memento(obj: Any, deep: bool = False) -> Callable: state = deepcopy(obj.__dict__) if deep else copy(obj.__dict__) def restore() -> None: obj.__dict__.clear() obj.__dict__.update(state) return restore class Transaction: deep = False states: List[Callable[[], None]] = [] def __init__(self, deep: bool, *targets: Any) -> None: self.deep = deep self.targets = targets self.commit() def commit(self) -> None: self.states = [memento(target, self.deep) for target in self.targets] def rollback(self) -> None: for a_state in self.states: a_state() def Transactional(method): def __init__(self, method: Callable) -> None: self.method = method def __get__(self, obj: Any, T: Type) -> Callable: def transaction(*args, **kwargs): state = memento(obj) try: return self.method(obj, *args, **kwargs) except Exception as e: state() raise e return transaction class NumObj: def __init__(self, value: int) -> None: self.value = value def __repr__(self) -> str: return f"<{self.__class__.__name__}: {self.value!r}>" def increment(self) -> None: self.value += 1 @Transactional def do_stuff(self) -> None: self.value = "1111" # <- invalid value self.increment() # <- will fail and rollback def main(): if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
--- +++ @@ -1,3 +1,9 @@+""" +http://code.activestate.com/recipes/413838-memento-closure/ + +*TL;DR +Provides the ability to restore an object to its previous state. +""" from copy import copy, deepcopy from typing import Any, Callable, List, Type @@ -14,6 +20,10 @@ class Transaction: + """A transaction guard. + + This is, in fact, just syntactic sugar around a memento closure. + """ deep = False states: List[Callable[[], None]] = [] @@ -32,11 +42,21 @@ def Transactional(method): + """Adds transactional semantics to methods. Methods decorated with + @Transactional will roll back to entry-state upon exceptions. + + :param method: The function to be decorated. + """ def __init__(self, method: Callable) -> None: self.method = method def __get__(self, obj: Any, T: Type) -> Callable: + """ + A decorator that makes a function transactional. + + :param method: The function to be decorated. + """ def transaction(*args, **kwargs): state = memento(obj) @@ -66,9 +86,60 @@ def main(): + """ + >>> num_obj = NumObj(-1) + >>> print(num_obj) + <NumObj: -1> + + >>> a_transaction = Transaction(True, num_obj) + + >>> try: + ... for i in range(3): + ... num_obj.increment() + ... print(num_obj) + ... a_transaction.commit() + ... print('-- committed') + ... for i in range(3): + ... num_obj.increment() + ... print(num_obj) + ... num_obj.value += 'x' # will fail + ... print(num_obj) + ... except Exception: + ... a_transaction.rollback() + ... print('-- rolled back') + <NumObj: 0> + <NumObj: 1> + <NumObj: 2> + -- committed + <NumObj: 3> + <NumObj: 4> + <NumObj: 5> + -- rolled back + + >>> print(num_obj) + <NumObj: 2> + + >>> print('-- now doing stuff ...') + -- now doing stuff ... + + >>> try: + ... num_obj.do_stuff() + ... except Exception: + ... print('-> doing stuff failed!') + ... import sys + ... import traceback + ... traceback.print_exc(file=sys.stdout) + -> doing stuff failed! + Traceback (most recent call last): + ... + TypeError: ...str...int... + + >>> print(num_obj) + <NumObj: 2> + """ if __name__ == "__main__": import doctest - doctest.testmod(optionflags=doctest.ELLIPSIS)+ doctest.testmod(optionflags=doctest.ELLIPSIS)
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/memento.py
Help me comply with documentation standards
from __future__ import annotations from typing import Any, Callable class Delegator: def __init__(self, delegate: Delegate) -> None: self.delegate = delegate def __getattr__(self, name: str) -> Any | Callable: attr = getattr(self.delegate, name) if not callable(attr): return attr def wrapper(*args, **kwargs): return attr(*args, **kwargs) return wrapper class Delegate: def __init__(self) -> None: self.p1 = 123 def do_something(self, something: str, kw=None) -> str: return f"Doing {something}{kw or ''}" if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,10 @@+""" +Reference: https://en.wikipedia.org/wiki/Delegation_pattern +Author: https://github.com/IuryAlves + +*TL;DR +Allows object composition to achieve the same code reuse as inheritance. +""" from __future__ import annotations @@ -5,6 +12,23 @@ class Delegator: + """ + >>> delegator = Delegator(Delegate()) + >>> delegator.p1 + 123 + >>> delegator.p2 + Traceback (most recent call last): + ... + AttributeError: 'Delegate' object has no attribute 'p2'. Did you mean: 'p1'? + >>> delegator.do_something("nothing") + 'Doing nothing' + >>> delegator.do_something("something", kw=", faif!") + 'Doing something, faif!' + >>> delegator.do_anything() + Traceback (most recent call last): + ... + AttributeError: 'Delegate' object has no attribute 'do_anything'. Did you mean: 'do_something'? + """ def __init__(self, delegate: Delegate) -> None: self.delegate = delegate @@ -32,4 +56,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/fundamental/delegation_pattern.py
Add docstrings to clarify complex logic
from typing import List, Union class HideFileCommand: def __init__(self) -> None: # an array of files hidden, to undo them as needed self._hidden_files: List[str] = [] def execute(self, filename: str) -> None: print(f"hiding {filename}") self._hidden_files.append(filename) def undo(self) -> None: filename = self._hidden_files.pop() print(f"un-hiding {filename}") class DeleteFileCommand: def __init__(self) -> None: # an array of deleted files, to undo them as needed self._deleted_files: List[str] = [] def execute(self, filename: str) -> None: print(f"deleting {filename}") self._deleted_files.append(filename) def undo(self) -> None: filename = self._deleted_files.pop() print(f"restoring {filename}") class MenuItem: def __init__(self, command: Union[HideFileCommand, DeleteFileCommand]) -> None: self._command = command def on_do_press(self, filename: str) -> None: self._command.execute(filename) def on_undo_press(self) -> None: self._command.undo() def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,32 @@+""" +Command pattern decouples the object invoking a job from the one who knows +how to do it. As mentioned in the GoF book, a good example is in menu items. +You have a menu that has lots of items. Each item is responsible for doing a +special thing and you want your menu item just call the execute method when +it is pressed. To achieve this you implement a command object with the execute +method for each menu item and pass to it. + +*About the example +We have a menu containing two items. Each item accepts a file name, one hides the file +and the other deletes it. Both items have an undo option. +Each item is a MenuItem class that accepts the corresponding command as input and executes +it's execute method when it is pressed. + +*TL;DR +Object oriented implementation of callback functions. + +*Examples in Python ecosystem: +Django HttpRequest (without execute method): +https://docs.djangoproject.com/en/2.1/ref/request-response/#httprequest-objects +""" from typing import List, Union class HideFileCommand: + """ + A command to hide a file given its name + """ def __init__(self) -> None: # an array of files hidden, to undo them as needed @@ -18,6 +42,9 @@ class DeleteFileCommand: + """ + A command to delete a file given its name + """ def __init__(self) -> None: # an array of deleted files, to undo them as needed @@ -33,6 +60,9 @@ class MenuItem: + """ + The invoker class. Here it is items in a menu. + """ def __init__(self, command: Union[HideFileCommand, DeleteFileCommand]) -> None: self._command = command @@ -45,9 +75,33 @@ def main(): + """ + >>> item1 = MenuItem(DeleteFileCommand()) + + >>> item2 = MenuItem(HideFileCommand()) + + # create a file named `test-file` to work with + >>> test_file_name = 'test-file' + + # deleting `test-file` + >>> item1.on_do_press(test_file_name) + deleting test-file + + # restoring `test-file` + >>> item1.on_undo_press() + restoring test-file + + # hiding `test-file` + >>> item2.on_do_press(test_file_name) + hiding test-file + + # un-hiding `test-file` + >>> item2.on_undo_press() + un-hiding test-file + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/command.py
Generate consistent docstrings
from abc import abstractmethod from typing import Union class Specification: def and_specification(self, candidate): raise NotImplementedError() def or_specification(self, candidate): raise NotImplementedError() def not_specification(self): raise NotImplementedError() @abstractmethod def is_satisfied_by(self, candidate): pass class CompositeSpecification(Specification): @abstractmethod def is_satisfied_by(self, candidate): pass def and_specification(self, candidate: "Specification") -> "AndSpecification": return AndSpecification(self, candidate) def or_specification(self, candidate: "Specification") -> "OrSpecification": return OrSpecification(self, candidate) def not_specification(self) -> "NotSpecification": return NotSpecification(self) class AndSpecification(CompositeSpecification): def __init__(self, one: "Specification", other: "Specification") -> None: self._one: Specification = one self._other: Specification = other def is_satisfied_by(self, candidate: Union["User", str]) -> bool: return bool( self._one.is_satisfied_by(candidate) and self._other.is_satisfied_by(candidate) ) class OrSpecification(CompositeSpecification): def __init__(self, one: "Specification", other: "Specification") -> None: self._one: Specification = one self._other: Specification = other def is_satisfied_by(self, candidate: Union["User", str]): return bool( self._one.is_satisfied_by(candidate) or self._other.is_satisfied_by(candidate) ) class NotSpecification(CompositeSpecification): def __init__(self, wrapped: "Specification"): self._wrapped: Specification = wrapped def is_satisfied_by(self, candidate: Union["User", str]): return bool(not self._wrapped.is_satisfied_by(candidate)) class User: def __init__(self, super_user: bool = False) -> None: self.super_user = super_user class UserSpecification(CompositeSpecification): def is_satisfied_by(self, candidate: Union["User", str]) -> bool: return isinstance(candidate, User) class SuperUserSpecification(CompositeSpecification): def is_satisfied_by(self, candidate: "User") -> bool: return getattr(candidate, "super_user", False) def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,9 @@+""" +@author: Gordeev Andrey <gordeev.and.and@gmail.com> + +*TL;DR +Provides recombination business logic by chaining together using boolean logic. +""" from abc import abstractmethod from typing import Union @@ -81,9 +87,24 @@ def main(): + """ + >>> andrey = User() + >>> ivan = User(super_user=True) + >>> vasiliy = 'not User instance' + + >>> root_specification = UserSpecification().and_specification(SuperUserSpecification()) + + # Is specification satisfied by <name> + >>> root_specification.is_satisfied_by(andrey), 'andrey' + (False, 'andrey') + >>> root_specification.is_satisfied_by(ivan), 'ivan' + (True, 'ivan') + >>> root_specification.is_satisfied_by(vasiliy), 'vasiliy' + (False, 'vasiliy') + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/specification.py
Create docstrings for all classes and functions
from abc import ABC, abstractmethod from typing import List class Graphic(ABC): @abstractmethod def render(self) -> None: raise NotImplementedError("You should implement this!") class CompositeGraphic(Graphic): def __init__(self) -> None: self.graphics: List[Graphic] = [] def render(self) -> None: for graphic in self.graphics: graphic.render() def add(self, graphic: Graphic) -> None: self.graphics.append(graphic) def remove(self, graphic: Graphic) -> None: self.graphics.remove(graphic) class Ellipse(Graphic): def __init__(self, name: str) -> None: self.name = name def render(self) -> None: print(f"Ellipse: {self.name}") def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,30 @@+""" +*What is this pattern about? +The composite pattern describes a group of objects that is treated the +same way as a single instance of the same type of object. The intent of +a composite is to "compose" objects into tree structures to represent +part-whole hierarchies. Implementing the composite pattern lets clients +treat individual objects and compositions uniformly. + +*What does this example do? +The example implements a graphic class,which can be either an ellipse +or a composition of several graphics. Every graphic can be printed. + +*Where is the pattern used practically? +In graphics editors a shape can be basic or complex. An example of a +simple shape is a line, where a complex shape is a rectangle which is +made of four line objects. Since shapes have many operations in common +such as rendering the shape to screen, and since shapes follow a +part-whole hierarchy, composite pattern can be used to enable the +program to deal with all shapes uniformly. + +*References: +https://en.wikipedia.org/wiki/Composite_pattern +https://infinitescript.com/2014/10/the-23-gang-of-three-design-patterns/ + +*TL;DR +Describes a group of objects that is treated as a single instance. +""" from abc import ABC, abstractmethod from typing import List @@ -33,9 +60,34 @@ def main(): + """ + >>> ellipse1 = Ellipse("1") + >>> ellipse2 = Ellipse("2") + >>> ellipse3 = Ellipse("3") + >>> ellipse4 = Ellipse("4") + + >>> graphic1 = CompositeGraphic() + >>> graphic2 = CompositeGraphic() + + >>> graphic1.add(ellipse1) + >>> graphic1.add(ellipse2) + >>> graphic1.add(ellipse3) + >>> graphic2.add(ellipse4) + + >>> graphic = CompositeGraphic() + + >>> graphic.add(graphic1) + >>> graphic.add(graphic2) + + >>> graphic.render() + Ellipse: 1 + Ellipse: 2 + Ellipse: 3 + Ellipse: 4 + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/composite.py
Document classes and their methods
def count_to(count: int): numbers = ["one", "two", "three", "four", "five"] yield from numbers[:count] # Test the generator def count_to_two() -> None: return count_to(2) def count_to_five() -> None: return count_to(5) def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,14 @@+""" +http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/ +Implementation of the iterator pattern with a generator + +*TL;DR +Traverses a container and accesses the container's elements. +""" def count_to(count: int): + """Counts by word numbers, up to a maximum of five""" numbers = ["one", "two", "three", "four", "five"] yield from numbers[:count] @@ -15,9 +23,25 @@ def main(): + """ + # Counting to two... + >>> for number in count_to_two(): + ... print(number) + one + two + + # Counting to five... + >>> for number in count_to_five(): + ... print(number) + one + two + three + four + five + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/iterator.py
Write docstrings for algorithm functions
# observer.py from __future__ import annotations from typing import List class Observer: def update(self, subject: Subject) -> None: pass class Subject: _observers: List[Observer] def __init__(self) -> None: self._observers = [] def attach(self, observer: Observer) -> None: if observer not in self._observers: self._observers.append(observer) def detach(self, observer: Observer) -> None: try: self._observers.remove(observer) except ValueError: pass def notify(self) -> None: for observer in self._observers: observer.update(self) class Data(Subject): def __init__(self, name: str = "") -> None: super().__init__() self.name = name self._data = 0 @property def data(self) -> int: return self._data @data.setter def data(self, value: int) -> None: self._data = value self.notify() class HexViewer: def update(self, subject: Data) -> None: print(f"HexViewer: Subject {subject.name} has data 0x{subject.data:x}") class DecimalViewer: def update(self, subject: Data) -> None: print(f"DecimalViewer: Subject {subject.name} has data {subject.data}") def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,13 @@+""" +http://code.activestate.com/recipes/131499-observer-pattern/ + +*TL;DR +Maintains a list of dependents and notifies them of any state changes. + +*Examples in Python ecosystem: +Django Signals: https://docs.djangoproject.com/en/3.1/topics/signals/ +Flask Signals: https://flask.palletsprojects.com/en/1.1.x/signals/ +""" # observer.py @@ -6,6 +16,12 @@ class Observer: def update(self, subject: Subject) -> None: + """ + Receive update from the subject. + + Args: + subject (Subject): The subject instance sending the update. + """ pass @@ -13,19 +29,37 @@ _observers: List[Observer] def __init__(self) -> None: + """ + Initialize the subject with an empty observer list. + """ self._observers = [] def attach(self, observer: Observer) -> None: + """ + Attach an observer to the subject. + + Args: + observer (Observer): The observer instance to attach. + """ if observer not in self._observers: self._observers.append(observer) def detach(self, observer: Observer) -> None: + """ + Detach an observer from the subject. + + Args: + observer (Observer): The observer instance to detach. + """ try: self._observers.remove(observer) except ValueError: pass def notify(self) -> None: + """ + Notify all attached observers by calling their update method. + """ for observer in self._observers: observer.update(self) @@ -57,9 +91,45 @@ def main(): + """ + >>> data1 = Data('Data 1') + >>> data2 = Data('Data 2') + >>> view1 = DecimalViewer() + >>> view2 = HexViewer() + >>> data1.attach(view1) + >>> data1.attach(view2) + >>> data2.attach(view2) + >>> data2.attach(view1) + + >>> data1.data = 10 + DecimalViewer: Subject Data 1 has data 10 + HexViewer: Subject Data 1 has data 0xa + + >>> data2.data = 15 + HexViewer: Subject Data 2 has data 0xf + DecimalViewer: Subject Data 2 has data 15 + + >>> data1.data = 3 + DecimalViewer: Subject Data 1 has data 3 + HexViewer: Subject Data 1 has data 0x3 + + >>> data2.data = 5 + HexViewer: Subject Data 2 has data 0x5 + DecimalViewer: Subject Data 2 has data 5 + + # Detach HexViewer from data1 and data2 + >>> data1.detach(view2) + >>> data2.detach(view2) + + >>> data1.data = 10 + DecimalViewer: Subject Data 1 has data 10 + + >>> data2.data = 15 + DecimalViewer: Subject Data 2 has data 15 + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/observer.py
Create simple docstrings for beginners
class TextTag: def __init__(self, text: str) -> None: self._text = text def render(self) -> str: return self._text class BoldWrapper(TextTag): def __init__(self, wrapped: TextTag) -> None: self._wrapped = wrapped def render(self) -> str: return f"<b>{self._wrapped.render()}</b>" class ItalicWrapper(TextTag): def __init__(self, wrapped: TextTag) -> None: self._wrapped = wrapped def render(self) -> str: return f"<i>{self._wrapped.render()}</i>" def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,32 @@+""" +*What is this pattern about? +The Decorator pattern is used to dynamically add a new feature to an +object without changing its implementation. It differs from +inheritance because the new feature is added only to that particular +object, not to the entire subclass. + +*What does this example do? +This example shows a way to add formatting options (boldface and +italic) to a text by appending the corresponding tags (<b> and +<i>). Also, we can see that decorators can be applied one after the other, +since the original text is passed to the bold wrapper, which in turn +is passed to the italic wrapper. + +*Where is the pattern used practically? +The Grok framework uses decorators to add functionalities to methods, +like permissions or subscription to an event: +http://grok.zope.org/doc/current/reference/decorators.html + +*References: +https://sourcemaking.com/design_patterns/decorator + +*TL;DR +Adds behaviour to object without affecting its class. +""" class TextTag: + """Represents a base text tag""" def __init__(self, text: str) -> None: self._text = text @@ -10,6 +36,7 @@ class BoldWrapper(TextTag): + """Wraps a tag in <b>""" def __init__(self, wrapped: TextTag) -> None: self._wrapped = wrapped @@ -19,6 +46,7 @@ class ItalicWrapper(TextTag): + """Wraps a tag in <i>""" def __init__(self, wrapped: TextTag) -> None: self._wrapped = wrapped @@ -28,9 +56,19 @@ def main(): + """ + >>> simple_hello = TextTag("hello, world!") + >>> special_hello = ItalicWrapper(BoldWrapper(simple_hello)) + + >>> print("before:", simple_hello.render()) + before: hello, world! + + >>> print("after:", special_hello.render()) + after: <i><b>hello, world!</b></i> + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/decorator.py
Write docstrings for backend logic
from typing import Dict, KeysView, Optional, Union class Data: products = { "milk": {"price": 1.50, "quantity": 10}, "eggs": {"price": 0.20, "quantity": 100}, "cheese": {"price": 2.00, "quantity": 10}, } def __get__(self, obj, klas): print("(Fetching from Data Store)") return {"products": self.products} class BusinessLogic: data = Data() def product_list(self) -> KeysView[str]: return self.data["products"].keys() def product_information( self, product: str ) -> Optional[Dict[str, Union[int, float]]]: return self.data["products"].get(product, None) class Ui: def __init__(self) -> None: self.business_logic = BusinessLogic() def get_product_list(self) -> None: print("PRODUCT LIST:") for product in self.business_logic.product_list(): print(product) print("") def get_product_information(self, product: str) -> None: product_info = self.business_logic.product_information(product) if product_info: print("PRODUCT INFORMATION:") print( f"Name: {product.title()}, " + f"Price: {product_info.get('price', 0):.2f}, " + f"Quantity: {product_info.get('quantity', 0):}" ) else: print(f"That product '{product}' does not exist in the records") def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,13 @@+""" +*TL;DR +Separates presentation, application processing, and data management functions. +""" from typing import Dict, KeysView, Optional, Union class Data: + """Data Store Class""" products = { "milk": {"price": 1.50, "quantity": 10}, @@ -16,6 +21,7 @@ class BusinessLogic: + """Business logic holding data store instances""" data = Data() @@ -29,6 +35,7 @@ class Ui: + """UI interaction class""" def __init__(self) -> None: self.business_logic = BusinessLogic() @@ -53,9 +60,38 @@ def main(): + """ + >>> ui = Ui() + >>> ui.get_product_list() + PRODUCT LIST: + (Fetching from Data Store) + milk + eggs + cheese + <BLANKLINE> + + >>> ui.get_product_information("cheese") + (Fetching from Data Store) + PRODUCT INFORMATION: + Name: Cheese, Price: 2.00, Quantity: 10 + + >>> ui.get_product_information("eggs") + (Fetching from Data Store) + PRODUCT INFORMATION: + Name: Eggs, Price: 0.20, Quantity: 100 + + >>> ui.get_product_information("milk") + (Fetching from Data Store) + PRODUCT INFORMATION: + Name: Milk, Price: 1.50, Quantity: 10 + + >>> ui.get_product_information("arepas") + (Fetching from Data Store) + That product 'arepas' does not exist in the records + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/3-tier.py
Generate docstrings for script automation
import weakref class Card: # Could be a simple dict. # With WeakValueDictionary garbage collection can reclaim the object # when there are no other references to it. _pool: weakref.WeakValueDictionary = weakref.WeakValueDictionary() def __new__(cls, value: str, suit: str): # If the object exists in the pool - just return it obj = cls._pool.get(value + suit) # otherwise - create new one (and add it to the pool) if obj is None: obj = object.__new__(Card) cls._pool[value + suit] = obj # This row does the part we usually see in `__init__` obj.value, obj.suit = value, suit return obj # If you uncomment `__init__` and comment-out `__new__` - # Card becomes normal (non-flyweight). # def __init__(self, value, suit): # self.value, self.suit = value, suit def __repr__(self) -> str: return f"<Card: {self.value}{self.suit}>" def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,35 @@+""" +*What is this pattern about? +This pattern aims to minimise the number of objects that are needed by +a program at run-time. A Flyweight is an object shared by multiple +contexts, and is indistinguishable from an object that is not shared. + +The state of a Flyweight should not be affected by it's context, this +is known as its intrinsic state. The decoupling of the objects state +from the object's context, allows the Flyweight to be shared. + +*What does this example do? +The example below sets-up an 'object pool' which stores initialised +objects. When a 'Card' is created it first checks to see if it already +exists instead of creating a new one. This aims to reduce the number of +objects initialised by the program. + +*References: +http://codesnipers.com/?q=python-flyweights +https://python-patterns.guide/gang-of-four/flyweight/ + +*Examples in Python ecosystem: +https://docs.python.org/3/library/sys.html#sys.intern + +*TL;DR +Minimizes memory usage by sharing data with other similar objects. +""" import weakref class Card: + """The Flyweight""" # Could be a simple dict. # With WeakValueDictionary garbage collection can reclaim the object @@ -30,9 +57,29 @@ def main(): + """ + >>> c1 = Card('9', 'h') + >>> c2 = Card('9', 'h') + >>> c1, c2 + (<Card: 9h>, <Card: 9h>) + >>> c1 == c2 + True + >>> c1 is c2 + True + + >>> c1.new_attr = 'temp' + >>> c3 = Card('9', 'h') + >>> hasattr(c3, 'new_attr') + True + + >>> Card._pool.clear() + >>> c4 = Card('9', 'h') + >>> hasattr(c4, 'new_attr') + False + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/flyweight.py
Add docstrings for better understanding
from __future__ import annotations from typing import Any class MobileView: def show_index_page(self) -> None: print("Displaying mobile index page") class TabletView: def show_index_page(self) -> None: print("Displaying tablet index page") class Dispatcher: def __init__(self) -> None: self.mobile_view = MobileView() self.tablet_view = TabletView() def dispatch(self, request: Request) -> None: if request.type == Request.mobile_type: self.mobile_view.show_index_page() elif request.type == Request.tablet_type: self.tablet_view.show_index_page() else: print("Cannot dispatch the request") class RequestController: def __init__(self) -> None: self.dispatcher = Dispatcher() def dispatch_request(self, request: Any) -> None: if isinstance(request, Request): self.dispatcher.dispatch(request) else: print("request must be a Request object") class Request: mobile_type = "mobile" tablet_type = "tablet" def __init__(self, request): self.type = None request = request.lower() if request == self.mobile_type: self.type = self.mobile_type elif request == self.tablet_type: self.type = self.tablet_type def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,9 @@+""" +@author: Gordeev Andrey <gordeev.and.and@gmail.com> + +*TL;DR +Provides a centralized entry point that controls and manages request handling. +""" from __future__ import annotations @@ -20,6 +26,12 @@ self.tablet_view = TabletView() def dispatch(self, request: Request) -> None: + """ + This function is used to dispatch the request based on the type of device. + If it is a mobile, then mobile view will be called and if it is a tablet, + then tablet view will be called. + Otherwise, an error message will be printed saying that cannot dispatch the request. + """ if request.type == Request.mobile_type: self.mobile_view.show_index_page() elif request.type == Request.tablet_type: @@ -29,11 +41,15 @@ class RequestController: + """front controller""" def __init__(self) -> None: self.dispatcher = Dispatcher() def dispatch_request(self, request: Any) -> None: + """ + This function takes a request object and sends it to the dispatcher. + """ if isinstance(request, Request): self.dispatcher.dispatch(request) else: @@ -41,6 +57,7 @@ class Request: + """request""" mobile_type = "mobile" tablet_type = "tablet" @@ -55,9 +72,24 @@ def main(): + """ + >>> front_controller = RequestController() + + >>> front_controller.dispatch_request(Request('mobile')) + Displaying mobile index page + + >>> front_controller.dispatch_request(Request('tablet')) + Displaying tablet index page + + >>> front_controller.dispatch_request(Request('desktop')) + Cannot dispatch the request + + >>> front_controller.dispatch_request('mobile') + request must be a Request object + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/front_controller.py
Generate consistent documentation across files
import functools from typing import Callable, Type class lazy_property: def __init__(self, function: Callable) -> None: self.function = function functools.update_wrapper(self, function) def __get__(self, obj: "Person", type_: Type["Person"]) -> str: if obj is None: return self val = self.function(obj) obj.__dict__[self.function.__name__] = val return val def lazy_property2(fn: Callable) -> property: attr = "_lazy__" + fn.__name__ @property def _lazy_property(self): if not hasattr(self, attr): setattr(self, attr, fn(self)) return getattr(self, attr) return _lazy_property class Person: def __init__(self, name: str, occupation: str) -> None: self.name = name self.occupation = occupation self.call_count2 = 0 @lazy_property def relatives(self) -> str: # Get all relatives, let's assume that it costs much time. relatives = "Many relatives." return relatives @lazy_property2 def parents(self) -> str: self.call_count2 += 1 return "Father and mother" def main(): if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS)
--- +++ @@ -1,3 +1,23 @@+""" +Lazily-evaluated property pattern in Python. + +https://en.wikipedia.org/wiki/Lazy_evaluation + +*References: +bottle +https://github.com/bottlepy/bottle/blob/cafc15419cbb4a6cb748e6ecdccf92893bb25ce5/bottle.py#L270 +django +https://github.com/django/django/blob/ffd18732f3ee9e6f0374aff9ccf350d85187fac2/django/utils/functional.py#L19 +pip +https://github.com/pypa/pip/blob/cb75cca785629e15efb46c35903827b3eae13481/pip/utils/__init__.py#L821 +pyramid +https://github.com/Pylons/pyramid/blob/7909e9503cdfc6f6e84d2c7ace1d3c03ca1d8b73/pyramid/decorator.py#L4 +werkzeug +https://github.com/pallets/werkzeug/blob/5a2bf35441006d832ab1ed5a31963cbc366c99ac/werkzeug/utils.py#L35 + +*TL;DR +Delays the eval of an expr until its value is needed and avoids repeated evals. +""" import functools from typing import Callable, Type @@ -17,6 +37,12 @@ def lazy_property2(fn: Callable) -> property: + """ + A lazy property decorator. + + The function decorated is called the first time to retrieve the result and + then that calculated result is used the next time you access the value. + """ attr = "_lazy__" + fn.__name__ @property @@ -47,9 +73,40 @@ def main(): + """ + >>> Jhon = Person('Jhon', 'Coder') + + >>> Jhon.name + 'Jhon' + >>> Jhon.occupation + 'Coder' + + # Before we access `relatives` + >>> sorted(Jhon.__dict__.items()) + [('call_count2', 0), ('name', 'Jhon'), ('occupation', 'Coder')] + + >>> Jhon.relatives + 'Many relatives.' + + # After we've accessed `relatives` + >>> sorted(Jhon.__dict__.items()) + [('call_count2', 0), ..., ('relatives', 'Many relatives.')] + + >>> Jhon.parents + 'Father and mother' + + >>> sorted(Jhon.__dict__.items()) + [('_lazy__parents', 'Father and mother'), ('call_count2', 1), ..., ('relatives', 'Many relatives.')] + + >>> Jhon.parents + 'Father and mother' + + >>> Jhon.call_count2 + 1 + """ if __name__ == "__main__": import doctest - doctest.testmod(optionflags=doctest.ELLIPSIS)+ doctest.testmod(optionflags=doctest.ELLIPSIS)
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/lazy_evaluation.py
Generate consistent docstrings
from __future__ import annotations class NumberWords: _WORD_MAP = ( "one", "two", "three", "four", "five", ) def __init__(self, start: int, stop: int) -> None: self.start = start self.stop = stop def __iter__(self) -> NumberWords: # this makes the class an Iterable return self def __next__(self) -> str: # this makes the class an Iterator if self.start > self.stop or self.start > len(self._WORD_MAP): raise StopIteration current = self.start self.start += 1 return self._WORD_MAP[current - 1] # Test the iterator def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,15 @@+""" +Implementation of the iterator pattern using the iterator protocol from Python + +*TL;DR +Traverses a container and accesses the container's elements. +""" from __future__ import annotations class NumberWords: + """Counts by word numbers, up to a maximum of five""" _WORD_MAP = ( "one", @@ -31,9 +38,25 @@ def main(): + """ + # Counting to two... + >>> for number in NumberWords(start=1, stop=2): + ... print(number) + one + two + + # Counting to five... + >>> for number in NumberWords(start=1, stop=5): + ... print(number) + one + two + three + four + five + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/iterator_alt.py
Add return value explanations in docstrings
from typing import Union class Subject: def do_the_job(self, user: str) -> None: raise NotImplementedError() class RealSubject(Subject): def do_the_job(self, user: str) -> None: print(f"I am doing the job for {user}") class Proxy(Subject): def __init__(self) -> None: self._real_subject = RealSubject() def do_the_job(self, user: str) -> None: print(f"[log] Doing the job for {user} is requested.") if user == "admin": self._real_subject.do_the_job(user) else: print("[log] I can do the job just for `admins`.") def client(job_doer: Union[RealSubject, Proxy], user: str) -> None: job_doer.do_the_job(user) def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,14 +1,42 @@+""" +*What is this pattern about? +Proxy is used in places where you want to add functionality to a class without +changing its interface. The main class is called `Real Subject`. A client should +use the proxy or the real subject without any code change, so both must have the +same interface. Logging and controlling access to the real subject are some of +the proxy pattern usages. + +*References: +https://refactoring.guru/design-patterns/proxy/python/example +https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Fronting.html + +*TL;DR +Add functionality or logic (e.g. logging, caching, authorization) to a resource +without changing its interface. +""" from typing import Union class Subject: + """ + As mentioned in the document, interfaces of both RealSubject and Proxy should + be the same, because the client should be able to use RealSubject or Proxy with + no code change. + + Not all times this interface is necessary. The point is the client should be + able to use RealSubject or Proxy interchangeably with no change in code. + """ def do_the_job(self, user: str) -> None: raise NotImplementedError() class RealSubject(Subject): + """ + This is the main job doer. External services like payment gateways can be a + good example. + """ def do_the_job(self, user: str) -> None: print(f"I am doing the job for {user}") @@ -19,6 +47,9 @@ self._real_subject = RealSubject() def do_the_job(self, user: str) -> None: + """ + logging and controlling access are some examples of proxy usages. + """ print(f"[log] Doing the job for {user} is requested.") @@ -33,9 +64,28 @@ def main(): + """ + >>> proxy = Proxy() + + >>> real_subject = RealSubject() + + >>> client(proxy, 'admin') + [log] Doing the job for admin is requested. + I am doing the job for admin + + >>> client(proxy, 'anonymous') + [log] Doing the job for anonymous is requested. + [log] I can do the job just for `admins`. + + >>> client(real_subject, 'admin') + I am doing the job for admin + + >>> client(real_subject, 'anonymous') + I am doing the job for anonymous + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/proxy.py
Include argument descriptions in docstrings
# Abstract Building class Building: def __init__(self) -> None: self.build_floor() self.build_size() def build_floor(self): raise NotImplementedError def build_size(self): raise NotImplementedError def __repr__(self) -> str: return "Floor: {0.floor} | Size: {0.size}".format(self) # Concrete Buildings class House(Building): def build_floor(self) -> None: self.floor = "One" def build_size(self) -> None: self.size = "Big" class Flat(Building): def build_floor(self) -> None: self.floor = "More than One" def build_size(self) -> None: self.size = "Small" # In some very complex cases, it might be desirable to pull out the building # logic into another function (or a method on another class), rather than being # in the base class '__init__'. (This leaves you in the strange situation where # a concrete class does not have a useful constructor) class ComplexBuilding: def __repr__(self) -> str: return "Floor: {0.floor} | Size: {0.size}".format(self) class ComplexHouse(ComplexBuilding): def build_floor(self) -> None: self.floor = "One" def build_size(self) -> None: self.size = "Big and fancy" def construct_building(cls) -> Building: building = cls() building.build_floor() building.build_size() return building def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,32 @@+""" +What is this pattern about? +It decouples the creation of a complex object and its representation, +so that the same process can be reused to build objects from the same +family. +This is useful when you must separate the specification of an object +from its actual representation (generally for abstraction). + +What does this example do? +The first example achieves this by using an abstract base +class for a building, where the initializer (__init__ method) specifies the +steps needed, and the concrete subclasses implement these steps. + +In other programming languages, a more complex arrangement is sometimes +necessary. In particular, you cannot have polymorphic behaviour in a constructor in C++ - +see https://stackoverflow.com/questions/1453131/how-can-i-get-polymorphic-behavior-in-a-c-constructor +- which means this Python technique will not work. The polymorphism +required has to be provided by an external, already constructed +instance of a different class. + +In general, in Python this won't be necessary, but a second example showing +this kind of arrangement is also included. + +Where is the pattern used practically? +See: https://sourcemaking.com/design_patterns/builder + +TL;DR +Decouples the creation of a complex object and its representation. +""" @@ -61,9 +90,23 @@ def main(): + """ + >>> house = House() + >>> house + Floor: One | Size: Big + + >>> flat = Flat() + >>> flat + Floor: More than One | Size: Small + + # Using an external constructor function: + >>> complex_house = construct_building(ComplexHouse) + >>> complex_house + Floor: One | Size: Big and fancy + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/builder.py
Add docstrings including usage examples
from __future__ import annotations from typing import Callable class DiscountStrategyValidator: # Descriptor class for check perform @staticmethod def validate(obj: Order, value: Callable) -> bool: try: if obj.price - value(obj) < 0: raise ValueError( f"Discount cannot be applied due to negative price resulting. {value.__name__}" ) except ValueError as ex: print(str(ex)) return False else: return True def __set_name__(self, owner, name: str) -> None: self.private_name = f"_{name}" def __set__(self, obj: Order, value: Callable = None) -> None: if value and self.validate(obj, value): setattr(obj, self.private_name, value) else: setattr(obj, self.private_name, None) def __get__(self, obj: object, objtype: type = None): return getattr(obj, self.private_name) class Order: discount_strategy = DiscountStrategyValidator() def __init__(self, price: float, discount_strategy: Callable = None) -> None: self.price: float = price self.discount_strategy = discount_strategy def apply_discount(self) -> float: if self.discount_strategy: discount = self.discount_strategy(self) else: discount = 0 return self.price - discount def __repr__(self) -> str: strategy = getattr(self.discount_strategy, "__name__", None) return f"<Order price: {self.price} with discount strategy: {strategy}>" def ten_percent_discount(order: Order) -> float: return order.price * 0.10 def on_sale_discount(order: Order) -> float: return order.price * 0.25 + 20 def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,11 @@+""" +*What is this pattern about? +Define a family of algorithms, encapsulate each one, and make them interchangeable. +Strategy lets the algorithm vary independently from clients that use it. + +*TL;DR +Enables selecting an algorithm at runtime. +""" from __future__ import annotations @@ -60,9 +68,25 @@ def main(): + """ + >>> order = Order(100, discount_strategy=ten_percent_discount) + >>> print(order) + <Order price: 100 with discount strategy: ten_percent_discount> + >>> print(order.apply_discount()) + 90.0 + >>> order = Order(100, discount_strategy=on_sale_discount) + >>> print(order) + <Order price: 100 with discount strategy: on_sale_discount> + >>> print(order.apply_discount()) + 55.0 + >>> order = Order(10, discount_strategy=on_sale_discount) + Discount cannot be applied due to negative price resulting. on_sale_discount + >>> print(order) + <Order price: 10 with discount strategy: None> + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/strategy.py
Create docstrings for reusable components
from typing import Dict, Protocol, Type class Localizer(Protocol): def localize(self, msg: str) -> str: ... class GreekLocalizer: def __init__(self) -> None: self.translations = {"dog": "σκύλος", "cat": "γάτα"} def localize(self, msg: str) -> str: return self.translations.get(msg, msg) class EnglishLocalizer: def localize(self, msg: str) -> str: return msg def get_localizer(language: str = "English") -> Localizer: localizers: Dict[str, Type[Localizer]] = { "English": EnglishLocalizer, "Greek": GreekLocalizer, } return localizers.get(language, EnglishLocalizer)() def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,3 +1,26 @@+"""*What is this pattern about? +A Factory is an object for creating other objects. + +*What does this example do? +The code shows a way to localize words in two languages: English and +Greek. "get_localizer" is the factory function that constructs a +localizer depending on the language chosen. The localizer object will +be an instance from a different class according to the language +localized. However, the main code does not have to worry about which +localizer will be instantiated, since the method "localize" will be called +in the same way independently of the language. + +*Where can the pattern be used practically? +The Factory Method can be seen in the popular web framework Django: +https://docs.djangoproject.com/en/4.0/topics/forms/formsets/ +For example, different types of forms are created using a formset_factory + +*References: +http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/ + +*TL;DR +Creates objects without having to specify the exact class. +""" from typing import Dict, Protocol, Type @@ -7,21 +30,25 @@ class GreekLocalizer: + """A simple localizer a la gettext""" def __init__(self) -> None: self.translations = {"dog": "σκύλος", "cat": "γάτα"} def localize(self, msg: str) -> str: + """We'll punt if we don't have a translation""" return self.translations.get(msg, msg) class EnglishLocalizer: + """Simply echoes the message""" def localize(self, msg: str) -> str: return msg def get_localizer(language: str = "English") -> Localizer: + """Factory""" localizers: Dict[str, Type[Localizer]] = { "English": EnglishLocalizer, "Greek": GreekLocalizer, @@ -31,9 +58,21 @@ def main(): + """ + # Create our localizers + >>> e, g = get_localizer(language="English"), get_localizer(language="Greek") + + # Localize some text + >>> for msg in "dog parrot cat bear".split(): + ... print(e.localize(msg), g.localize(msg)) + dog σκύλος + parrot parrot + cat γάτα + bear bear + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/factory.py
Create docstrings for each class method
from abc import ABC, abstractmethod from typing import Dict, List, Union, Any from inspect import signature from sys import argv class Model(ABC): @abstractmethod def __iter__(self) -> Any: pass @abstractmethod def get(self, item: str) -> dict: pass @property @abstractmethod def item_type(self) -> str: pass class ProductModel(Model): class Price(float): def __str__(self) -> str: return f"{self:.2f}" products = { "milk": {"price": Price(1.50), "quantity": 10}, "eggs": {"price": Price(0.20), "quantity": 100}, "cheese": {"price": Price(2.00), "quantity": 10}, } item_type = "product" def __iter__(self) -> Any: yield from self.products def get(self, product: str) -> dict: try: return self.products[product] except KeyError as e: raise KeyError(str(e) + " not in the model's item list.") class View(ABC): @abstractmethod def show_item_list(self, item_type: str, item_list: list) -> None: pass @abstractmethod def show_item_information( self, item_type: str, item_name: str, item_info: dict ) -> None: pass @abstractmethod def item_not_found(self, item_type: str, item_name: str) -> None: pass class ConsoleView(View): def show_item_list(self, item_type: str, item_list: list) -> None: print(item_type.upper() + " LIST:") for item in item_list: print(item) print("") @staticmethod def capitalizer(string: str) -> str: return string[0].upper() + string[1:].lower() def show_item_information( self, item_type: str, item_name: str, item_info: dict ) -> None: print(item_type.upper() + " INFORMATION:") printout = "Name: %s" % item_name for key, value in item_info.items(): printout += ", " + self.capitalizer(str(key)) + ": " + str(value) printout += "\n" print(printout) def item_not_found(self, item_type: str, item_name: str) -> None: print(f'That {item_type} "{item_name}" does not exist in the records') class Controller: def __init__(self, model_class: Model, view_class: View) -> None: self.model: Model = model_class self.view: View = view_class def show_items(self) -> None: items = list(self.model) item_type = self.model.item_type self.view.show_item_list(item_type, items) def show_item_information(self, item_name: str) -> None: item_type: str = self.model.item_type try: item_info: dict = self.model.get(item_name) except Exception: self.view.item_not_found(item_type, item_name) else: self.view.show_item_information(item_type, item_name, item_info) class Router: def __init__(self): self.routes = {} def register( self, path: str, controller_class: type[Controller], model_class: type[Model], view_class: type[View], ) -> None: model_instance: Model = model_class() view_instance: View = view_class() self.routes[path] = controller_class(model_instance, view_instance) def resolve(self, path: str) -> Controller: if self.routes.get(path): controller: Controller = self.routes[path] return controller else: raise KeyError(f"No controller registered for path '{path}'") def main(): if __name__ == "__main__": router = Router() router.register("products", Controller, ProductModel, ConsoleView) controller: Controller = router.resolve(argv[1]) action: str = str(argv[2]) if len(argv) > 2 else "" args: str = " ".join(map(str, argv[3:])) if len(argv) > 3 else "" if hasattr(controller, action): command = getattr(controller, action) sig = signature(command) if len(sig.parameters) > 0: if args: command(args) else: print("Command requires arguments.") else: command() else: print(f"Command {action} not found in the controller.") import doctest doctest.testmod()
--- +++ @@ -1,3 +1,7 @@+""" +*TL;DR +Separates data in GUIs from the ways it is presented, and accepted. +""" from abc import ABC, abstractmethod from typing import Dict, List, Union, Any @@ -6,6 +10,7 @@ class Model(ABC): + """The Model is the data layer of the application.""" @abstractmethod def __iter__(self) -> Any: @@ -13,6 +18,8 @@ @abstractmethod def get(self, item: str) -> dict: + """Returns an object with a .items() call method + that iterates over key,value pairs of its information.""" pass @property @@ -22,8 +29,11 @@ class ProductModel(Model): + """The Model is the data layer of the application.""" class Price(float): + """A polymorphic way to pass a float with a particular + __str__ functionality.""" def __str__(self) -> str: return f"{self:.2f}" @@ -47,6 +57,7 @@ class View(ABC): + """The View is the presentation layer of the application.""" @abstractmethod def show_item_list(self, item_type: str, item_list: list) -> None: @@ -56,6 +67,8 @@ def show_item_information( self, item_type: str, item_name: str, item_info: dict ) -> None: + """Will look for item information by iterating over key,value pairs + yielded by item_info.items()""" pass @abstractmethod @@ -64,6 +77,7 @@ class ConsoleView(View): + """The View is the presentation layer of the application.""" def show_item_list(self, item_type: str, item_list: list) -> None: print(item_type.upper() + " LIST:") @@ -73,11 +87,13 @@ @staticmethod def capitalizer(string: str) -> str: + """Capitalizes the first letter of a string and lowercases the rest.""" return string[0].upper() + string[1:].lower() def show_item_information( self, item_type: str, item_name: str, item_info: dict ) -> None: + """Will look for item information by iterating over key,value pairs""" print(item_type.upper() + " INFORMATION:") printout = "Name: %s" % item_name for key, value in item_info.items(): @@ -90,6 +106,7 @@ class Controller: + """The Controller is the intermediary between the Model and the View.""" def __init__(self, model_class: Model, view_class: View) -> None: self.model: Model = model_class @@ -101,6 +118,10 @@ self.view.show_item_list(item_type, items) def show_item_information(self, item_name: str) -> None: + """ + Show information about a {item_type} item. + :param str item_name: the name of the {item_type} item to show information about + """ item_type: str = self.model.item_type try: item_info: dict = self.model.get(item_name) @@ -111,6 +132,7 @@ class Router: + """The Router is the entry point of the application.""" def __init__(self): self.routes = {} @@ -135,6 +157,36 @@ def main(): + """ + >>> model = ProductModel() + >>> view = ConsoleView() + >>> controller = Controller(model, view) + + >>> controller.show_items() + PRODUCT LIST: + milk + eggs + cheese + <BLANKLINE> + + >>> controller.show_item_information("cheese") + PRODUCT INFORMATION: + Name: cheese, Price: 2.00, Quantity: 10 + <BLANKLINE> + + >>> controller.show_item_information("eggs") + PRODUCT INFORMATION: + Name: eggs, Price: 0.20, Quantity: 100 + <BLANKLINE> + + >>> controller.show_item_information("milk") + PRODUCT INFORMATION: + Name: milk, Price: 1.50, Quantity: 10 + <BLANKLINE> + + >>> controller.show_item_information("arepas") + That product "arepas" does not exist in the records + """ if __name__ == "__main__": @@ -161,4 +213,4 @@ import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/mvc.py
Create docstrings for reusable components
import math class Position: def __init__(self, x, y): self.x = x self.y = y class Circle: def __init__(self, radius, position: Position): self.radius = radius self.position = position class Rectangle: def __init__(self, width, height, position: Position): self.width = width self.height = height self.position = position class GeometryTools: @staticmethod def calculate_area(shape): if isinstance(shape, Circle): return math.pi * shape.radius**2 elif isinstance(shape, Rectangle): return shape.width * shape.height else: raise ValueError("Unsupported shape type") @staticmethod def calculate_perimeter(shape): if isinstance(shape, Circle): return 2 * math.pi * shape.radius elif isinstance(shape, Rectangle): return 2 * (shape.width + shape.height) else: raise ValueError("Unsupported shape type") @staticmethod def move_to(shape, new_position: Position): shape.position = new_position print(f"Moved to ({shape.position.x}, {shape.position.y})") def main(): if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,8 +1,30 @@+""" +Implementation of the Servant design pattern. + +The Servant design pattern is a behavioral pattern used to offer functionality +to a group of classes without requiring them to inherit from a base class. + +This pattern involves creating a Servant class that provides certain services +or functionalities. These services are used by other classes which do not need +to be related through a common parent class. It is particularly useful in +scenarios where adding the desired functionality through inheritance is impractical +or would lead to a rigid class hierarchy. + +This pattern is characterized by the following: + +- A Servant class that provides specific services or actions. +- Client classes that need these services, but do not derive from the Servant class. +- The use of the Servant class by the client classes to perform actions on their behalf. + +References: +- https://en.wikipedia.org/wiki/Servant_(design_pattern) +""" import math class Position: + """Representation of a 2D position with x and y coordinates.""" def __init__(self, x, y): self.x = x @@ -10,6 +32,7 @@ class Circle: + """Representation of a circle defined by a radius and a position.""" def __init__(self, radius, position: Position): self.radius = radius @@ -17,6 +40,7 @@ class Rectangle: + """Representation of a rectangle defined by width, height, and a position.""" def __init__(self, width, height, position: Position): self.width = width @@ -25,9 +49,25 @@ class GeometryTools: + """ + Servant class providing geometry-related services, including area and + perimeter calculations and position updates. + """ @staticmethod def calculate_area(shape): + """ + Calculate the area of a given shape. + + Args: + shape: The geometric shape whose area is to be calculated. + + Returns: + The area of the shape. + + Raises: + ValueError: If the shape type is unsupported. + """ if isinstance(shape, Circle): return math.pi * shape.radius**2 elif isinstance(shape, Rectangle): @@ -37,6 +77,18 @@ @staticmethod def calculate_perimeter(shape): + """ + Calculate the perimeter of a given shape. + + Args: + shape: The geometric shape whose perimeter is to be calculated. + + Returns: + The perimeter of the shape. + + Raises: + ValueError: If the shape type is unsupported. + """ if isinstance(shape, Circle): return 2 * math.pi * shape.radius elif isinstance(shape, Rectangle): @@ -46,14 +98,34 @@ @staticmethod def move_to(shape, new_position: Position): + """ + Move a given shape to a new position. + + Args: + shape: The geometric shape to be moved. + new_position: The new position to move the shape to. + """ shape.position = new_position print(f"Moved to ({shape.position.x}, {shape.position.y})") def main(): + """ + >>> servant = GeometryTools() + >>> circle = Circle(5, Position(0, 0)) + >>> rectangle = Rectangle(3, 4, Position(0, 0)) + >>> servant.calculate_area(circle) + 78.53981633974483 + >>> servant.calculate_perimeter(rectangle) + 14 + >>> servant.move_to(circle, Position(3, 4)) + Moved to (3, 4) + >>> servant.move_to(rectangle, Position(5, 6)) + Moved to (5, 6) + """ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/servant.py
Document this module using docstrings
import weakref class FlyweightMeta(type): def __new__(mcs, name, parents, dct): dct["pool"] = weakref.WeakValueDictionary() return super().__new__(mcs, name, parents, dct) @staticmethod def _serialize_params(cls, *args, **kwargs): args_list = list(map(str, args)) args_list.extend([str(kwargs), cls.__name__]) key = "".join(args_list) return key def __call__(cls, *args, **kwargs): key = FlyweightMeta._serialize_params(cls, *args, **kwargs) pool = getattr(cls, "pool", {}) instance = pool.get(key) if instance is None: instance = super().__call__(*args, **kwargs) pool[key] = instance return instance class Card2(metaclass=FlyweightMeta): def __init__(self, *args, **kwargs): # print('Init {}: {}'.format(self.__class__, (args, kwargs))) pass if __name__ == "__main__": instances_pool = getattr(Card2, "pool") cm1 = Card2("10", "h", a=1) cm2 = Card2("10", "h", a=1) cm3 = Card2("10", "h", a=2) assert (cm1 == cm2) and (cm1 != cm3) assert (cm1 is cm2) and (cm1 is not cm3) assert len(instances_pool) == 2 del cm1 assert len(instances_pool) == 2 del cm2 assert len(instances_pool) == 1 del cm3 assert len(instances_pool) == 0
--- +++ @@ -3,11 +3,24 @@ class FlyweightMeta(type): def __new__(mcs, name, parents, dct): + """ + Set up object pool + + :param name: class name + :param parents: class parents + :param dct: dict: includes class attributes, class methods, + static methods, etc + :return: new class + """ dct["pool"] = weakref.WeakValueDictionary() return super().__new__(mcs, name, parents, dct) @staticmethod def _serialize_params(cls, *args, **kwargs): + """ + Serialize input parameters to a key. + Simple implementation is just to serialize it as a string + """ args_list = list(map(str, args)) args_list.extend([str(kwargs), cls.__name__]) key = "".join(args_list) @@ -47,4 +60,4 @@ assert len(instances_pool) == 1 del cm3 - assert len(instances_pool) == 0+ assert len(instances_pool) == 0
https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/flyweight_with_metaclass.py