Repository navigation
Expand file tree
/
Copy pathtabnews_cli.py
More file actions
419 lines (360 loc) · 14.2 KB
/
Copy pathtabnews_cli.py
File metadata and controls
419 lines (360 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import requests
import json
import os
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from rich.markdown import Markdown
from rich.prompt import Prompt
from rich.table import Table
from prompt_toolkit import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout import Layout, HSplit, VSplit
from prompt_toolkit.widgets import TextArea, Frame, Button
from prompt_toolkit.styles import Style
from prompt_toolkit.layout.containers import Window, WindowAlign, ConditionalContainer
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.layout.dimension import D
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.filters import Condition
import asyncio
from typing import List, Dict, Any
import markdown2
import re
import textwrap
import math
console = Console()
BASE_URL = "https://www.tabnews.com.br/api/v1"
class TabNewsAPI:
def __init__(self):
self.session = requests.Session()
self.token = None
load_dotenv()
self.token = os.getenv("TABNEWS_TOKEN")
def get_contents(self, page: int = 1, per_page: int = 10, strategy: str = "relevant"):
url = f"{BASE_URL}/contents"
params = {
"page": page,
"per_page": per_page,
"strategy": strategy
}
response = self.session.get(url, params=params)
if response.status_code != 200:
error_data = response.json()
error_message = error_data.get("message", "Unknown error")
raise Exception(f"API Error ({response.status_code}): {error_message}")
return response.json()
def get_user_contents(self, username: str, page: int = 1, per_page: int = 10, strategy: str = "relevant"):
url = f"{BASE_URL}/contents/{username}"
params = {
"page": page,
"per_page": per_page,
"strategy": strategy
}
response = self.session.get(url, params=params)
if response.status_code != 200:
error_data = response.json()
error_message = error_data.get("message", "Unknown error")
raise Exception(f"API Error ({response.status_code}): {error_message}")
return response.json()
def get_content(self, username: str, slug: str):
url = f"{BASE_URL}/contents/{username}/{slug}"
response = self.session.get(url)
if response.status_code != 200:
error_data = response.json()
error_message = error_data.get("message", "Unknown error")
raise Exception(f"API Error ({response.status_code}): {error_message}")
return response.json()
def get_comments(self, username: str, slug: str):
url = f"{BASE_URL}/contents/{username}/{slug}/children"
response = self.session.get(url)
if response.status_code != 200:
error_data = response.json()
error_message = error_data.get("message", "Unknown error")
raise Exception(f"API Error ({response.status_code}): {error_message}")
return response.json()
def login(self, email: str, password: str):
url = f"{BASE_URL}/sessions"
data = {
"email": email,
"password": password
}
response = self.session.post(url, json=data)
if response.status_code == 200:
self.token = response.json().get("token")
return True
return False
class TabNewsUI:
def __init__(self):
self.api = TabNewsAPI()
self.current_page = 1
self.current_strategy = "relevant"
self.selected_index = 0
self.contents = []
self.current_content = None
self.view_mode = "feed"
self.content_scroll_position = 0
self.comments = []
self.terminal_width = 80
self.terminal_height = 24
self.content_pages = []
self.current_content_page = 0
self.setup_ui()
def setup_ui(self):
self.kb = KeyBindings()
@self.kb.add('up')
def _(event):
if self.view_mode == "feed":
self.selected_index = max(0, self.selected_index - 1)
self.update_feed()
elif self.view_mode == "content":
self.current_content_page = max(0, self.current_content_page - 1)
self.update_content_view()
event.app.invalidate()
@self.kb.add('down')
def _(event):
if self.view_mode == "feed":
self.selected_index = min(len(self.contents) - 1, self.selected_index + 1)
self.update_feed()
elif self.view_mode == "content":
self.current_content_page = min(len(self.content_pages) - 1, self.current_content_page + 1)
self.update_content_view()
event.app.invalidate()
@self.kb.add('left')
def _(event):
if self.view_mode == "feed":
if self.current_page > 1:
self.current_page -= 1
self.selected_index = 0
self.update_feed()
event.app.invalidate()
@self.kb.add('right')
def _(event):
if self.view_mode == "feed":
self.current_page += 1
self.selected_index = 0
self.update_feed()
event.app.invalidate()
@self.kb.add('enter')
def _(event):
if self.view_mode == "feed" and self.contents:
content = self.contents[self.selected_index]
self.show_content(content)
elif self.view_mode == "content":
self.show_comments()
event.app.invalidate()
@self.kb.add('escape')
def _(event):
if self.view_mode == "content":
self.view_mode = "feed"
self.update_feed()
elif self.view_mode == "comments":
self.view_mode = "content"
self.update_content_view()
event.app.invalidate()
@self.kb.add('q')
def _(event):
event.app.exit()
@self.kb.add('c')
def _(event):
if self.view_mode == "content":
self.show_comments()
event.app.invalidate()
self.feed_control = FormattedTextControl("")
self.content_control = FormattedTextControl("")
self.comments_control = FormattedTextControl("")
self.header_window = Window(
height=1,
content=FormattedTextControl("TabNews CLI - ↑↓: Navigate | ←→: Pages | Enter: Select | Esc: Back | C: Comments | Q: Quit"),
style="class:header"
)
self.feed_window = Window(
content=self.feed_control,
style="class:feed"
)
self.content_window = Window(
content=self.content_control,
style="class:content"
)
self.comments_window = Window(
content=self.comments_control,
style="class:comments"
)
self.is_feed = Condition(lambda: self.view_mode == "feed")
self.is_content = Condition(lambda: self.view_mode == "content")
self.is_comments = Condition(lambda: self.view_mode == "comments")
self.feed_container = ConditionalContainer(
self.feed_window,
filter=self.is_feed
)
self.content_container = ConditionalContainer(
self.content_window,
filter=self.is_content
)
self.comments_container = ConditionalContainer(
self.comments_window,
filter=self.is_comments
)
self.layout = Layout(
HSplit([
self.header_window,
self.feed_container,
self.content_container,
self.comments_container
])
)
self.style = Style.from_dict({
'header': 'bg:ansiblue fg:white',
'feed': 'bg:ansiblack fg:white',
'content': 'bg:ansiblack fg:white',
'comments': 'bg:ansiblack fg:white',
'title': 'bold fg:ansiyellow',
'author': 'italic fg:ansigreen',
'date': 'fg:ansicyan',
'comment': 'fg:ansiyellow',
'page': 'bold fg:ansiyellow',
'separator': 'fg:ansiblue',
'page_number': 'fg:ansicyan'
})
self.app = Application(
layout=self.layout,
key_bindings=self.kb,
style=self.style,
full_screen=True
)
def wrap_text(self, text, width=80):
return textwrap.fill(text, width=width)
def format_markdown(self, text):
html = markdown2.markdown(text)
return HTML(html)
def split_into_pages(self, text, width=80, height=20):
wrapped_text = self.wrap_text(text, width=width)
lines = wrapped_text.split('\n')
pages = []
current_page = []
current_height = 0
for line in lines:
if current_height >= height:
pages.append('\n'.join(current_page))
current_page = []
current_height = 0
current_page.append(line)
current_height += 1
if current_page:
pages.append('\n'.join(current_page))
return pages
def update_feed(self):
feed_text = []
feed_text.append(f"[page]Page {self.current_page}[/page]")
feed_text.append("")
try:
self.contents = self.api.get_contents(self.current_page, 10, self.current_strategy)
for i, content in enumerate(self.contents):
prefix = "→ " if i == self.selected_index else " "
title = self.wrap_text(content['title'], width=self.terminal_width - 4)
author = content['owner_username']
feed_text.append(f"{prefix}{title}")
feed_text.append(f" by {author}")
feed_text.append("")
except Exception as e:
# Handle API errors and display them nicely in the feed view
error_message = str(e)
wrapped_error = self.wrap_text(error_message, width=self.terminal_width - 4)
feed_text.append("[title]Error fetching content[/title]")
feed_text.append("")
feed_text.append(wrapped_error)
feed_text.append("")
feed_text.append("Try again later or change page.")
self.contents = [] # Reset contents to empty list
self.feed_control.text = "\n".join(feed_text)
self.content_control.text = ""
self.comments_control.text = ""
def show_content(self, content):
self.view_mode = "content"
self.current_content_page = 0
try:
full_content = self.api.get_content(content["owner_username"], content["slug"])
self.current_content = full_content
self.prepare_content_pages()
self.update_content_view()
except Exception as e:
error_message = str(e)
self.content_pages = []
error_content = [
f"[title]Error loading content[/title]",
"",
self.wrap_text(error_message, width=self.terminal_width - 4),
"",
"Press Esc to go back to the feed."
]
self.content_pages.append("\n".join(error_content))
self.update_content_view()
def prepare_content_pages(self):
if not self.current_content:
return
content = self.current_content
title = self.wrap_text(content['title'], width=self.terminal_width - 4)
author = content['owner_username']
date = content['created_at']
body_pages = self.split_into_pages(
content['body'],
width=self.terminal_width - 4,
height=self.terminal_height - 6
)
self.content_pages = []
for i, page in enumerate(body_pages):
page_content = [
f"[title]{title}[/title]",
f"[author]by {author}[/author] | [date]{date}[/date]",
"",
"[separator]" + "─" * (self.terminal_width - 4) + "[/separator]",
"",
page,
"",
f"[page_number]Page {i + 1} of {len(body_pages)}[/page_number]"
]
self.content_pages.append("\n".join(page_content))
def update_content_view(self):
if not self.content_pages:
return
self.content_control.text = self.content_pages[self.current_content_page]
self.comments_control.text = ""
def show_comments(self):
if not self.current_content:
return
self.view_mode = "comments"
comments_text = []
try:
comments = self.api.get_comments(
self.current_content["owner_username"],
self.current_content["slug"]
)
for comment in comments:
author = comment['owner_username']
date = comment['created_at']
body = self.wrap_text(comment['body'], width=self.terminal_width - 4)
comments_text.extend([
f"[author]{author}[/author] | [date]{date}[/date]",
"",
body,
"",
"[separator]" + "─" * (self.terminal_width - 4) + "[/separator]",
""
])
except Exception as e:
error_message = str(e)
comments_text = [
"[title]Error loading comments[/title]",
"",
self.wrap_text(error_message, width=self.terminal_width - 4),
"",
"Press Esc to go back to the content."
]
self.comments_control.text = "\n".join(comments_text)
self.content_control.text = ""
def run(self):
self.update_feed()
self.app.run()
if __name__ == "__main__":
ui = TabNewsUI()
ui.run()