notionary 0.2.14__py3-none-any.whl → 0.2.16__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
notionary/cli/main.py DELETED
@@ -1,376 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Notionary CLI - Integration Key Setup
4
- """
5
-
6
- import click
7
- import os
8
- import platform
9
- import asyncio
10
- import logging
11
- from pathlib import Path
12
- from dotenv import load_dotenv
13
- from rich.console import Console
14
- from rich.panel import Panel
15
- from rich.prompt import Prompt, Confirm
16
- from rich.table import Table
17
- from rich import box
18
- from rich.progress import Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
19
- from notionary.workspace import NotionWorkspace
20
-
21
-
22
- # Disable logging for CLI usage
23
- def disable_notionary_logging():
24
- """Disable logging for notionary modules when used in CLI"""
25
- # Option 1: Set to WARNING level (recommended for CLI)
26
- logging.getLogger("notionary").setLevel(logging.WARNING)
27
- logging.getLogger("DatabaseDiscovery").setLevel(logging.WARNING)
28
- logging.getLogger("NotionClient").setLevel(logging.WARNING)
29
-
30
-
31
- def enable_verbose_logging():
32
- """Enable verbose logging for debugging (use with --verbose flag)"""
33
- logging.getLogger("notionary").setLevel(logging.DEBUG)
34
- logging.getLogger("DatabaseDiscovery").setLevel(logging.DEBUG)
35
- logging.getLogger("NotionClient").setLevel(logging.DEBUG)
36
-
37
-
38
- # Initialize logging configuration for CLI
39
- disable_notionary_logging()
40
-
41
- console = Console()
42
-
43
-
44
- def get_paste_tips():
45
- """Get platform-specific paste tips"""
46
- system = platform.system().lower()
47
-
48
- if system == "darwin": # macOS
49
- return [
50
- "• Terminal: [cyan]Cmd+V[/cyan]",
51
- "• iTerm2: [cyan]Cmd+V[/cyan]",
52
- ]
53
- elif system == "windows":
54
- return [
55
- "• PowerShell: [cyan]Right-click[/cyan] or [cyan]Shift+Insert[/cyan]",
56
- "• cmd: [cyan]Right-click[/cyan]",
57
- ]
58
- else: # Linux and others
59
- return [
60
- "• Terminal: [cyan]Ctrl+Shift+V[/cyan] or [cyan]Right-click[/cyan]",
61
- "• Some terminals: [cyan]Shift+Insert[/cyan]",
62
- ]
63
-
64
-
65
- def show_paste_tips():
66
- """Show platform-specific paste tips"""
67
- console.print("\n[bold yellow]💡 Paste Tips:[/bold yellow]")
68
- for tip in get_paste_tips():
69
- console.print(tip)
70
- console.print()
71
-
72
-
73
- def get_notion_secret() -> str:
74
- """Get NOTION_SECRET using the same logic as NotionClient"""
75
- load_dotenv()
76
- return os.getenv("NOTION_SECRET", "")
77
-
78
-
79
- async def fetch_notion_databases_with_progress():
80
- """Fetch databases using DatabaseDiscovery with progress animation"""
81
- try:
82
- workspace = NotionWorkspace()
83
-
84
- # Create progress display with custom spinner
85
- with Progress(
86
- SpinnerColumn(spinner_name="dots12", style="cyan"),
87
- TextColumn("[bold blue]Discovering databases..."),
88
- TimeElapsedColumn(),
89
- console=console,
90
- transient=True,
91
- ) as progress:
92
- # Add progress task
93
- task = progress.add_task("Fetching...", total=None)
94
-
95
- # Fetch databases
96
- databases = await workspace.list_all_databases(limit=50)
97
-
98
- # Update progress to show completion
99
- progress.update(
100
- task, description=f"[bold green]Found {len(databases)} databases!"
101
- )
102
-
103
- # Brief pause to show completion
104
- await asyncio.sleep(0.5)
105
-
106
- return {"databases": databases, "success": True}
107
-
108
- except Exception as e:
109
- return {"error": str(e), "success": False}
110
-
111
-
112
- def show_databases_overview(api_key: str):
113
- """Show available databases with nice formatting"""
114
- console.print("\n[bold blue]🔍 Connecting to Notion...[/bold blue]")
115
-
116
- # Run async function in sync context
117
- try:
118
- result = asyncio.run(fetch_notion_databases_with_progress())
119
- except Exception as e:
120
- console.print(
121
- Panel.fit(
122
- f"[bold red]❌ Unexpected error[/bold red]\n\n"
123
- f"[red]{str(e)}[/red]\n\n"
124
- "[yellow]Please check:[/yellow]\n"
125
- "• Your internet connection\n"
126
- "• Your integration key validity\n"
127
- "• Try running the command again",
128
- title="Connection Error",
129
- )
130
- )
131
- return
132
-
133
- if not result["success"]:
134
- console.print(
135
- Panel.fit(
136
- f"[bold red]❌ Could not fetch databases[/bold red]\n\n"
137
- f"[red]{result['error']}[/red]\n\n"
138
- "[yellow]Common issues:[/yellow]\n"
139
- "• Check your integration key\n"
140
- "• Make sure your integration has access to databases\n"
141
- "• Visit your integration settings to grant access",
142
- title="Connection Error",
143
- )
144
- )
145
- return
146
-
147
- databases = result["databases"]
148
-
149
- if not databases:
150
- console.print(
151
- Panel.fit(
152
- "[bold yellow]⚠️ No databases found[/bold yellow]\n\n"
153
- "Your integration key is valid, but no databases are accessible.\n\n"
154
- "[bold blue]To grant access:[/bold blue]\n"
155
- "1. Go to any Notion database\n"
156
- "2. Click the '...' menu (top right)\n"
157
- "3. Go to 'Add connections'\n"
158
- "4. Find and select your integration\n\n"
159
- "[cyan]https://www.notion.so/help/add-and-manage-connections-with-the-api[/cyan]",
160
- title="No Databases Available",
161
- )
162
- )
163
- return
164
-
165
- # Create beautiful table
166
- table = Table(
167
- title=f"📊 Available Databases ({len(databases)} found)",
168
- box=box.ROUNDED,
169
- title_style="bold green",
170
- header_style="bold cyan",
171
- )
172
-
173
- table.add_column("#", style="dim", justify="right", width=3)
174
- table.add_column("Database Name", style="bold white", min_width=25)
175
- table.add_column("ID", style="dim cyan", min_width=36)
176
-
177
- for i, (title, db_id) in enumerate(databases, 1):
178
- table.add_row(str(i), title or "Untitled Database", db_id)
179
-
180
- console.print("\n")
181
- console.print(table)
182
-
183
- # Success message with next steps
184
- console.print(
185
- Panel.fit(
186
- "[bold green]🎉 Setup Complete![/bold green]\n\n"
187
- f"Found [bold cyan]{len(databases)}[/bold cyan] accessible database(s).\n"
188
- "You can now use notionary in your Python code!\n\n"
189
- "[bold yellow]💡 Tip:[/bold yellow] Run [cyan]notionary db[/cyan] anytime to see this overview again.",
190
- title="Ready to Go!",
191
- )
192
- )
193
-
194
-
195
- @click.group()
196
- @click.version_option() # Automatische Version aus setup.py
197
- @click.option("--verbose", "-v", is_flag=True, help="Enable verbose logging")
198
- def main(verbose):
199
- """
200
- Notionary CLI - Notion API Integration
201
- """
202
- if verbose:
203
- enable_verbose_logging()
204
- console.print("[dim]Verbose logging enabled[/dim]")
205
- pass
206
-
207
-
208
- @main.command()
209
- def init():
210
- """
211
- Setup your Notion Integration Key
212
- """
213
- # Check if key already exists
214
- existing_key = get_notion_secret()
215
-
216
- if existing_key:
217
- console.print(
218
- Panel.fit(
219
- "[bold green]✅ You're all set![/bold green]\n"
220
- f"Your Notion Integration Key is already configured.\n"
221
- f"Key: [dim]{existing_key[:8]}...[/dim]",
222
- title="Already Configured",
223
- )
224
- )
225
-
226
- # Option to reconfigure or show databases
227
- choice = Prompt.ask(
228
- "\n[yellow]What would you like to do?[/yellow]",
229
- choices=["show", "update", "exit"],
230
- default="show",
231
- )
232
-
233
- if choice == "show":
234
- show_databases_overview(existing_key)
235
- elif choice == "update":
236
- setup_new_key()
237
- else:
238
- console.print("\n[blue]Happy coding! 🚀[/blue]")
239
- else:
240
- # No key found, start setup
241
- console.print(
242
- Panel.fit(
243
- "[bold green]🚀 Notionary Setup[/bold green]\n"
244
- "Enter your Notion Integration Key to get started...\n\n"
245
- "[bold blue]🔗 Create an Integration Key or get an existing one:[/bold blue]\n"
246
- "[cyan]https://www.notion.so/profile/integrations[/cyan]",
247
- title="Initialization",
248
- )
249
- )
250
- setup_new_key()
251
-
252
-
253
- @main.command()
254
- def db() -> None:
255
- """
256
- Show available Notion databases
257
- """
258
- existing_key = get_notion_secret()
259
-
260
- if not existing_key:
261
- console.print(
262
- Panel.fit(
263
- "[bold red]❌ No Integration Key found![/bold red]\n\n"
264
- "Please run [cyan]notionary init[/cyan] first to set up your key.",
265
- title="Not Configured",
266
- )
267
- )
268
- return
269
-
270
- show_databases_overview(existing_key)
271
-
272
-
273
- def setup_new_key():
274
- """Handle the key setup process"""
275
- try:
276
- # Show Integration Key creation link
277
- console.print("\n[bold blue]🔗 Create an Integration Key:[/bold blue]")
278
- console.print("[cyan]https://www.notion.so/profile/integrations[/cyan]")
279
- console.print()
280
-
281
- # Get integration key
282
- integration_key = Prompt.ask("[bold cyan]Notion Integration Key[/bold cyan]")
283
-
284
- # Input validation
285
- if not integration_key or not integration_key.strip():
286
- console.print("[bold red]❌ Integration Key cannot be empty![/bold red]")
287
- return
288
-
289
- # Trim whitespace
290
- integration_key = integration_key.strip()
291
-
292
- # Check for common paste issues
293
- if integration_key in ["^V", "^v", "^C", "^c"]:
294
- console.print("[bold red]❌ Paste didn't work! Try:[/bold red]")
295
- show_paste_tips()
296
- return
297
-
298
- # Show masked feedback that paste worked
299
- masked_key = "•" * len(integration_key)
300
- console.print(
301
- f"[dim]Received: {masked_key} ({len(integration_key)} characters)[/dim]"
302
- )
303
-
304
- # Basic validation for Notion keys
305
- if not integration_key.startswith("ntn_") or len(integration_key) < 30:
306
- console.print(
307
- "[bold yellow]⚠️ Warning: This doesn't look like a valid Notion Integration Key[/bold yellow]"
308
- )
309
- console.print(
310
- "[dim]Notion keys usually start with 'ntn_' and are about 50+ characters long[/dim]"
311
- )
312
- if not Confirm.ask("Continue anyway?"):
313
- return
314
-
315
- # Save the key
316
- if save_integration_key(integration_key):
317
- # Show databases overview after successful setup
318
- show_databases_overview(integration_key)
319
-
320
- except KeyboardInterrupt:
321
- console.print("\n[yellow]Setup cancelled.[/yellow]")
322
- except Exception as e:
323
- console.print(f"\n[bold red]❌ Error during setup: {e}[/bold red]")
324
- raise click.Abort()
325
-
326
-
327
- def save_integration_key(integration_key: str) -> bool:
328
- """Save the integration key to .env file"""
329
- try:
330
- # .env Datei im aktuellen Verzeichnis erstellen/aktualisieren
331
- env_file = Path.cwd() / ".env"
332
-
333
- # Bestehende .env lesen falls vorhanden
334
- existing_lines = []
335
- if env_file.exists():
336
- with open(env_file, "r", encoding="utf-8") as f:
337
- existing_lines = [line.rstrip() for line in f.readlines()]
338
-
339
- # NOTION_SECRET Zeile hinzufügen/ersetzen
340
- updated_lines = []
341
- notion_secret_found = False
342
-
343
- for line in existing_lines:
344
- if line.startswith("NOTION_SECRET="):
345
- updated_lines.append(f"NOTION_SECRET={integration_key}")
346
- notion_secret_found = True
347
- else:
348
- updated_lines.append(line)
349
-
350
- # Falls NOTION_SECRET noch nicht existiert, hinzufügen
351
- if not notion_secret_found:
352
- updated_lines.append(f"NOTION_SECRET={integration_key}")
353
-
354
- # .env Datei schreiben
355
- with open(env_file, "w", encoding="utf-8") as f:
356
- f.write("\n".join(updated_lines) + "\n")
357
-
358
- # Verification
359
- written_key = get_notion_secret()
360
- if written_key == integration_key:
361
- console.print(
362
- "\n[bold green]✅ Integration Key saved and verified![/bold green]"
363
- )
364
- console.print(f"[dim]Configuration: {env_file}[/dim]")
365
- return True
366
- else:
367
- console.print("\n[bold red]❌ Error: Key verification failed![/bold red]")
368
- return False
369
-
370
- except Exception as e:
371
- console.print(f"\n[bold red]❌ Error saving key: {e}[/bold red]")
372
- return False
373
-
374
-
375
- if __name__ == "__main__":
376
- main()
@@ -1,117 +0,0 @@
1
- import asyncio
2
- from dataclasses import dataclass
3
- from notionary import NotionDatabase
4
-
5
-
6
- @dataclass
7
- class OnboardingPageResult:
8
- url: str
9
- tile: str
10
- emoji: str
11
-
12
-
13
- async def generate_doc_for_database(
14
- datbase_name: str,
15
- ) -> OnboardingPageResult:
16
- database = await NotionDatabase.from_database_name(datbase_name)
17
- page = await database.create_blank_page()
18
-
19
- page_title = "Welcome to Notionary!"
20
- page_icon = "📚"
21
-
22
- markdown_content = """!> [🚀] This page was created fully automatically and serves as a showcase of what is possible with Notionary.
23
-
24
- ---
25
-
26
- ## 🗃️ Working with Databases
27
-
28
- Discover and manage your Notion databases programmatically:
29
-
30
- ```python
31
- import asyncio
32
- from notionary import NotionDatabase, DatabaseDiscovery
33
-
34
- async def main():
35
- # Discover available databases
36
- discovery = DatabaseDiscovery()
37
- await discovery()
38
-
39
- # Connect to a database by name
40
- db = await NotionDatabase.from_database_name("Projects")
41
-
42
- # Create a new page in the database
43
- page = await db.create_blank_page()
44
-
45
- # Query pages from database
46
- async for page in db.iter_pages():
47
- title = await page.get_title()
48
- print(f"Page: {title}")
49
-
50
- if __name__ == "__main__":
51
- asyncio.run(main())
52
- ```
53
-
54
- ## 📄 Creating and Managing Pages
55
- Create and update Notion pages with rich content:
56
- ```python
57
- import asyncio
58
- from notionary import NotionPage
59
-
60
- async def main():
61
- # Create a page from URL
62
- page = NotionPage.from_url("https://www.notion.so/your-page-url")
63
-
64
- # Or find by name
65
- page = await NotionPage.from_page_name("My Project Page")
66
-
67
- # Update page metadata
68
- await page.set_title("Updated Title")
69
- await page.set_emoji_icon("🚀")
70
- await page.set_random_gradient_cover()
71
-
72
- # Add markdown content
73
- markdown = '''
74
- # Project Overview
75
-
76
- !> [💡] This page was created programmatically using Notionary.
77
-
78
- ## Features
79
- - **Rich** Markdown support
80
- - Async functionality
81
- - Custom syntax extensions
82
- '''
83
-
84
- await page.replace_content(markdown)
85
-
86
- if __name__ == "__main__":
87
- asyncio.run(main())
88
- ```
89
-
90
- ## 📊 Tables and Structured Data
91
- Create tables for organizing information:
92
- FeatureStatusPriorityAPI IntegrationCompleteHighDocumentationIn ProgressMediumDatabase QueriesCompleteHighFile UploadsCompleteMedium
93
-
94
- 🎥 Media Embedding
95
- Embed videos directly in your pages:
96
- @[Caption](https://www.youtube.com/watch?v=dQw4w9WgXcQ) - Never gonna give you up!
97
-
98
- Happy building with Notionary! 🎉"""
99
-
100
- await page.set_title(page_title)
101
- await page.set_emoji_icon(page_icon)
102
- await page.set_random_gradient_cover()
103
- await page.append_markdown(markdown_content)
104
-
105
- url = await page.get_url()
106
-
107
- return OnboardingPageResult(
108
- url=url,
109
- tile=page_title,
110
- emoji=page_icon,
111
- )
112
-
113
-
114
- if __name__ == "__main__":
115
- print("🚀 Starting Notionary onboarding page generation...")
116
- result = asyncio.run(generate_doc_for_database("Wissen & Notizen"))
117
- print(f"✅ Onboarding page created: {result.tile} {result.emoji} - {result.url}")