Files
  • main.py
main.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
print('Loading.',end='\r')

import sys
import tty
import string
import time
print('Loading..',end='\r')
import requests
import os
from datetime import datetime
import traceback
print('Loading...',end='\r')

headers = {'referrer': 'https://repl.it', 'X-Requested-With': 'repl-talk-terminal'}

def escape(code):
	return '\033['+code
def timeago(dt):
	if type(dt)==str:dt=datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%fZ')
	totalsecondsago = (datetime.now()-dt).total_seconds()
	yearsago = int(totalsecondsago/31536000)
	monthsago = int(totalsecondsago/2628000)
	weeksago = int(totalsecondsago/604800)
	daysago = int(totalsecondsago/86400)
	hoursago = int(totalsecondsago/3600)
	minutesago = int(totalsecondsago/60)
	secondsago = int(totalsecondsago)
	if yearsago != 0:
		return f'{yearsago} year ago' if yearsago == 1 else f'{yearsago} years ago'
	elif monthsago != 0:
		return f'{monthsago} month ago' if monthsago == 1 else f'{monthsago} months ago'
	elif weeksago != 0:
		return f'{weeksago} week ago' if weeksago == 1 else f'{weeksago} weeks ago'
	elif daysago != 0:
		return f'{daysago} day ago' if daysago == 1 else f'{daysago} days ago'
	elif hoursago != 0:
		return f'{hoursago} hour ago' if hoursago == 1 else f'{hoursago} hours ago'
	elif minutesago != 0:
		return f'{minutesago} minute ago' if minutesago == 1 else f'{minutesago} minutes ago'
	elif secondsago != 0:
		return f'{secondsago} second ago' if secondsago == 1 else f'{secondsago} seconds ago'
	else:
		return 'Just now'
def getPadding(text,columns=None):
	if columns == None:columns = cols
	try:
		return int((columns-len(text))/2)
	except TypeError as e:
		console.log(traceback.format_tb(e.__traceback__))
		return 0
def centerText(text,paddingChr=' '):
	if text == None:
		console.log('ERROR: "text" is set to None (centerText)')
		return ''
	totalspaces = getPadding(text)
	if paddingChr == ' ':
		return ' '*totalspaces+text
	else:
		return paddingChr*totalspaces+text+paddingChr*totalspaces


def getTermSize():
	cols, rows = os.get_terminal_size()
	return cols, rows

stream = sys.stdin
tty.setraw(stream,when=1)
cols, rows = getTermSize()

def render(output,end=None):
	if end == None:end=updatepos
	print(output,end=end)

chrnum = -1

updatepos = escape('s')+''+escape('u')

inesccode = False #in escape code
esccode = ''
clearscreen = escape('H')+escape('J')

class console:
	logs = []
	disabled = False
	size = rows-int(rows/1.5)
	@staticmethod #so console.log() works instead of console().log()
	def log(t,render=False):
		if not console.disabled or True: # TODO
			for l in str(t).splitlines():
				console.logs.append(l)
			if render:
				render(renderConsole(),end=updatepos)
console.log(cols)
console.log(rows)
def disableconsole():
	console.disabled = True
	console.size = 2
	#console.logs = []
	newRender()
def enableconsole():
	console.disabled = False
	rows-int(rows/1.5)
	newRender()

def queryGetPosts(boardName='All',order='hot',searchQuery=''):
	board.desc = ''
	if boardName == 'All':
		boardData = queryGetAllPosts(order=order,searchQuery=searchQuery)
	else:
		boardInfo = queryGetBoard(boardName)
		board.desc = boardInfo['description']
		if board.desc==None:board.desc=''
		boardId = int(boardInfo['id'])
		data = {'operationName':'postsByBoard','variables':{'id':boardId,'searchQuery':'','postsOrder':'hot'},'query':'query postsByBoard($id: Int!, $searchQuery: String, $postsOrder: String, $postsAfter: String) {postsByBoard(id: $id, searchQuery: $searchQuery, order: $postsOrder, after: $postsAfter) {pageInfo {nextCursor __typename} items {id ...PostListItemPost __typename} __typename}}fragment PostListItemPost on Post {id title body url commentCount isPinned isLocked isAnnouncement timeCreated ...PostVoteControlPost user {id url username karma __typename} __typename}fragment PostVoteControlPost on Post {id voteCount canVote hasVoted __typename}'}

		r = requests.post('https://repl.it/graphql',json=data, headers=headers)
		boardData = r.json()['data']['postsByBoard']
	posts = boardData['items']
	board.posts = posts
	return boardData
def queryGetBoard(boardName):
	if boardName.lower() in boardInfos:
		return boardInfos[boardName.lower()]
	else:
		data = {'operationName':'boardBySlug','variables':{'slug':boardName.lower()},'query':'query boardBySlug($slug: String!) {board: boardBySlug(slug: $slug) {id name description url cta titleCta bodyCta buttonCta replRequired canPost __typename}}'}
		r = requests.post('https://repl.it/graphql',json=data, headers=headers)
		boardData = r.json()['data']['board']
		boardInfos[boardName.lower()] = boardData
		return boardData
def queryGetAllPosts(order='hot',searchQuery='',postsAfter=0):
	data = {'operationName': 'posts', 'variables': {'order': order, 'searchQuery': searchQuery,'postsAfter':postsAfter}, 'query': 'query posts($order: String, $after: String, $searchQuery: String) {posts(order: $order, after: $after, searchQuery: $searchQuery) {pageInfo {nextCursor __typename} items {id timeCreated ...PostListItemPost board {id name url slug __typename} __typename} __typename}}fragment PostListItemPost on Post {id title body url commentCount isPinned isLocked isAnnouncement timeCreated ...PostVoteControlPost user {id url username karma __typename} __typename}fragment PostVoteControlPost on Post {id voteCount canVote hasVoted __typename}'}
	r = requests.post('https://repl.it/graphql',json=data, headers=headers)
	boardData = r.json()['data']['posts']
	return boardData



class board:
	data = {}
	scroll = 0
	selected = 'All'
	desc = ''
	posts = []
	displayingpost = False
	postData = {}
	postlength = 0

def renderConsole():
	cols, rows = getTermSize()
	output=escape('s')
	output+=escape(f'{int(rows/1.5)};H')+escape('37m')+centerText(' Debug console ','-')+'\n\r'
	console.size = rows-int(rows/1.5)-1
	for l in console.logs[-console.size+1:]:
		output+=escape('K')+l+'\n\r'
	output+=escape('u')
	return output
	
def renderBoard2():
	starttime = datetime.now()
	output = ''
	for post in board.posts:
		bold = escape('1m')
		faint = escape('2m')
		reset = escape('m')
		title = post['title']
		body = post['body']
		author = post['user']
		if author == None:
			author={'username':'[deleted]'}
		votes = post['voteCount']
		isPinned = post['isPinned']
		authorname = author['username']
		bodyshort = ' '.join(body.splitlines())[:cols-(len(str(votes))+2)].strip()
		titleshort = ('📌 ' if isPinned else '')+title
		titleshort = titleshort[:cols-(len(str(votes))+2)]
		#id, timeCreated, title, body, url, commentCount, isPinned, isLocked, isAnnouncement,voteCount, canVote, hasVoted, user, board
		extraspaces = ' '*(len(str(votes))+1)
		timeCreated = timeago(post['timeCreated'])
		#output+=title+'\n\n\r'
		
		output += f'^{extraspaces[1:]}{bold}{titleshort}{reset}\n\r{votes} {bodyshort}\n\r{extraspaces}{faint}posted by{reset} {authorname} {faint}{timeCreated}{reset}\n\n\r'
	endtime = datetime.now()
	#console.log(f'rendered board: {endtime-starttime}')
	return output
def renderPost():
	post = board.postData
	board.postlength = 0
	for l in post['body'].splitlines():
		board.postlength += int((len(l)//cols)+1)
	bold = escape('1m')
	faint = escape('2m')
	reset = escape('m')
	title = post['title']
	body = post['body']
	author = post['user']
	if author == None:
		author={'username':'[deleted]'}
	votes = post['voteCount']
	isPinned = post['isPinned']
	authorname = author['username']
	output = ''
	output += escape('J')
	output += f'^\n\r{votes}'
	output += f'\t{bold}{title}{reset}\n\r  {escape("96m")}{authorname} ({author["karma"]}){reset}'
	for l in post['body'].splitlines():
		output += '\n\r'+l
	output += '\n\n\r'
	return output
def renderBoard(paddingTop=5):
	cols, rows = getTermSize()

	if board.displayingpost:
		rawoutput = renderPost()
	else:
		rawoutput = renderBoard2()	

	outputsplit = rawoutput.split('\n')

	extraSize = 5 if console.disabled else 7

	outputsplit = outputsplit[board.scroll:int(rows-(console.size+extraSize)+board.scroll)]
	while len(outputsplit) < rows-extraSize-console.size:
		outputsplit.append('')
	console.log(f'a {len(outputsplit)}')
	console.log(f'b {rows-extraSize-console.size}')
	output = escape(f'{paddingTop};H')
	#for _ in outputsplit:
	#	output += '\n\r'+escape('2K')

	output += ('\n'+escape('2K')).join(outputsplit)
	return output
def renderHeader(comment=None):
	output = escape('H')
	output+=centerText('Repl Talk - Terminal Edition')+'\n\r'
	boardHeader = ''
	for b in boards:
		if b == board.selected:
			b =  escape('7m')+b+escape('27m')
		boardHeader += b + ' | '
	boardHeader = boardHeader[:-3]
	padding = ' '*getPadding(boardsHeaderUncentered)
	output += padding+boardHeader
	if comment == None:
		comment = board.desc
		commentpadding = getPadding(comment)
	else:
		commentpadding = getPadding(comment)
		comment = escape('37m')+comment+escape('m')
	commentpadding = ' '*commentpadding
	if commentpadding == None:
		commentpadding=''
	if comment == None:
		comment=''
	output += '\r\n'+escape('K')+commentpadding+comment
	output += '\n\n\r'
	return output
def newRender():
	cols, rows = getTermSize()
	output = clearscreen
	output += renderHeader()
	output += '\n\r'
	if not console.disabled:
		output+=renderConsole()
	output += renderBoard()
	render(output,end=updatepos)
def updateBoard(boardName):
	board.selected = boardName
	board.data = queryGetPosts(boardName)
	board.scroll = 0
	board.displayingpost = False
	render(renderHeader(),end=updatepos)
	console.log(f'Board: {boardName}')

def clickBoard(x,y):
	startpos = getPadding(boardsHeaderUncentered)+1
	endpos = cols-startpos-1
	if x >= startpos and x <= endpos:
		xtmp = x
		xtmp2 = x
		while True:
			try:
				if boardsHeader[xtmp-1] == ' ':
					break
				xtmp -= 1
			except:
				xtmp = x
				break
		while True:
			try:
				if boardsHeader[xtmp2] == ' ':
					break
				xtmp2 += 1
			except:
				break
		boardName = boardsHeader[xtmp:xtmp2].strip()
		if boardName in ['','|']:
			return
		else:
			board.selected = boardName
			render(renderHeader('Loading...'))
			updateBoard(boardName)
	else:
		pass
def clickPost(x,y):
	thepost = board.posts[int((y+board.scroll-4)/4)]
	board.postData = thepost
	board.displayingpost = True
	board.scroll = 0
	newRender()
def click(x,y):
	if y == 1:
		clickBoard(x,y)
	elif y >= 4:
		if not board.displayingpost:
			clickPost(x,y)

board.data = queryGetPosts()
print('Loading....',end='\r')
boards = ['All','Announcements','Ask','Challenge','Learn','Share']
boardsHeaderUncentered = (' | '.join(boards))
boardsHeader = centerText(boardsHeaderUncentered)
cols, rows = getTermSize()
render(clearscreen,end='')
render(escape('?1003h'),end='')
render(escape('?1006h'),end='')
render(escape('?25l'),end='')
console.log(f'Columns: {cols}')
newRender()
scrollspeed = 2
mousedown = False
outputbefore = ''
boardInfos = {}
render(renderConsole())

def parseMouseCode():
	mouseid = ''
	while True:
		text = stream.read(1)
		if text == ';':break
		mouseid += text
	x = ''
	while True:
		text = stream.read(1)
		if text == ';':break
		x += text
	y = ''
	while True:
		text = stream.read(1)
		if text in 'Mm':break
		y += text
	x, y, mouseid = int(x)-1, int(y)-1, int(mouseid)

	mousenames = {0:'Mouse down',35:'Mouse up',64:'Mouse dragged',2:'Mouse 2 down',34:'Mouse 2 dragged',64:'Scroll up',65:'Scroll down',1:'Middle mouse down',33:'Middle mouse scroll',3:'Forward button down',36:'Forward button still down',35:'Back button down'}
	if mouseid == 0:
		click(x,y)
	if mouseid in mousenames:
		downorup = 'up' if text=='m' else 'down'
		console.log(f'{mousenames[mouseid]}: {x}, {y} '+downorup)
	else:
		console.log(f'Unknown mouse {mouseid}: {x}, {y}')
	return mouseid,x,y
#	while True:
#		text = stream.read(1)
#		mousecode += text
#		console.log(f'Mouse code: {mousecode}')
def parseEscapeCode():
	esccode=''
	while True:
		text = stream.read(1)
		esccode += text
		if text in string.ascii_letters+'<':
			if esccode == '[D':#left arrow
				console.log('Left arrow pressed')

				selectedId = boards.index(board.selected)
				selectedId -= 1
				try:
					updateBoard(boards[selectedId])
				except IndexError:
					updateBoard(boards[0])
			elif esccode == '[C':#right arrow
				console.log('Right arrow pressed')

				selectedId = boards.index(board.selected)
				selectedId += 1
				try:
					updateBoard(boards[selectedId])
				except IndexError:
					updateBoard(boards[0])
			elif esccode == '[A':#up arrow
				console.log('Up arrow pressed')
				if board.scroll>0:
					board.scroll-= scrollspeed
			elif esccode == '[B':#down arrow
				console.log('Down arrow pressed')
				board.scroll += scrollspeed
			elif esccode == '[<':#mouse parse
				mouseid, x, y = parseMouseCode()
				if mouseid == 65:
					board.scroll+=scrollspeed #scroll down
					#if board.displayingpost:
					#	maxscroll = board.postlength - rows + console.size + (2 if console.disabled else 4)
					#	if board.scroll > maxscroll:
					#		console.log('oof '+str(board.postlength))
					#		board.scroll = maxscroll
				elif mouseid == 64:#scroll up
					if board.scroll>0:
						board.scroll-=scrollspeed
			elif esccode == 'O':#f-something
				text = stream.read(1)
				f=ord(text)-79
				console.log(f'F{f}')
				if f == 1:
					if console.disabled:
						enableconsole()
					else:
						disableconsole()
				elif f == 2:
					newRender()
				elif f == 3:
					print(clearscreen)
					time.sleep(1)
					newRender()
			else:
				#render(escape(esccode),end=updatepos) #other escape code
				console.log(f'Unknown escape code: {esccode}')
			esccode = ''
			break

while True:
	text = stream.read(1)
	if ord(text)==127:#backspace
		console.log('Backspace pressed')
	elif ord(text)==13:#enter
		console.log('Enter pressed')
	elif ord(text)==27:#escape
		parseEscapeCode()
	else: #normal key pressed
		if text == 'r':
			newRender()
		elif text == 'w': #up
			if board.scroll>0:
				board.scroll-= scrollspeed
		elif text == 's':#down
			board.scroll += scrollspeed
		elif text == 'd':
			selectedId = boards.index(board.selected)
			selectedId += 1
			try:
				updateBoard(boards[selectedId])
			except IndexError:
				updateBoard(boards[0])
		elif text == 'a':
			selectedId = boards.index(board.selected)
			selectedId -= 1
			try:
				updateBoard(boards[selectedId])
			except IndexError:
				updateBoard(boards[0])
		console.log(f'Key pressed: {text} ({ord(text)})')
	output = renderBoard()
	if not console.disabled:
		output += renderConsole()
	if output == outputbefore:
		pass
	else:
		outputbefore = output
		render(output,end=updatepos)