Compare commits
73 Commits
053bb8696f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 93b88917df | |||
| 25618ab5bf | |||
| 81fa68ed08 | |||
| ca6eaed146 | |||
| 1b8b32027c | |||
| a6190aeb84 | |||
| 887169e7d2 | |||
| 9565e4008e | |||
| c2aab71955 | |||
| 97dd55981b | |||
| 0e91c95e9b | |||
| a818df4a6c | |||
| 9aec57bd56 | |||
| ec9943822c | |||
| 0240ff9f8e | |||
| 45e2e1eb00 | |||
| ff20228fa6 | |||
| 9d9c09d56a | |||
| 64355fbeeb | |||
| 4a337e6b20 | |||
| f27be4d603 | |||
| 9d254ac4b7 | |||
| 590cc03ba4 | |||
| c493a99860 | |||
| 3f9ef6527f | |||
| f53e5bb527 | |||
| f2854a0df5 | |||
| defd991006 | |||
| f922e3cf9d | |||
| 06d70edaf1 | |||
| 58ab6cfafa | |||
| dba06e642a | |||
| 5868c1649b | |||
| a14184cddc | |||
| 6587f8c39c | |||
| ae6663572c | |||
| 3eb456e999 | |||
| cfa5773e62 | |||
| ddee2a6029 | |||
| 5e2b4f3408 | |||
| c238278df6 | |||
| a9c25c8c10 | |||
| 5ff25b3eb6 | |||
| c396ba8ae9 | |||
| d12f14a994 | |||
| a4b622bfd3 | |||
| 005c76119f | |||
| b1e2b266f4 | |||
| 6475a117e7 | |||
| 28a193078a | |||
| 07bbe88784 | |||
| 59554f6f17 | |||
| 02f609d829 | |||
| c8df3d0460 | |||
| 5afee97259 | |||
| ebbcbeeaa7 | |||
| 044ec67aa3 | |||
| e871d19a9f | |||
| 0ec562e0d2 | |||
| 276d177c4d | |||
| ed0076a34e | |||
| e99defc533 | |||
| 50288e9130 | |||
| c7ef63cc05 | |||
| 2395f60d11 | |||
| edba17e9a3 | |||
| e3da6c4f12 | |||
| debf55577d | |||
| 2efe83650b | |||
| 1c7a903131 | |||
| 472b828f72 | |||
| 8090a3432c | |||
| 8b406f5d4e |
69
README.md
69
README.md
@@ -1,16 +1,16 @@
|
|||||||
# Skywipe
|
# Skywipe
|
||||||
|
|
||||||
Skywipe is a work-in-progress Python 3.13+ CLI that helps you wipe data from your Bluesky account using the AT Protocol.
|
Skywipe is a work-in-progress Python 3.13+ CLI that helps you wipe data from your Bluesky account using the AT Protocol SDK.
|
||||||
|
|
||||||
## Warning
|
**Warning:** This tool performs _**destructive operations**_.
|
||||||
|
|
||||||
This tool performs destructive operations. Only use it if you intend to erase data from your Bluesky account.
|
Only use it if you intend to permanently erase data from your Bluesky account.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
We're using [`uv`](https://github.com/astral-sh/uv) for dependency and virtual environment management.
|
Check [pyproject.toml](pyproject.toml).
|
||||||
|
|
||||||
You can setup the project (aka create a virtual environment and install dependencies) with :
|
You can use `uv` to install dependencies:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.kharec.info/Kharec/skywipe.git
|
git clone https://git.kharec.info/Kharec/skywipe.git
|
||||||
@@ -20,31 +20,25 @@ uv sync
|
|||||||
|
|
||||||
## How to run
|
## How to run
|
||||||
|
|
||||||
When installation will be worked out, you'll be able to :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
skywipe all # target everything
|
|
||||||
skywipe configure # create configuration
|
|
||||||
skywipe posts # only posts
|
|
||||||
skywipe medias # only posts with medias
|
|
||||||
skywipe likes # only likes
|
|
||||||
skywipe reposts # only reposts
|
|
||||||
skywipe follows # only follows
|
|
||||||
```
|
|
||||||
|
|
||||||
While it's being developed, you can use the tool using `uv` :
|
While it's being developed, you can use the tool using `uv` :
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv run main.py all # target everything
|
uv run python -m skywipe.cli all # target everything
|
||||||
uv run main.py configure # create configuration
|
uv run python -m skywipe.cli configure # create configuration
|
||||||
uv run main.py posts # only posts
|
uv run python -m skywipe.cli posts # delete posts
|
||||||
uv run main.py medias # only posts with medias
|
uv run python -m skywipe.cli medias # delete posts with medias
|
||||||
uv run main.py likes # only likes
|
uv run python -m skywipe.cli likes # undo likes
|
||||||
uv run main.py reposts # only reposts
|
uv run python -m skywipe.cli reposts # undo reposts
|
||||||
uv run main.py follows # only follows
|
uv run python -m skywipe.cli quotes # delete quotes
|
||||||
|
uv run python -m skywipe.cli follows # unfollow all
|
||||||
|
uv run python -m skywipe.cli bookmarks # delete bookmarks
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuration
|
Use the `--yes` flag to skip the confirmation prompt and proceed with the operation.
|
||||||
|
|
||||||
|
A log of the operations will be saved in `~/.cache/skywipe/skywipe.log`.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
If you run the tool for the first time, it will prompt you to use `skywipe configure` to create the configuration file, which is located in `~/.config/skywipe/config.yml` :
|
If you run the tool for the first time, it will prompt you to use `skywipe configure` to create the configuration file, which is located in `~/.config/skywipe/config.yml` :
|
||||||
|
|
||||||
@@ -60,17 +54,20 @@ BE SURE TO USE A [BLUESKY APP PASSWORD](https://blueskyfeeds.com/faq-app-passwor
|
|||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
- [ ] build cli parameter management
|
- [x] build cli parameter management
|
||||||
- [ ] handle configuration logic
|
- [x] handle configuration logic
|
||||||
- [ ] sign in to at protocol
|
- [x] sign in to at protocol
|
||||||
- [ ] delete posts in groups
|
- [x] delete posts in batch
|
||||||
- [ ] only delete posts with media
|
- [x] only delete posts with media
|
||||||
- [ ] remove likes
|
- [x] undo likes
|
||||||
- [ ] remove reposts
|
- [x] undo reposts
|
||||||
- [ ] unfollow accounts
|
- [x] delete quotes
|
||||||
- [ ] make `all` run the other commands
|
- [x] unfollow accounts
|
||||||
- [ ] add simple progress and logging
|
- [x] remove bookmarks
|
||||||
- [ ] add safeguards like confirmations and clear dry-run info
|
- [x] make `all` run the other commands
|
||||||
|
- [x] add simple progress and logging
|
||||||
|
- [x] add safeguards (confirmation, dry-run flag)
|
||||||
|
- [x] decent code architecture
|
||||||
- [ ] installation and run process
|
- [ ] installation and run process
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
57
main.py
57
main.py
@@ -1,57 +0,0 @@
|
|||||||
"""Main entry point for Skywipe"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
import argparse
|
|
||||||
|
|
||||||
from skywipe.commands import get_registry
|
|
||||||
from skywipe.configure import Configuration
|
|
||||||
|
|
||||||
|
|
||||||
def _create_parser():
|
|
||||||
registry = get_registry()
|
|
||||||
commands = registry.get_all_commands()
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description="Clean your bluesky account with style.",
|
|
||||||
epilog="WARNING: This tool performs destructive operations. Only use it if you intend to erase data from your Bluesky account."
|
|
||||||
)
|
|
||||||
|
|
||||||
subparsers = parser.add_subparsers(
|
|
||||||
dest="command",
|
|
||||||
help="Command to execute",
|
|
||||||
metavar="COMMAND",
|
|
||||||
required=True
|
|
||||||
)
|
|
||||||
|
|
||||||
for cmd, help_text in commands.items():
|
|
||||||
subparsers.add_parser(cmd, help=help_text)
|
|
||||||
|
|
||||||
return parser
|
|
||||||
|
|
||||||
|
|
||||||
def _require_config():
|
|
||||||
config = Configuration()
|
|
||||||
if not config.exists():
|
|
||||||
print("Error: Configuration file not found.")
|
|
||||||
print("You must run 'skywipe configure' first.")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
parser = _create_parser()
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
registry = get_registry()
|
|
||||||
|
|
||||||
if registry.requires_config(args.command):
|
|
||||||
_require_config()
|
|
||||||
|
|
||||||
try:
|
|
||||||
registry.execute(args.command)
|
|
||||||
except ValueError as e:
|
|
||||||
print(f"Error: {e}")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
@@ -1,13 +1,10 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "skywipe"
|
name = "skywipe"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
description = "Clean your bluesky account with style"
|
description = "Clean your bluesky account"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.13"
|
requires-python = ">=3.13"
|
||||||
dependencies = [
|
dependencies = ["atproto>=0.0.65", "pyyaml>=6.0"]
|
||||||
"atproto>=0.0.65",
|
|
||||||
"pyyaml>=6.0",
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
skywipe = "main:main"
|
skywipe = "skywipe.cli:main"
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
"""Authentication module for Skywipe CLI."""
|
"""Authentication module for Skywipe"""
|
||||||
|
|
||||||
from atproto import Client
|
from atproto import Client
|
||||||
from skywipe.configure import Configuration
|
from .configure import Configuration
|
||||||
|
|
||||||
|
|
||||||
class Auth:
|
class Auth:
|
||||||
def __init__(self, configuration: Configuration = None):
|
def __init__(self):
|
||||||
self.configuration = configuration or Configuration()
|
self.config = Configuration()
|
||||||
self.client: Client = None
|
self.client = None
|
||||||
|
|
||||||
def login(self) -> Client:
|
def login(self) -> Client:
|
||||||
config_data = self.configuration.load()
|
try:
|
||||||
|
config_data = self.config.load()
|
||||||
|
except FileNotFoundError as e:
|
||||||
|
raise ValueError(
|
||||||
|
"Configuration file not found. Run 'skywipe configure' first.") from e
|
||||||
|
|
||||||
handle = config_data.get("handle")
|
handle = config_data.get("handle")
|
||||||
password = config_data.get("password")
|
password = config_data.get("password")
|
||||||
@@ -19,7 +23,11 @@ class Auth:
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"handle and password must be set in configuration")
|
"handle and password must be set in configuration")
|
||||||
|
|
||||||
self.client = Client()
|
try:
|
||||||
self.client.login(handle, password)
|
self.client = Client()
|
||||||
|
self.client.login(handle, password)
|
||||||
|
except Exception as e:
|
||||||
|
raise ValueError(
|
||||||
|
f"Failed to authenticate: {e}") from e
|
||||||
|
|
||||||
return self.client
|
return self.client
|
||||||
|
|||||||
76
skywipe/cli.py
Normal file
76
skywipe/cli.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
"""Main entry point for Skywipe"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .commands import registry
|
||||||
|
from .configure import Configuration
|
||||||
|
from .logger import setup_logger, get_logger
|
||||||
|
|
||||||
|
|
||||||
|
def create_parser():
|
||||||
|
commands = registry.get_all_commands()
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Clean your bluesky account with style.",
|
||||||
|
epilog="WARNING: This tool performs destructive operations. Only use it if you intend to erase data from your Bluesky account."
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--yes",
|
||||||
|
action="store_true",
|
||||||
|
help="Skip confirmation prompt and proceed with destructive operations"
|
||||||
|
)
|
||||||
|
|
||||||
|
subparsers = parser.add_subparsers(
|
||||||
|
dest="command",
|
||||||
|
help="Command to execute",
|
||||||
|
metavar="COMMAND",
|
||||||
|
required=True
|
||||||
|
)
|
||||||
|
|
||||||
|
for cmd, help_text in commands.items():
|
||||||
|
subparsers.add_parser(cmd, help=help_text)
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def require_config():
|
||||||
|
config = Configuration()
|
||||||
|
if not config.exists():
|
||||||
|
logger = setup_logger(verbose=False)
|
||||||
|
logger.error("Configuration file not found.")
|
||||||
|
logger.error("You must run 'skywipe configure' first.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = create_parser()
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if registry.requires_config(args.command):
|
||||||
|
require_config()
|
||||||
|
config = Configuration()
|
||||||
|
config_data = config.load()
|
||||||
|
verbose = config_data.get("verbose", False)
|
||||||
|
log_file = Path.home() / ".cache" / "skywipe" / "skywipe.log"
|
||||||
|
setup_logger(verbose=verbose, log_file=log_file)
|
||||||
|
else:
|
||||||
|
setup_logger(verbose=False)
|
||||||
|
|
||||||
|
try:
|
||||||
|
registry.execute(
|
||||||
|
args.command, skip_confirmation=getattr(args, "yes", False))
|
||||||
|
except ValueError as e:
|
||||||
|
logger = get_logger()
|
||||||
|
logger.error(f"{e}")
|
||||||
|
sys.exit(1)
|
||||||
|
except Exception as e:
|
||||||
|
logger = get_logger()
|
||||||
|
logger.error(f"Unexpected error: {e}", exc_info=True)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -1,17 +1,91 @@
|
|||||||
"""Command implementations for Skywipe CLI."""
|
"""Command implementations for Skywipe"""
|
||||||
|
|
||||||
from typing import Callable, Dict, Optional
|
from typing import Callable, Dict, Optional, Any
|
||||||
from skywipe.configure import Configuration
|
from .configure import Configuration
|
||||||
|
from .operations import Operation
|
||||||
|
from .post_analysis import PostAnalyzer
|
||||||
|
from .logger import get_logger
|
||||||
|
from .safeguard import require_confirmation
|
||||||
|
|
||||||
|
|
||||||
CommandHandler = Callable[[], None]
|
CommandHandler = Callable[..., None]
|
||||||
|
|
||||||
|
|
||||||
|
COMMAND_METADATA = {
|
||||||
|
"posts": {
|
||||||
|
"confirmation": "delete all posts",
|
||||||
|
"help_text": "only posts",
|
||||||
|
"operation_name": "Deleting posts",
|
||||||
|
"strategy_type": "feed",
|
||||||
|
"collection": None,
|
||||||
|
"filter_fn": None,
|
||||||
|
},
|
||||||
|
"medias": {
|
||||||
|
"confirmation": "delete all posts with media",
|
||||||
|
"help_text": "only posts with medias",
|
||||||
|
"operation_name": "Deleting posts with media",
|
||||||
|
"strategy_type": "feed",
|
||||||
|
"collection": None,
|
||||||
|
"filter_fn": lambda post: PostAnalyzer.has_media(post.post),
|
||||||
|
},
|
||||||
|
"likes": {
|
||||||
|
"confirmation": "undo all likes",
|
||||||
|
"help_text": "only likes",
|
||||||
|
"operation_name": "Undoing likes",
|
||||||
|
"strategy_type": "record",
|
||||||
|
"collection": "app.bsky.feed.like",
|
||||||
|
"filter_fn": None,
|
||||||
|
},
|
||||||
|
"reposts": {
|
||||||
|
"confirmation": "undo all reposts",
|
||||||
|
"help_text": "only reposts",
|
||||||
|
"operation_name": "Undoing reposts",
|
||||||
|
"strategy_type": "record",
|
||||||
|
"collection": "app.bsky.feed.repost",
|
||||||
|
"filter_fn": None,
|
||||||
|
},
|
||||||
|
"quotes": {
|
||||||
|
"confirmation": "delete all quote posts",
|
||||||
|
"help_text": "only quotes",
|
||||||
|
"operation_name": "Deleting quote posts",
|
||||||
|
"strategy_type": "feed",
|
||||||
|
"collection": None,
|
||||||
|
"filter_fn": lambda post: PostAnalyzer.has_quote(post.post),
|
||||||
|
},
|
||||||
|
"follows": {
|
||||||
|
"confirmation": "unfollow all accounts",
|
||||||
|
"help_text": "only follows",
|
||||||
|
"operation_name": "Unfollowing accounts",
|
||||||
|
"strategy_type": "record",
|
||||||
|
"collection": "app.bsky.graph.follow",
|
||||||
|
"filter_fn": None,
|
||||||
|
},
|
||||||
|
"bookmarks": {
|
||||||
|
"confirmation": "delete all bookmarks",
|
||||||
|
"help_text": "only bookmarks",
|
||||||
|
"operation_name": "Deleting bookmarks",
|
||||||
|
"strategy_type": "bookmark",
|
||||||
|
"collection": None,
|
||||||
|
"filter_fn": None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
COMMAND_EXECUTION_ORDER = [
|
||||||
|
"quotes",
|
||||||
|
"medias",
|
||||||
|
"posts",
|
||||||
|
"likes",
|
||||||
|
"reposts",
|
||||||
|
"follows",
|
||||||
|
"bookmarks",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class CommandRegistry:
|
class CommandRegistry:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._commands: Dict[str, CommandHandler] = {}
|
self._commands = {}
|
||||||
self._help_texts: Dict[str, str] = {}
|
self._help_texts = {}
|
||||||
self._requires_config: Dict[str, bool] = {}
|
self._requires_config = {}
|
||||||
|
|
||||||
def register(
|
def register(
|
||||||
self,
|
self,
|
||||||
@@ -36,19 +110,46 @@ class CommandRegistry:
|
|||||||
def get_all_commands(self) -> Dict[str, str]:
|
def get_all_commands(self) -> Dict[str, str]:
|
||||||
return self._help_texts.copy()
|
return self._help_texts.copy()
|
||||||
|
|
||||||
def execute(self, name: str):
|
def execute(self, name: str, skip_confirmation: bool = False):
|
||||||
handler = self.get_handler(name)
|
handler = self.get_handler(name)
|
||||||
if handler:
|
if handler:
|
||||||
handler()
|
if name == "configure":
|
||||||
|
handler()
|
||||||
|
else:
|
||||||
|
handler(skip_confirmation)
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"Unknown command: {name}")
|
raise ValueError(f"Unknown command: {name}")
|
||||||
|
|
||||||
|
|
||||||
_registry = CommandRegistry()
|
registry = CommandRegistry()
|
||||||
|
|
||||||
|
|
||||||
def get_registry() -> CommandRegistry:
|
def _create_operation_handler(
|
||||||
return _registry
|
confirmation_message: str,
|
||||||
|
operation_name: str,
|
||||||
|
strategy_type: str = "feed",
|
||||||
|
collection: Optional[str] = None,
|
||||||
|
filter_fn: Optional[Callable[[Any], bool]] = None
|
||||||
|
) -> CommandHandler:
|
||||||
|
def handler(skip_confirmation: bool = False):
|
||||||
|
require_confirmation(confirmation_message, skip_confirmation)
|
||||||
|
try:
|
||||||
|
Operation(
|
||||||
|
operation_name,
|
||||||
|
strategy_type=strategy_type,
|
||||||
|
collection=collection,
|
||||||
|
filter_fn=filter_fn
|
||||||
|
).run()
|
||||||
|
except ValueError as e:
|
||||||
|
logger = get_logger()
|
||||||
|
logger.error(f"{e}")
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
logger = get_logger()
|
||||||
|
logger.error(
|
||||||
|
f"Unexpected error during operation: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
return handler
|
||||||
|
|
||||||
|
|
||||||
def run_configure():
|
def run_configure():
|
||||||
@@ -56,40 +157,82 @@ def run_configure():
|
|||||||
config.create()
|
config.create()
|
||||||
|
|
||||||
|
|
||||||
def run_posts():
|
def _create_command_handlers():
|
||||||
print("Command 'posts' is not yet implemented.")
|
handlers = {}
|
||||||
|
for cmd, metadata in COMMAND_METADATA.items():
|
||||||
|
handlers[cmd] = _create_operation_handler(
|
||||||
|
metadata["confirmation"],
|
||||||
|
metadata["operation_name"],
|
||||||
|
strategy_type=metadata["strategy_type"],
|
||||||
|
collection=metadata["collection"],
|
||||||
|
filter_fn=metadata["filter_fn"]
|
||||||
|
)
|
||||||
|
return handlers
|
||||||
|
|
||||||
|
|
||||||
def run_medias():
|
_command_handlers = _create_command_handlers()
|
||||||
print("Command 'medias' is not yet implemented.")
|
run_posts = _command_handlers["posts"]
|
||||||
|
run_medias = _command_handlers["medias"]
|
||||||
|
run_likes = _command_handlers["likes"]
|
||||||
|
run_reposts = _command_handlers["reposts"]
|
||||||
|
run_quotes = _command_handlers["quotes"]
|
||||||
|
run_follows = _command_handlers["follows"]
|
||||||
|
run_bookmarks = _command_handlers["bookmarks"]
|
||||||
|
|
||||||
|
|
||||||
def run_likes():
|
def run_all(skip_confirmation: bool = False):
|
||||||
print("Command 'likes' is not yet implemented.")
|
logger = get_logger()
|
||||||
|
|
||||||
|
all_commands = registry.get_all_commands()
|
||||||
|
available_commands = [cmd for cmd in all_commands.keys()
|
||||||
|
if cmd not in ("configure", "all")]
|
||||||
|
|
||||||
|
commands = [cmd for cmd in COMMAND_EXECUTION_ORDER
|
||||||
|
if cmd in available_commands]
|
||||||
|
|
||||||
|
commands.extend([cmd for cmd in available_commands
|
||||||
|
if cmd not in COMMAND_EXECUTION_ORDER])
|
||||||
|
|
||||||
|
commands_str = ", ".join(commands)
|
||||||
|
all_confirmation = f"run all cleanup commands ({commands_str})"
|
||||||
|
require_confirmation(all_confirmation, skip_confirmation)
|
||||||
|
|
||||||
|
logger.info("Running all cleanup commands...")
|
||||||
|
|
||||||
|
from .operations import OperationContext
|
||||||
|
try:
|
||||||
|
context = OperationContext()
|
||||||
|
shared_client = context.client
|
||||||
|
shared_config_data = context.config_data
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
f"Failed to initialize shared context: {e}", exc_info=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
for cmd in commands:
|
||||||
|
try:
|
||||||
|
logger.info(f"Starting command: {cmd}")
|
||||||
|
metadata = COMMAND_METADATA.get(cmd)
|
||||||
|
if metadata:
|
||||||
|
Operation(
|
||||||
|
metadata["operation_name"],
|
||||||
|
strategy_type=metadata["strategy_type"],
|
||||||
|
collection=metadata["collection"],
|
||||||
|
filter_fn=metadata["filter_fn"],
|
||||||
|
client=shared_client,
|
||||||
|
config_data=shared_config_data
|
||||||
|
).run()
|
||||||
|
else:
|
||||||
|
registry.execute(cmd, skip_confirmation=True)
|
||||||
|
logger.info(f"Completed command: {cmd}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error running '{cmd}': {e}", exc_info=True)
|
||||||
|
continue
|
||||||
|
logger.info("All commands completed.")
|
||||||
|
|
||||||
|
|
||||||
def run_reposts():
|
registry.register("configure", run_configure,
|
||||||
print("Command 'reposts' is not yet implemented.")
|
"create configuration", requires_config=False)
|
||||||
|
for cmd, metadata in COMMAND_METADATA.items():
|
||||||
|
registry.register(cmd, _command_handlers[cmd], metadata["help_text"])
|
||||||
def run_follows():
|
registry.register("all", run_all, "target everything")
|
||||||
print("Command 'follows' is not yet implemented.")
|
|
||||||
|
|
||||||
|
|
||||||
def run_all():
|
|
||||||
registry = get_registry()
|
|
||||||
registry.execute("posts")
|
|
||||||
registry.execute("medias")
|
|
||||||
registry.execute("likes")
|
|
||||||
registry.execute("reposts")
|
|
||||||
registry.execute("follows")
|
|
||||||
|
|
||||||
|
|
||||||
_registry.register("configure", run_configure,
|
|
||||||
"create configuration", requires_config=False)
|
|
||||||
_registry.register("posts", run_posts, "only posts")
|
|
||||||
_registry.register("medias", run_medias, "only posts with medias")
|
|
||||||
_registry.register("likes", run_likes, "only likes")
|
|
||||||
_registry.register("reposts", run_reposts, "only reposts")
|
|
||||||
_registry.register("follows", run_follows, "only follows")
|
|
||||||
_registry.register("all", run_all, "target everything")
|
|
||||||
|
|||||||
@@ -1,8 +1,46 @@
|
|||||||
"""Core configuration handling class and related logic."""
|
"""Core configuration module for Skywipe"""
|
||||||
|
|
||||||
import getpass
|
import getpass
|
||||||
|
import re
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import yaml
|
import yaml
|
||||||
|
from .logger import setup_logger
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_handle(handle: str) -> tuple[bool, str]:
|
||||||
|
if not handle:
|
||||||
|
return False, "Handle cannot be empty"
|
||||||
|
|
||||||
|
if len(handle) > 253:
|
||||||
|
return False, "Handle is too long (max 253 characters)"
|
||||||
|
|
||||||
|
if " " in handle:
|
||||||
|
return False, "Handle cannot contain spaces"
|
||||||
|
|
||||||
|
handle_pattern = re.compile(
|
||||||
|
r"^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$|"
|
||||||
|
r"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$|"
|
||||||
|
r"^did:[a-z]+:[a-zA-Z0-9._-]+$"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not handle_pattern.match(handle):
|
||||||
|
return False, (
|
||||||
|
"Invalid handle format. "
|
||||||
|
"Use a username (e.g., 'alice'), full handle (e.g., 'alice.bsky.social'), "
|
||||||
|
"or DID (e.g., 'did:plc:...')"
|
||||||
|
)
|
||||||
|
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_password(password: str) -> tuple[bool, str]:
|
||||||
|
if not password:
|
||||||
|
return False, "Password cannot be empty"
|
||||||
|
|
||||||
|
if len(password) < 8:
|
||||||
|
return False, "Password is too short (minimum 8 characters)"
|
||||||
|
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
class Configuration:
|
class Configuration:
|
||||||
@@ -13,10 +51,12 @@ class Configuration:
|
|||||||
return self.config_file.exists()
|
return self.config_file.exists()
|
||||||
|
|
||||||
def create(self):
|
def create(self):
|
||||||
|
logger = setup_logger(verbose=False)
|
||||||
if self.exists():
|
if self.exists():
|
||||||
overwrite = input(
|
overwrite = input(
|
||||||
"Configuration already exists. Overwrite? (y/N): ").strip().lower()
|
"Configuration already exists. Overwrite? (y/N): ").strip().lower()
|
||||||
if overwrite not in ("y", "yes"):
|
if overwrite not in ("y", "yes"):
|
||||||
|
logger.info("Configuration creation cancelled.")
|
||||||
return
|
return
|
||||||
|
|
||||||
config_dir = self.config_file.parent
|
config_dir = self.config_file.parent
|
||||||
@@ -24,8 +64,27 @@ class Configuration:
|
|||||||
|
|
||||||
print("Skywipe Configuration")
|
print("Skywipe Configuration")
|
||||||
print("=" * 50)
|
print("=" * 50)
|
||||||
handle = input("Bluesky handle: ").strip()
|
print("Note: You should use an app password from Bluesky settings.")
|
||||||
password = getpass.getpass("Bluesky app password: ").strip()
|
|
||||||
|
while True:
|
||||||
|
handle = input("Bluesky handle: ").strip()
|
||||||
|
is_valid, error_msg = _validate_handle(handle)
|
||||||
|
if is_valid:
|
||||||
|
break
|
||||||
|
logger.error(error_msg)
|
||||||
|
logger.info("Please enter a valid handle and try again.")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
password = getpass.getpass(
|
||||||
|
"Bluesky (hopefully app) password: ").strip()
|
||||||
|
is_valid, error_msg = _validate_password(password)
|
||||||
|
if is_valid:
|
||||||
|
break
|
||||||
|
logger.error(error_msg)
|
||||||
|
logger.info("Please check your password and try again.")
|
||||||
|
logger.info(
|
||||||
|
"Generate an app password at: https://bsky.app/settings/app-passwords")
|
||||||
|
|
||||||
batch_size = input("Batch size (default: 10): ").strip() or "10"
|
batch_size = input("Batch size (default: 10): ").strip() or "10"
|
||||||
delay = input(
|
delay = input(
|
||||||
"Delay between batches in seconds (default: 1): ").strip() or "1"
|
"Delay between batches in seconds (default: 1): ").strip() or "1"
|
||||||
@@ -35,9 +94,20 @@ class Configuration:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
batch_size = int(batch_size)
|
batch_size = int(batch_size)
|
||||||
delay = int(delay)
|
if batch_size < 1 or batch_size > 100:
|
||||||
|
logger.error("batch_size must be between 1 and 100")
|
||||||
|
return
|
||||||
except ValueError:
|
except ValueError:
|
||||||
print("Error: batch_size and delay must be integers")
|
logger.error("batch_size must be an integer")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
delay = int(delay)
|
||||||
|
if delay < 0 or delay > 60:
|
||||||
|
logger.error("delay must be between 0 and 60 seconds")
|
||||||
|
return
|
||||||
|
except ValueError:
|
||||||
|
logger.error("delay must be an integer")
|
||||||
return
|
return
|
||||||
|
|
||||||
config_data = {
|
config_data = {
|
||||||
@@ -48,14 +118,28 @@ class Configuration:
|
|||||||
"verbose": verbose
|
"verbose": verbose
|
||||||
}
|
}
|
||||||
|
|
||||||
with open(self.config_file, "w") as f:
|
try:
|
||||||
yaml.dump(config_data, f, default_flow_style=False)
|
with open(self.config_file, "w") as f:
|
||||||
|
yaml.dump(config_data, f, default_flow_style=False)
|
||||||
|
except (IOError, OSError) as e:
|
||||||
|
logger.error(f"Failed to save configuration: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
print(f"\nConfiguration saved to {self.config_file}")
|
logger.info(f"Configuration saved to {self.config_file}")
|
||||||
|
|
||||||
def load(self) -> dict:
|
def load(self) -> dict:
|
||||||
if not self.exists():
|
if not self.exists():
|
||||||
raise FileNotFoundError(
|
raise FileNotFoundError(
|
||||||
f"Configuration file not found: {self.config_file}")
|
f"Configuration file not found: {self.config_file}")
|
||||||
with open(self.config_file, "r") as f:
|
try:
|
||||||
return yaml.safe_load(f)
|
with open(self.config_file, "r") as f:
|
||||||
|
config_data = yaml.safe_load(f)
|
||||||
|
if config_data is None:
|
||||||
|
raise ValueError("Configuration file is empty or invalid")
|
||||||
|
return config_data
|
||||||
|
except (IOError, OSError) as e:
|
||||||
|
raise ValueError(
|
||||||
|
f"Failed to read configuration file: {e}") from e
|
||||||
|
except yaml.YAMLError as e:
|
||||||
|
raise ValueError(
|
||||||
|
f"Invalid YAML in configuration file: {e}") from e
|
||||||
|
|||||||
91
skywipe/logger.py
Normal file
91
skywipe/logger.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
"""Centralized logging module for Skywipe"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class ProgressTracker:
|
||||||
|
def __init__(self, operation: str = "Processing"):
|
||||||
|
self.current = 0
|
||||||
|
self.operation = operation
|
||||||
|
|
||||||
|
def update(self, count: int = 1):
|
||||||
|
self.current += count
|
||||||
|
|
||||||
|
def batch(self, batch_num: int, batch_size: int, total_batches: Optional[int] = None):
|
||||||
|
logger = logging.getLogger("skywipe.progress")
|
||||||
|
if total_batches:
|
||||||
|
logger.info(
|
||||||
|
f"{self.operation} - batch {batch_num}/{total_batches} ({batch_size} items)"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.info(
|
||||||
|
f"{self.operation} - batch {batch_num} ({batch_size} items)")
|
||||||
|
|
||||||
|
|
||||||
|
class LevelFilter(logging.Filter):
|
||||||
|
def __init__(self, min_level: int, max_level: int):
|
||||||
|
super().__init__()
|
||||||
|
self.min_level = min_level
|
||||||
|
self.max_level = max_level
|
||||||
|
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
return self.min_level <= record.levelno <= self.max_level
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logger(verbose: bool = False, log_file: Optional[Path] = None) -> logging.Logger:
|
||||||
|
logger = logging.getLogger("skywipe")
|
||||||
|
target_level = logging.DEBUG if verbose else logging.INFO
|
||||||
|
logger.setLevel(target_level)
|
||||||
|
|
||||||
|
info_handler = None
|
||||||
|
error_handler = None
|
||||||
|
file_handlers = []
|
||||||
|
|
||||||
|
for handler in logger.handlers:
|
||||||
|
if isinstance(handler, logging.StreamHandler):
|
||||||
|
if handler.stream == sys.stdout:
|
||||||
|
info_handler = handler
|
||||||
|
elif handler.stream == sys.stderr:
|
||||||
|
error_handler = handler
|
||||||
|
elif isinstance(handler, logging.FileHandler):
|
||||||
|
file_handlers.append(handler)
|
||||||
|
|
||||||
|
formatter = logging.Formatter(fmt="%(levelname)s: %(message)s")
|
||||||
|
|
||||||
|
if info_handler is None:
|
||||||
|
info_handler = logging.StreamHandler(sys.stdout)
|
||||||
|
info_handler.addFilter(LevelFilter(logging.DEBUG, logging.INFO))
|
||||||
|
info_handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(info_handler)
|
||||||
|
info_handler.setLevel(target_level)
|
||||||
|
|
||||||
|
if error_handler is None:
|
||||||
|
error_handler = logging.StreamHandler(sys.stderr)
|
||||||
|
error_handler.setLevel(logging.WARNING)
|
||||||
|
error_handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(error_handler)
|
||||||
|
|
||||||
|
if log_file:
|
||||||
|
if not file_handlers:
|
||||||
|
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
file_handler = logging.FileHandler(log_file, encoding="utf-8")
|
||||||
|
file_handler.setLevel(logging.DEBUG)
|
||||||
|
file_formatter = logging.Formatter(
|
||||||
|
fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||||
|
datefmt="%Y-%m-%d %H:%M:%S"
|
||||||
|
)
|
||||||
|
file_handler.setFormatter(file_formatter)
|
||||||
|
logger.addHandler(file_handler)
|
||||||
|
else:
|
||||||
|
for handler in file_handlers:
|
||||||
|
handler.close()
|
||||||
|
logger.removeHandler(handler)
|
||||||
|
|
||||||
|
return logger
|
||||||
|
|
||||||
|
|
||||||
|
def get_logger() -> logging.Logger:
|
||||||
|
return logging.getLogger("skywipe")
|
||||||
207
skywipe/operations.py
Normal file
207
skywipe/operations.py
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
"""Shared operation utilities and strategies for Skywipe"""
|
||||||
|
|
||||||
|
import time
|
||||||
|
from typing import Callable, Optional, Any
|
||||||
|
from atproto import models
|
||||||
|
|
||||||
|
from .auth import Auth
|
||||||
|
from .configure import Configuration
|
||||||
|
from .logger import get_logger, ProgressTracker
|
||||||
|
|
||||||
|
|
||||||
|
class OperationContext:
|
||||||
|
def __init__(self, client=None, config_data=None):
|
||||||
|
self.logger = get_logger()
|
||||||
|
|
||||||
|
if client is not None:
|
||||||
|
self.client = client
|
||||||
|
self.did = client.me.did
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
self.auth = Auth()
|
||||||
|
self.client = self.auth.login()
|
||||||
|
self.did = self.client.me.did
|
||||||
|
except (ValueError, FileNotFoundError) as e:
|
||||||
|
self.logger.error(f"Configuration error: {e}")
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(
|
||||||
|
f"Unexpected error during initialization: {e}", exc_info=True)
|
||||||
|
raise ValueError(
|
||||||
|
f"Failed to initialize operation context: {e}") from e
|
||||||
|
|
||||||
|
if config_data is not None:
|
||||||
|
self.config_data = config_data
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
self.config = Configuration()
|
||||||
|
self.config_data = self.config.load()
|
||||||
|
except (ValueError, FileNotFoundError) as e:
|
||||||
|
self.logger.error(f"Configuration error: {e}")
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(
|
||||||
|
f"Unexpected error loading configuration: {e}", exc_info=True)
|
||||||
|
raise ValueError(
|
||||||
|
f"Failed to load configuration: {e}") from e
|
||||||
|
|
||||||
|
self.batch_size = self.config_data.get("batch_size", 10)
|
||||||
|
self.delay = self.config_data.get("delay", 1)
|
||||||
|
|
||||||
|
|
||||||
|
class BaseStrategy:
|
||||||
|
def get_cursor(self, response):
|
||||||
|
return response.cursor
|
||||||
|
|
||||||
|
|
||||||
|
class RecordDeletionStrategy(BaseStrategy):
|
||||||
|
def __init__(self, collection: str):
|
||||||
|
self.collection = collection
|
||||||
|
|
||||||
|
def fetch(self, context: OperationContext, cursor: Optional[str] = None):
|
||||||
|
list_params = models.ComAtprotoRepoListRecords.Params(
|
||||||
|
repo=context.did,
|
||||||
|
collection=self.collection,
|
||||||
|
limit=context.batch_size,
|
||||||
|
cursor=cursor
|
||||||
|
)
|
||||||
|
return context.client.com.atproto.repo.list_records(params=list_params)
|
||||||
|
|
||||||
|
def extract_items(self, response):
|
||||||
|
return response.records
|
||||||
|
|
||||||
|
def process_item(self, record, context: OperationContext):
|
||||||
|
record_uri = record.uri
|
||||||
|
rkey = record_uri.rsplit("/", 1)[-1]
|
||||||
|
delete_data = {
|
||||||
|
"repo": context.did,
|
||||||
|
"collection": self.collection,
|
||||||
|
"rkey": rkey
|
||||||
|
}
|
||||||
|
context.client.com.atproto.repo.delete_record(data=delete_data)
|
||||||
|
context.logger.debug(f"Deleted: {record_uri}")
|
||||||
|
|
||||||
|
|
||||||
|
class FeedStrategy(BaseStrategy):
|
||||||
|
def fetch(self, context: OperationContext, cursor: Optional[str] = None):
|
||||||
|
if cursor:
|
||||||
|
return context.client.get_author_feed(
|
||||||
|
actor=context.did, limit=context.batch_size, cursor=cursor
|
||||||
|
)
|
||||||
|
return context.client.get_author_feed(actor=context.did, limit=context.batch_size)
|
||||||
|
|
||||||
|
def extract_items(self, response):
|
||||||
|
return response.feed
|
||||||
|
|
||||||
|
def process_item(self, post, context: OperationContext):
|
||||||
|
uri = post.post.uri
|
||||||
|
context.client.delete_post(uri)
|
||||||
|
context.logger.debug(f"Deleted post: {uri}")
|
||||||
|
|
||||||
|
|
||||||
|
class BookmarkStrategy(BaseStrategy):
|
||||||
|
def fetch(self, context: OperationContext, cursor: Optional[str] = None):
|
||||||
|
get_params = models.AppBskyBookmarkGetBookmarks.Params(
|
||||||
|
limit=context.batch_size,
|
||||||
|
cursor=cursor
|
||||||
|
)
|
||||||
|
return context.client.app.bsky.bookmark.get_bookmarks(params=get_params)
|
||||||
|
|
||||||
|
def extract_items(self, response):
|
||||||
|
return response.bookmarks
|
||||||
|
|
||||||
|
def process_item(self, bookmark, context: OperationContext):
|
||||||
|
bookmark_uri = self._extract_bookmark_uri(bookmark)
|
||||||
|
if not bookmark_uri:
|
||||||
|
raise ValueError("Unable to find bookmark URI")
|
||||||
|
|
||||||
|
delete_data = models.AppBskyBookmarkDeleteBookmark.Data(
|
||||||
|
uri=bookmark_uri)
|
||||||
|
context.client.app.bsky.bookmark.delete_bookmark(data=delete_data)
|
||||||
|
context.logger.debug(f"Deleted bookmark: {bookmark_uri}")
|
||||||
|
|
||||||
|
def _extract_bookmark_uri(self, bookmark):
|
||||||
|
if hasattr(bookmark, "uri"):
|
||||||
|
return bookmark.uri
|
||||||
|
|
||||||
|
for attr_name in ("subject", "record", "post", "item"):
|
||||||
|
if hasattr(bookmark, attr_name):
|
||||||
|
nested = getattr(bookmark, attr_name)
|
||||||
|
if hasattr(nested, "uri"):
|
||||||
|
return nested.uri
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class Operation:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
operation_name: str,
|
||||||
|
strategy_type: str = "feed",
|
||||||
|
collection: Optional[str] = None,
|
||||||
|
filter_fn: Optional[Callable[[Any], bool]] = None,
|
||||||
|
client=None,
|
||||||
|
config_data=None
|
||||||
|
):
|
||||||
|
self.operation_name = operation_name
|
||||||
|
self.filter_fn = filter_fn
|
||||||
|
self._client = client
|
||||||
|
self._config_data = config_data
|
||||||
|
|
||||||
|
if strategy_type == "record":
|
||||||
|
if not collection:
|
||||||
|
raise ValueError("Collection is required for record strategy")
|
||||||
|
self.strategy = RecordDeletionStrategy(collection)
|
||||||
|
elif strategy_type == "bookmark":
|
||||||
|
self.strategy = BookmarkStrategy()
|
||||||
|
else:
|
||||||
|
self.strategy = FeedStrategy()
|
||||||
|
|
||||||
|
def run(self) -> int:
|
||||||
|
context = OperationContext(
|
||||||
|
client=self._client, config_data=self._config_data)
|
||||||
|
progress = ProgressTracker(operation=self.operation_name)
|
||||||
|
|
||||||
|
context.logger.info(
|
||||||
|
f"Starting {self.operation_name} with batch_size={context.batch_size}, delay={context.delay}s"
|
||||||
|
)
|
||||||
|
|
||||||
|
cursor = None
|
||||||
|
total_processed = 0
|
||||||
|
batch_num = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
batch_num += 1
|
||||||
|
try:
|
||||||
|
response = self.strategy.fetch(context, cursor)
|
||||||
|
items = self.strategy.extract_items(response)
|
||||||
|
except Exception as e:
|
||||||
|
context.logger.error(
|
||||||
|
f"Error fetching items for batch {batch_num}: {e}", exc_info=True)
|
||||||
|
break
|
||||||
|
|
||||||
|
if not items:
|
||||||
|
break
|
||||||
|
|
||||||
|
progress.batch(batch_num, len(items))
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
if self.filter_fn and not self.filter_fn(item):
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.strategy.process_item(item, context)
|
||||||
|
total_processed += 1
|
||||||
|
progress.update(1)
|
||||||
|
except Exception as e:
|
||||||
|
context.logger.error(f"Error processing item: {e}")
|
||||||
|
|
||||||
|
cursor = self.strategy.get_cursor(response)
|
||||||
|
if not cursor:
|
||||||
|
break
|
||||||
|
|
||||||
|
if context.delay > 0:
|
||||||
|
time.sleep(context.delay)
|
||||||
|
|
||||||
|
context.logger.info(
|
||||||
|
f"{self.operation_name}: {total_processed} items processed.")
|
||||||
|
return total_processed
|
||||||
70
skywipe/post_analysis.py
Normal file
70
skywipe/post_analysis.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
"""Post analysis utilities for Skywipe"""
|
||||||
|
|
||||||
|
|
||||||
|
class PostAnalyzer:
|
||||||
|
MEDIA_TYPES = {
|
||||||
|
'app.bsky.embed.images',
|
||||||
|
'app.bsky.embed.video',
|
||||||
|
'app.bsky.embed.external'
|
||||||
|
}
|
||||||
|
|
||||||
|
QUOTE_TYPES = {
|
||||||
|
'app.bsky.embed.record',
|
||||||
|
'app.bsky.embed.recordWithMedia',
|
||||||
|
'app.bsky.embed.record_with_media'
|
||||||
|
}
|
||||||
|
|
||||||
|
QUOTE_WITH_MEDIA_TYPES = {
|
||||||
|
'app.bsky.embed.recordWithMedia',
|
||||||
|
'app.bsky.embed.record_with_media'
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _get_embed(post_record):
|
||||||
|
return getattr(post_record, 'embed', None)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _get_embed_type_base(embed):
|
||||||
|
embed_type = getattr(embed, 'py_type', None)
|
||||||
|
if embed_type:
|
||||||
|
return embed_type.split('#')[0]
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def has_media(post_record):
|
||||||
|
embed = PostAnalyzer._get_embed(post_record)
|
||||||
|
if not embed:
|
||||||
|
return False
|
||||||
|
|
||||||
|
embed_type_base = PostAnalyzer._get_embed_type_base(embed)
|
||||||
|
if embed_type_base:
|
||||||
|
if embed_type_base in PostAnalyzer.MEDIA_TYPES:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if embed_type_base in PostAnalyzer.QUOTE_WITH_MEDIA_TYPES:
|
||||||
|
media = getattr(embed, 'media', None)
|
||||||
|
if media:
|
||||||
|
media_type_base = PostAnalyzer._get_embed_type_base(media)
|
||||||
|
if media_type_base and media_type_base in PostAnalyzer.MEDIA_TYPES:
|
||||||
|
return True
|
||||||
|
|
||||||
|
for attr in ('images', 'video', 'external'):
|
||||||
|
if hasattr(embed, attr):
|
||||||
|
return True
|
||||||
|
if isinstance(embed, dict) and embed.get(attr):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def has_quote(post_record):
|
||||||
|
embed = PostAnalyzer._get_embed(post_record)
|
||||||
|
if not embed:
|
||||||
|
return False
|
||||||
|
|
||||||
|
embed_type_base = PostAnalyzer._get_embed_type_base(embed)
|
||||||
|
if embed_type_base and embed_type_base in PostAnalyzer.QUOTE_TYPES:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return (hasattr(embed, 'record') or
|
||||||
|
(isinstance(embed, dict) and embed.get('record')))
|
||||||
27
skywipe/safeguard.py
Normal file
27
skywipe/safeguard.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
"""Safeguard module for Skywipe"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from .logger import get_logger
|
||||||
|
|
||||||
|
|
||||||
|
CONFIRM_RESPONSES = {"yes", "y"}
|
||||||
|
|
||||||
|
|
||||||
|
def require_confirmation(operation: str, skip_confirmation: bool = False) -> None:
|
||||||
|
if skip_confirmation:
|
||||||
|
return
|
||||||
|
|
||||||
|
logger = get_logger()
|
||||||
|
logger.warning(f"This will {operation}")
|
||||||
|
logger.warning("This operation is DESTRUCTIVE and cannot be undone!")
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = input(
|
||||||
|
"Are you sure you want to continue? (y/N): ").strip().lower()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
logger.info("\nOperation cancelled.")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
if response not in CONFIRM_RESPONSES:
|
||||||
|
logger.info("Operation cancelled.")
|
||||||
|
sys.exit(0)
|
||||||
Reference in New Issue
Block a user