-
Notifications
You must be signed in to change notification settings - Fork 18
/
terminus_browser.py
executable file
·213 lines (164 loc) · 6.9 KB
/
terminus_browser.py
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
#!/usr/bin/env python3
import sys, urwid, time, os
import requests, json, collections, re
import urwid.raw_display
import urwid.web_display
from enum import Enum
# add sys to path so you don't have to sys.
sys.path.append('src')
from config import Config
from views.view_class import View
from frames.default_frame import DefaultFrame
from debug import setupLogger
from split_tracker import Column, Row, buildUrwidFromSplits
from custom_urwid_classes import CommandBar, HistoryButton
from command_handler_class import CommandHandler
from customer_types import LEVEL, MODE, SITE, STICKIES
import asyncio
loop = asyncio.get_event_loop()
import logging
log = logging.getLogger(__name__)
################################################################################
class urwidView():
KEYMAP = {
'h': 'left',
'j': 'down',
'k': 'up',
'l': 'right'
}
def __init__(self, test=False):
self.mode = MODE.NORMAL
self.stickies = STICKIES.HIDE
self.cfg = Config()
self.test = test
self.mL = None
self.commandHandler = CommandHandler(self)
self.commandBar = CommandBar(lambda: self._update_focus(True), self)
urwid.connect_signal(self.commandBar, 'command_entered', self.commandHandler.routeCommand)
urwid.connect_signal(self.commandBar, 'exit_command', self.exitCommand)
self.idList = []
self.history = []
self.watched = {}
self.totalNewPosts = 0
self.palette = [
('body', 'light gray', 'black', 'standout'),
('quote', 'light cyan', 'black'),
('greenText', 'dark green', 'black'),
('header', 'white', 'dark red', 'bold'),
('quotePreview', 'light gray', 'black')
]
# use appropriate Screen class
if urwid.web_display.is_web_request():
self.screen = urwid.web_display.Screen()
else:
self.screen = urwid.raw_display.Screen()
self.buildSetStartView()
self.body = None
self.splitTuple = self.currFocusView
self.buildAddHeaderView(self.currFocusView)
self.buildAddFooterView(self.currFocusView)
def getFreeID(self):
ID = 1
while ID in self.idList:
ID += 1
return ID
def exitCommand(self):
self.mode = MODE.NORMAL
self.buildAddFooterView(self.currFocusView)
self.commandBar.set_caption('')
self.body.focus_position = 'body'
self.renderScreen()
def _update_focus(self, focus):
self._focus=focus
def buildAddHeaderView(self, focusView):
try:
headerStringLeft = urwid.AttrWrap(urwid.Text(focusView.frame.headerString), 'header')
except:
headerStringLeft = urwid.AttrWrap(urwid.Text(''), 'header')
if len(self.watched) > 0:
headerStringRight = urwid.AttrWrap(urwid.Text(str(self.totalNewPosts) + ' new posts in ' + str(len(self.watched)) + ' watched thread(s)', 'right'), 'header')
else:
headerStringRight = urwid.AttrWrap(urwid.Text(''), 'header')
builtUrwidSplits = buildUrwidFromSplits(self.splitTuple)
log.debug(type(builtUrwidSplits))
self.body = urwid.Frame(urwid.AttrWrap(builtUrwidSplits, 'body'))
headerWidget = urwid.Columns([headerStringLeft, headerStringRight])
self.body.header = headerWidget
def buildAddFooterView(self, focusView):
try:
footerStringLeft = urwid.AttrWrap(urwid.Text('Mode: ' + str(self.mode) + ', Filter: ' + str(self.currFocusView.uFilter)), 'header')
footerStringRight = urwid.AttrWrap(urwid.Text(focusView.frame.footerStringRight, 'right'), 'header')
except:
footerStringLeft = urwid.Text('')
footerStringRight = urwid.Text('')
footerWidget = urwid.Pile([urwid.Columns([footerStringLeft, footerStringRight]), self.commandBar])
self.body.footer = footerWidget
def buildSetStartView(self):
self.currFocusView = View(self, DefaultFrame(True, self.test))
# self.currFocusView = View(self)
def watcherUpdate(self, something, somethingElse):
def getThreadSize(url):
response = requests.get(url, headers=None)
data = response.json()
try:
return len(data["posts"])
except:
return None
self.totalNewPosts = 0
for url, tDict in self.watched.items():
tS = getThreadSize(url)
if not tS:
tDict['isArchived'] = None
continue
if tS > tDict['numReplies']:
self.totalNewPosts += tS - tDict['numReplies']
self.buildAddHeaderView(self.currFocusView)
self.buildAddFooterView(self.currFocusView)
self.renderScreen()
self.mL.set_alarm_in(30, self.watcherUpdate)
log.debug(f'alarm triggered, watcher updated, {str(self.totalNewPosts)} new posts')
def renderScreen(self):
if __name__ == '__main__': # for testing purposes don't render outside file
if self.mL == None:
self.mL = urwid.MainLoop(self.body,
self.palette,
screen=self.screen,
# event_loop=urwid.AsyncioEventLoop(loop=loop),
unhandled_input=self.handleKey,
pop_ups=True)
self.mL.set_alarm_in(30, self.watcherUpdate)
self.mL.run()
else:
self.mL.widget = self.body
# self.mL.draw_screen()
def handleKey(self, key):
if not isinstance(key, tuple): # avoid mouse click event tuples
if key == ':':
self.mode = MODE.COMMAND
self.commandBar.set_caption(':')
self.body.focus_position = 'footer'
self.renderScreen()
if self.mode is MODE.NORMAL:
if key.isalpha():
key = key.lower()
if key not in urwidView.KEYMAP:
return
rows, cols = urwid.raw_display.Screen().get_cols_rows()
self.body.keypress((rows, cols), urwidView.KEYMAP[key])
################################################################################
def main():
u = urwidView()
u.renderScreen()
def setup():
urwid.web_display.set_preferences("Urwid Tour")
# try to handle short web requests quickly
if urwid.web_display.handle_short_request():
return
main()
def refresh_log():
if os.path.exists("debug.log"):
os.remove("debug.log")
if __name__ == '__main__' or urwid.web_display.is_web_request():
refresh_log()
setupLogger()
setup()