Carmeninkunming commited on
Commit
9b59c10
·
1 Parent(s): d78fb18

Delete ocr.py

Browse files
Files changed (1) hide show
  1. ocr.py +0 -675
ocr.py DELETED
@@ -1,675 +0,0 @@
1
- import os
2
- import re
3
- import time
4
- import uuid
5
- import select
6
- import psutil
7
- from sys import exit as exx
8
- from subprocess import Popen, PIPE
9
-
10
- HOME = os.path.expanduser("~")
11
- CWD = os.getcwd()
12
- tokens = {}
13
-
14
- class ngrok:
15
-
16
- def __init__(self, TOKEN=None, USE_FREE_TOKEN=True,
17
- service=[['Service1', 80, 'tcp'], ['Service2', 8080, 'tcp']],
18
- region='us',
19
- dBug=[f"{HOME}/.ngrok2/ngrok.yml", 4040]):
20
- self.region = region
21
- self.configPath, self.dport = dBug
22
- self.TOKEN = TOKEN
23
- self.USE_FREE_TOKEN = USE_FREE_TOKEN
24
- self.service = service
25
- if USE_FREE_TOKEN:
26
- self.sdict = {}
27
- for i, sn in enumerate(service):
28
- tempcP = f'{HOME}/.ngrok2/'+sn[0]+'.yml'
29
- # Port, Protocol, config path
30
- self.sdict[sn[0]] = [self.dport+i, sn[2], tempcP]
31
-
32
- def nameport(self, TOKEN, AUTO):
33
- if AUTO:
34
- try:
35
- return tokens.popitem()[1]
36
- except KeyError:
37
- return "Invalid Token"
38
- elif not TOKEN:
39
- if not 'your' in tokens.keys():
40
- from IPython import get_ipython
41
- from IPython.display import clear_output
42
- ipython = get_ipython()
43
-
44
- print(r"Copy authtoken from https://dashboard.ngrok.com/auth")
45
- __temp = ipython.magic('%sx read -p "Token :"')
46
- tokens['your'] = __temp[0].split(':')[1]
47
- USR_Api = "your"
48
- clear_output()
49
- else:
50
- USR_Api = "your"
51
- else:
52
- USR_Api = "mind"
53
- tokens["mind"] = TOKEN
54
- return tokens[USR_Api]
55
-
56
-
57
- def ngrok_config(self, token, Gport, configPath, region, service):
58
- import os
59
- data = """
60
- region: {}
61
- update: false
62
- update_channel: stable
63
- web_addr: localhost:{}
64
- tunnels:\n""".format(region, Gport)
65
- if not self.USE_FREE_TOKEN:
66
- auth ="""
67
- authtoken: {}""".format(token)
68
- data = auth+data
69
- tunnels = ""
70
- for S in service:
71
- Sn, Sp, SpC = S
72
- tunnels += """ {}:
73
- addr: {}
74
- proto: {}
75
- inspect: false\n""".format(Sn, Sp, SpC)
76
- data = data + tunnels
77
- os.makedirs(f'{HOME}/.ngrok2/', exist_ok=True)
78
- with open(configPath, "w+") as configFile:
79
- configFile.write(data)
80
- return True
81
-
82
-
83
- def startWebUi(self, token, dport, nServer, region, btc, configPath,
84
- displayB, service, v):
85
- import os, time, urllib
86
- from IPython.display import clear_output
87
- from json import loads
88
-
89
- if token == "Invalid Token":
90
- print(tokens)
91
- os.exit()
92
-
93
- installNgrok()
94
- if v:
95
- clear_output()
96
- loadingAn(name="lds")
97
- textAn("Starting ngrok ...", ty='twg')
98
- if self.USE_FREE_TOKEN:
99
- for sn in service:
100
- self.ngrok_config(
101
- token,
102
- self.sdict[nServer][0],
103
- self.sdict[nServer][2],
104
- region,
105
- service)
106
- if sn[0] == nServer:
107
- runSh(f"ngrok {sn[2]} -config={self.sdict[nServer][2]} {sn[1]} &", shell=True)
108
- else:
109
- self.ngrok_config(token, dport, configPath, region, service)
110
- runSh(f"ngrok start --config {configPath} --all &", shell=True)
111
- time.sleep(3)
112
- try:
113
- if self.USE_FREE_TOKEN:
114
- dport = self.sdict[nServer][0]
115
- nServer = 'command_line'
116
- host = urllib.request.urlopen(f"http://localhost:{dport}/api/tunnels")
117
- else:
118
- host = urllib.request.urlopen(f"http://localhost:{dport}/api/tunnels")
119
- host = loads(host.read())['tunnels']
120
- for h in host:
121
- if h['name'] == nServer:
122
- host = h['public_url'][8:]
123
- break
124
- except urllib.error.URLError:
125
- if v:
126
- clear_output()
127
- loadingAn(name="lds")
128
- textAn("Ngrok Token is in used!. Again trying token ...", ty='twg')
129
- time.sleep(2)
130
- return True
131
-
132
- data = {"url": f"https://{host}"}
133
- if displayB:
134
- displayUrl(data, btc)
135
- return data
136
-
137
-
138
- def start(self, nServer, btc='b', displayB=True, v=True):
139
- import urllib
140
- from IPython.display import clear_output
141
- from json import loads
142
-
143
- try:
144
- nServerbk = nServer
145
- if self.USE_FREE_TOKEN:
146
- dport = self.sdict[nServer][0]
147
- nServer = 'command_line'
148
- else:
149
- dport = self.dport
150
- host = urllib.request.urlopen(f"http://localhost:{dport}/api/tunnels")
151
- host = loads(host.read())['tunnels']
152
- for h in host:
153
- if h['name'] == nServer:
154
- host = h['public_url'][8:]
155
- data = {"url": f"https://{host}"}
156
- if displayB:
157
- displayUrl(data, btc)
158
- return data
159
-
160
- raise Exception('Not found tunnels')
161
- except urllib.error.URLError:
162
- for run in range(10):
163
- if v:
164
- clear_output()
165
- loadingAn(name='lds')
166
- dati = self.startWebUi(
167
- self.nameport(self.TOKEN, self.USE_FREE_TOKEN) if not self.USE_FREE_TOKEN else {},
168
- self.dport,
169
- nServerbk,
170
- self.region,
171
- btc,
172
- self.configPath,
173
- displayB,
174
- self.service,
175
- v
176
- )
177
- if dati == True:
178
- continue
179
- return dati
180
-
181
- def checkAvailable(path_="", userPath=False):
182
- from os import path as _p
183
-
184
- if path_ == "":
185
- return False
186
- else:
187
- return (
188
- _p.exists(path_)
189
- if not userPath
190
- else _p.exists(f"/usr/local/sessionSettings/{path_}")
191
- )
192
-
193
- def accessSettingFile(file="", setting={}, v=True):
194
- from json import load, dump
195
-
196
- if not isinstance(setting, dict):
197
- if v:print("Only accept Dictionary object.")
198
- exx()
199
- fullPath = f"/usr/local/sessionSettings/{file}"
200
- try:
201
- if not len(setting):
202
- if not checkAvailable(fullPath):
203
- if v:print(f"File unavailable: {fullPath}.")
204
- exx()
205
- with open(fullPath) as jsonObj:
206
- return load(jsonObj)
207
- else:
208
- with open(fullPath, "w+") as outfile:
209
- dump(setting, outfile)
210
- except:
211
- if v:print(f"Error accessing the file: {fullPath}.")
212
-
213
-
214
- def displayUrl(data, btc='b', pNamU='Public URL: ', EcUrl=None, ExUrl=None, cls=True):
215
- from IPython.display import HTML, clear_output
216
-
217
- if cls:
218
- clear_output()
219
- showTxT = f'{pNamU}{data["url"]}'
220
- if EcUrl:
221
- showUrL = data["url"]+EcUrl
222
- elif ExUrl:
223
- showUrL = ExUrl
224
- else:
225
- showUrL = data["url"]
226
- if btc == 'b':
227
- # blue
228
- bttxt = 'hsla(210, 50%, 85%, 1)'
229
- btcolor = 'hsl(210, 80%, 42%)'
230
- btshado = 'hsla(210, 40%, 52%, .4)'
231
- elif btc == 'g':
232
- # green
233
- bttxt = 'hsla(110, 50%, 85%, 1)'
234
- btcolor = 'hsla(110, 86%, 56%, 1)'
235
- btshado = 'hsla(110, 40%, 52%, .4)'
236
- elif btc == 'r':
237
- # red
238
- bttxt = 'hsla(10, 50%, 85%, 1)'
239
- btcolor = 'hsla(10, 86%, 56%, 1)'
240
- btshado = 'hsla(10, 40%, 52%, .4)'
241
-
242
- return display(HTML('''<style>@import url('https://fonts.googleapis.com/css?family=Source+Code+Pro:200,900'); :root { --text-color: '''+bttxt+'''; --shadow-color: '''+btshado+'''; --btn-color: '''+btcolor+'''; --bg-color: #141218; } * { box-sizing: border-box; } button { position:relative; padding: 10px 20px; border: none; background: none; cursor: pointer; font-family: "Source Code Pro"; font-weight: 900; font-size: 100%; color: var(--text-color); background-color: var(--btn-color); box-shadow: var(--shadow-color) 2px 2px 22px; border-radius: 4px; z-index: 0; overflow: hidden; } button:focus { outline-color: transparent; box-shadow: var(--btn-color) 2px 2px 22px; } .right::after, button::after { content: var(--content); display: block; position: absolute; white-space: nowrap; padding: 40px 40px; pointer-events:none; } button::after{ font-weight: 200; top: -30px; left: -20px; } .right, .left { position: absolute; width: 100%; height: 100%; top: 0; } .right { left: 66%; } .left { right: 66%; } .right::after { top: -30px; left: calc(-66% - 20px); background-color: var(--bg-color); color:transparent; transition: transform .4s ease-out; transform: translate(0, -90%) rotate(0deg) } button:hover .right::after { transform: translate(0, -47%) rotate(0deg) } button .right:hover::after { transform: translate(0, -50%) rotate(-7deg) } button .left:hover ~ .right::after { transform: translate(0, -50%) rotate(7deg) } /* bubbles */ button::before { content: ''; pointer-events: none; opacity: .6; background: radial-gradient(circle at 20% 35%, transparent 0, transparent 2px, var(--text-color) 3px, var(--text-color) 4px, transparent 4px), radial-gradient(circle at 75% 44%, transparent 0, transparent 2px, var(--text-color) 3px, var(--text-color) 4px, transparent 4px), radial-gradient(circle at 46% 52%, transparent 0, transparent 4px, var(--text-color) 5px, var(--text-color) 6px, transparent 6px); width: 100%; height: 300%; top: 0; left: 0; position: absolute; animation: bubbles 5s linear infinite both; } @keyframes bubbles { from { transform: translate(); } to { transform: translate(0, -66.666%); } } Resources</style><center><a href="'''+showUrL+'''" target="_blank"><div style="width: 700px; height: 80px; padding-top:15px"><button style='--content: "'''+showTxT+'''";'"> <div class="left"></div>'''+showTxT+'''<div class="right"></div> </div></button></a></center>'''))
243
-
244
-
245
- def findProcess(process, command="", isPid=False):
246
- from psutil import pids, Process
247
-
248
- if isinstance(process, int):
249
- if process in pids():
250
- return True
251
- else:
252
- for pid in pids():
253
- try:
254
- p = Process(pid)
255
- if process in p.name():
256
- for arg in p.cmdline():
257
- if command in str(arg):
258
- return True if not isPid else str(pid)
259
- else:
260
- pass
261
- else:
262
- pass
263
- except:
264
- continue
265
-
266
- def installArgoTunnel():
267
- if checkAvailable(f"{HOME}/tools/argotunnel/cloudflared"):
268
- return
269
- else:
270
- import os
271
- from shutil import unpack_archive
272
- from urllib.request import urlretrieve
273
-
274
- os.makedirs(f'{HOME}/tools/argotunnel/', exist_ok=True)
275
- aTURL = findPackageR("cloudflare/cloudflared", "cloudflared-linux-amd64")
276
- urlretrieve(aTURL, f'{HOME}/tools/argotunnel/cloudflared')
277
- # unpack_archive('cloudflared.tgz',
278
- # f'{HOME}/tools/argotunnel')
279
- os.chmod(f'{HOME}/tools/argotunnel/cloudflared', 0o755)
280
- # os.unlink('cloudflared.tgz')
281
-
282
- def installNgrok():
283
- if checkAvailable("/usr/local/bin/ngrok"):
284
- return
285
- else:
286
- import os
287
- from zipfile import ZipFile
288
- from urllib.request import urlretrieve
289
-
290
- ngURL = "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip"
291
- urlretrieve(ngURL, 'ngrok-amd64.zip')
292
- with ZipFile('ngrok-amd64.zip', 'r') as zip_ref:
293
- zip_ref.extractall('/usr/local/bin/')
294
- os.chmod('/usr/local/bin/ngrok', 0o755)
295
- os.unlink('ngrok-amd64.zip')
296
-
297
- def installAutoSSH():
298
- if checkAvailable("/usr/bin/autossh"):
299
- return
300
- else:
301
- runSh("apt-get install autossh -qq -y")
302
-
303
-
304
-
305
- def runSh(args, *, output=False, shell=False, cd=None):
306
- import subprocess, shlex
307
-
308
- if not shell:
309
- if output:
310
- proc = subprocess.Popen(
311
- shlex.split(args), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cd
312
- )
313
- while True:
314
- output = proc.stdout.readline()
315
- if output == b"" and proc.poll() is not None:
316
- return
317
- if output:
318
- print(output.decode("utf-8").strip())
319
- return subprocess.run(shlex.split(args), cwd=cd).returncode
320
- else:
321
- if output:
322
- return (
323
- subprocess.run(
324
- args,
325
- shell=True,
326
- stdout=subprocess.PIPE,
327
- stderr=subprocess.STDOUT,
328
- cwd=cd,
329
- )
330
- .stdout.decode("utf-8")
331
- .strip()
332
- )
333
- return subprocess.run(args, shell=True, cwd=cd).returncode
334
-
335
- def loadingAn(name="cal"):
336
- from IPython.display import HTML
337
-
338
- if name == "cal":
339
- return display(HTML('<style>.lds-ring { display: inline-block; position: relative; width: 34px; height: 34px; } .lds-ring div { box-sizing: border-box; display: block; position: absolute; width: 34px; height: 34px; margin: 4px; border: 5px solid #cef; border-radius: 50%; animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; border-color: #cef transparent transparent transparent; } .lds-ring div:nth-child(1) { animation-delay: -0.45s; } .lds-ring div:nth-child(2) { animation-delay: -0.3s; } .lds-ring div:nth-child(3) { animation-delay: -0.15s; } @keyframes lds-ring { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style><div class="lds-ring"><div></div><div></div><div></div><div></div></div>'))
340
- elif name == "lds":
341
- return display(HTML('''<style>.lds-hourglass { display: inline-block; position: relative; width: 34px; height: 34px;}.lds-hourglass:after { content: " "; display: block; border-radius: 50%; width: 34px; height: 34px; margin: 0px; box-sizing: border-box; border: 20px solid #dfc; border-color: #dfc transparent #dfc transparent; animation: lds-hourglass 1.2s infinite;}@keyframes lds-hourglass { 0% { transform: rotate(0); animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); } 50% { transform: rotate(900deg); animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); } 100% { transform: rotate(1800deg); }}</style><div class="lds-hourglass"></div>'''))
342
-
343
- def textAn(TEXT, ty='d'):
344
- from IPython.display import HTML
345
-
346
- if ty == 'd':
347
- return display(HTML('''<style>@import url(https://fonts.googleapis.com/css?family=Raleway:400,700,900,400italic,700italic,900italic);#wrapper { font: 17px 'Raleway', sans-serif;animation: text-shadow 1.5s ease-in-out infinite; margin-left: auto; margin-right: auto; }#container { display: flex; flex-direction: column; float: left; }@keyframes text-shadow { 0% 20% { transform: translateY(-0.1em); text-shadow: 0 0.1em 0 #0c2ffb, 0 0.1em 0 #2cfcfd, 0 -0.1em 0 #fb203b, 0 -0.1em 0 #fefc4b; } 40% { transform: translateY(0.1em); text-shadow: 0 -0.1em 0 #0c2ffb, 0 -0.1em 0 #2cfcfd, 0 0.1em 0 #fb203b, 0 0.1em 0 #fefc4b; } 60% { transform: translateY(-0.1em); text-shadow: 0 0.1em 0 #0c2ffb, 0 0.1em 0 #2cfcfd, 0 -0.1em 0 #fb203b, 0 -0.1em 0 #fefc4b; } }@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; }}</style><div id="wrapper"><div id="container">'''+TEXT+'''</div></div>'''))
348
- elif ty == 'twg':
349
- textcover = str(len(TEXT)*0.55)
350
- return display(HTML('''<style>@import url(https://fonts.googleapis.com/css?family=Anonymous+Pro);.line-1{font-family: 'Anonymous Pro', monospace; position: relative; border-right: 1px solid; font-size: 15px; white-space: nowrap; overflow: hidden; }.anim-typewriter{ animation: typewriter 0.4s steps(44) 0.2s 1 normal both, blinkTextCursor 600ms steps(44) infinite normal;}@keyframes typewriter{ from{width: 0;} to{width: '''+textcover+'''em;}}@keyframes blinkTextCursor{ from{border-right:2px;} to{border-right-color: transparent;}}</style><div class="line-1 anim-typewriter">'''+TEXT+'''</div>'''))
351
-
352
- class LocalhostRun:
353
- RE_PATTERN = r"n,\s(?:https?://)?((?:[-\w]+\.)+[\w]{2,}(?:/[-\w./?%&=]*)?)"
354
-
355
- def __init__(self,port,id=None,interval=30,retries=30):
356
- import os
357
- filePath = "/usr/local/sessionSettings/localhostDB.json"
358
- if not os.path.exists(filePath):
359
- os.makedirs(filePath[:-16], exist_ok=True)
360
- open(filePath, 'w').close()
361
- installAutoSSH()
362
- if not id:id=str(uuid.uuid4())[:8]
363
- self.connection=None
364
- self.id=id
365
- self.port=port
366
- self.interval=interval
367
- self.retries=retries
368
-
369
- def start(self):
370
- if self.connection:self.connection.kill()
371
- self.connection=Popen(f"ssh -R 80:localhost:{self.port} {self.id}@ssh.localhost.run -o StrictHostKeyChecking=no".split(), stdout=PIPE, stdin=PIPE)
372
- try:
373
- outputString = read_subprocess_output(self.connection, timeout=5)
374
- return re.findall(self.RE_PATTERN, outputString)[0]
375
- except:
376
- raise Exception(self.connection.stdout.readline().decode("utf-8"))
377
-
378
- def keep_alive(self):
379
- # if self.connection:self.connection.kill()
380
- import urllib
381
- try:
382
- localhostOpenDB = dict(accessSettingFile("localhostDB.json", v=False))
383
- except TypeError:
384
- localhostOpenDB = dict()
385
-
386
- if findProcess("autossh", f"80:localhost:{self.port}"):
387
- try:
388
- oldAddr = localhostOpenDB[str(self.port)]
389
- urllib.request.urlopen("http://"+oldAddr)
390
- return oldAddr
391
- except:
392
- pass
393
- for _ in range(2):
394
- self.connection=Popen(f"autossh -R 80:localhost:{self.port} {self.id}@ssh.localhost.run -o StrictHostKeyChecking=no -o ServerAliveInterval={self.interval} -o ServerAliveCountMax={self.retries}".split(),
395
- stdout=PIPE, stdin=PIPE, stderr=PIPE)
396
- #print("ssh -R 80:localhost:{self.port} {self.id}@ssh.localhost.run -o StrictHostKeyChecking=no -o ServerAliveInterval={self.interval} -o ServerAliveCountMax={self.retries}")
397
- try:
398
- outputString = read_subprocess_output(self.connection, timeout=5)
399
- newAddr = re.findall(self.RE_PATTERN, outputString)[0]
400
- localhostOpenDB[str(self.port)] = newAddr
401
- accessSettingFile("localhostDB.json" , localhostOpenDB, v=False)
402
- return newAddr
403
- except:
404
- outs, errs = self.connection.communicate(timeout=15)
405
- self.connection.kill()
406
- # print(outs)
407
- # print(errs)
408
- if re.search(r"Permission\sdenied\s\(publickey\)", errs.decode("utf-8")):
409
- os.system("ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa")
410
- continue
411
- raise Exception(errs.decode("utf-8"))
412
- break
413
-
414
- def kill(self):
415
- self.connection.kill()
416
-
417
- class ArgoTunnel:
418
- def __init__(self, port, proto='http', metrics=49589, interval=30, retries=30):
419
- import os
420
- filePath = "/usr/local/sessionSettings/argotunnelDB.json"
421
- if not os.path.exists(filePath):
422
- os.makedirs(filePath[:-17], exist_ok=True)
423
- open(filePath, 'w').close()
424
-
425
- #Installing argotunnel
426
- installArgoTunnel()
427
-
428
- self.connection=None
429
- self.proto=proto
430
- self.port=port
431
- self.metricPort=metrics
432
- self.interval=interval
433
- self.retries=retries
434
-
435
- # def start(self):
436
- # if self.connection:self.connection.kill()
437
- # # self.connection=Popen(f"ssh -R 80:localhost:{self.port} {self.id}@ssh.localhost.run -o StrictHostKeyChecking=no".split(), stdout=PIPE, stdin=PIPE)
438
- # self.connection=Popen(f"/content/tools/argotunnel/cloudflared tunnel --url {self.proto}://0.0.0.0:{self.port} --logfile cloudflared.log".split(), stdout=PIPE, stdin=PIPE)
439
- # try:
440
- # return re.findall("https://(.*?.trycloudflare.com)",self.connection.stdout.readline().decode("utf-8"))[0]
441
- # except:
442
- # raise Exception(self.connection.stdout.readline().decode("utf-8"))
443
-
444
- def keep_alive(self):
445
- # if self.connection:self.connection.kill()
446
- import urllib, requests, re
447
- from urllib.error import HTTPError
448
-
449
- try:
450
- argotunnelOpenDB = dict(accessSettingFile("argotunnelDB.json", v=False))
451
- except TypeError:
452
- argotunnelOpenDB = dict()
453
-
454
- if findProcess("cloudflared", f"localhost:{self.metricPort}"):
455
- try:
456
- oldAddr = argotunnelOpenDB[str(self.port)]
457
- if requests.get("http://"+oldAddr).status_code == 200:
458
- return oldAddr
459
- except:
460
- pass
461
-
462
- self.connection=Popen(f"{HOME}/tools/argotunnel/cloudflared tunnel --url {self.proto}://0.0.0.0:{self.port} --logfile {HOME}/tools/argotunnel/cloudflared_{self.port}.log --metrics localhost:{self.metricPort}".split(),
463
- stdout=PIPE, stdin=PIPE, stderr=PIPE, universal_newlines=True)
464
-
465
- time.sleep(5)
466
-
467
- hostname = None
468
- for i in range(20):
469
- try:
470
- with urllib.request.urlopen(f"http://127.0.0.1:{self.metricPort}/metrics") as response:
471
- hostname = re.search(r'userHostname=\"https://(.+)\"',
472
- response.read().decode('utf-8'), re.MULTILINE)
473
- if not hostname:
474
- time.sleep(1)
475
- continue
476
- hostname = hostname.group(1)
477
- break
478
- except HTTPError:
479
- time.sleep(2)
480
-
481
- if not hostname:
482
- raise RuntimeError("Failed to get user hostname from cloudflared")
483
-
484
- argotunnelOpenDB[str(self.port)] = hostname
485
- accessSettingFile("argotunnelDB.json" , argotunnelOpenDB, v=False)
486
- return hostname
487
-
488
- def kill(self):
489
- self.connection.kill()
490
-
491
- class jprq:
492
- def __init__(self, port, proto='http', ids=None):
493
- import os, uuid
494
- filePath = "/usr/local/sessionSettings/jprqDB.json"
495
- if not os.path.exists(filePath):
496
- os.makedirs(filePath[:-11], exist_ok=True)
497
- open(filePath, 'w').close()
498
-
499
- if not ids:self.ids=str(uuid.uuid4())[:12]
500
- #Installing jprq
501
- runSh("apt update")
502
- # pass
503
-
504
- self.connection=None
505
- self.proto=proto
506
- self.port=port
507
-
508
- def keep_alive(self):
509
- # if self.connection:self.connection.kill()
510
- import urllib, requests, re
511
- try:
512
- jprqOpenDB = dict(accessSettingFile("jprqDB.json", v=False))
513
- except TypeError:
514
- jprqOpenDB = dict()
515
-
516
- if findProcess("jprq", f"{self.port}"):
517
- try:
518
- oldAddr = jprqOpenDB[str(self.port)]
519
- if requests.get("http://"+oldAddr).status_code == 200:
520
- return oldAddr
521
- except:
522
- pass
523
- hostname = f"OneClickRun-{self.ids}"
524
- self.connection=Popen(f"jprq -s {hostname} {self.port}".split(),
525
- stdout=PIPE, stdin=PIPE, stderr=PIPE)
526
-
527
- time.sleep(3)
528
-
529
- # try:
530
- # return re.findall("https://(.*?.jprq.live/)", self.connection.stdout.readline().decode("utf-8"))[0]
531
- # except:
532
- # raise Exception(self.connection.stdout.readline().decode("utf-8"))
533
- hostname += ".jprq.live"
534
- jprqOpenDB[str(self.port)] = hostname
535
- accessSettingFile("jprqDB.json" , jprqOpenDB, v=False)
536
- return hostname
537
-
538
- def kill(self):
539
- self.connection.kill()
540
-
541
- class PortForward:
542
- def __init__(self,connections,region=None,SERVICE="localhost",TOKEN=None,USE_FREE_TOKEN=None,config=None):
543
- c=dict()
544
- for con in connections:
545
- c[con[0]]=dict(port=con[1],proto=con[2])
546
- self.connections=c
547
- if config:config[1] = closePort(config[1])
548
- self.config = config
549
- if SERVICE=="ngrok":self.ngrok=ngrok(TOKEN,USE_FREE_TOKEN,connections,region,self.config)
550
- self.SERVICE = SERVICE
551
-
552
-
553
- def start(self,name,btc='b',displayB=True,v=True):
554
- from IPython.display import clear_output
555
-
556
- if self.SERVICE == "localhost":
557
- con=self.connections[name]
558
- port=con["port"]
559
- proto=con["proto"]
560
- if(proto=="tcp"):
561
- return self.ngrok.start(name,btc,displayB,v)
562
- else:
563
- if v:
564
- clear_output()
565
- loadingAn(name="lds")
566
- textAn("Starting localhost ...", ty="twg")
567
- data = dict(url="https://"+LocalhostRun(port).keep_alive())
568
- if displayB:
569
- displayUrl(data, btc)
570
- return data
571
- elif self.SERVICE == "ngrok":
572
- return self.ngrok.start(name,btc,displayB,v)
573
- elif self.SERVICE == "argotunnel":
574
- con=self.connections[name]
575
- port=con["port"]
576
- proto=con["proto"]
577
- if v:
578
- clear_output()
579
- loadingAn(name="lds")
580
- textAn("Starting Argo Tunnel ...", ty="twg")
581
- data = dict(url="https://"+ArgoTunnel(port, proto, closePort(self.config[1])).keep_alive())
582
- if displayB:
583
- displayUrl(data, btc)
584
- return data
585
- elif self.SERVICE == "jprq":
586
- con=self.connections[name]
587
- port=con["port"]
588
- proto=con["proto"]
589
- if v:
590
- clear_output()
591
- loadingAn(name="lds")
592
- textAn("Starting jprq ...", ty="twg")
593
- data = dict(url="https://"+jprq(port, proto).keep_alive())
594
- if displayB:
595
- displayUrl(data, btc)
596
- return data
597
-
598
-
599
-
600
- class PortForward_wrapper(PortForward):
601
- def __init__(self,SERVICE,TOKEN,USE_FREE_TOKEN,connections,region,config):
602
- super(self.__class__,self).__init__(connections,region,SERVICE,TOKEN,USE_FREE_TOKEN,config)
603
-
604
-
605
- def findPackageR(id_repo, p_name, tag_name=False, all_=False):
606
- import requests
607
-
608
- for rawData in requests.get(f"https://api.github.com/repos/{id_repo}/releases").json():
609
- if tag_name:
610
- if rawData['tag_name'] != tag_name:
611
- continue
612
-
613
- for f in rawData['assets']:
614
- if p_name == f['browser_download_url'][-len(p_name):]:
615
- rawData['assets'] = f
616
- return f['browser_download_url'] if not all_ else rawData
617
- raise Exception("not found or maybe api changed!\n Try again with Change packages name")
618
-
619
- def closePort(port):
620
- import socket
621
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
622
- for _ in range(100):
623
- if s.connect_ex(('localhost', port)) == 0:
624
- port += 1
625
- else:
626
- return port
627
- raise Exception("Close port not found!")
628
-
629
- def read_subprocess_output(process, timeout=5):
630
- output = ""
631
- # set the process to non-blocking mode
632
- process.stdout.fileno()
633
- # create a poll object to wait for data
634
- poll_obj = select.poll()
635
- poll_obj.register(process.stdout, select.POLLIN)
636
- # read the data with a timeout
637
- start_time = time.monotonic()
638
- while True:
639
- # calculate the remaining timeout
640
- elapsed_time = time.monotonic() - start_time
641
- remaining_time = timeout - elapsed_time
642
- # break if the timeout has expired
643
- if remaining_time <= 0:
644
- process.kill()
645
- output += f"\nProcess killed after {timeout} seconds due to timeout."
646
- break
647
- # wait for data with a timeout
648
- poll_result = poll_obj.poll(remaining_time * 1000)
649
- if poll_result:
650
- # read the available data
651
- output += process.stdout.readline().decode().strip() + "\n"
652
- # break if the subprocess has exited
653
- if process.poll() is not None:
654
- output += process.stdout.read().decode().strip()
655
- break
656
- return output
657
-
658
- def run_process(command, shell=False, cwd=None, env=None, notSilent=True):
659
- for proc in psutil.process_iter():
660
- try:
661
- # Get process info as a named tuple containing the process name and command-line arguments
662
- process_info = proc.as_dict(attrs=['pid', 'name', 'cmdline'])
663
- process_cmdline = process_info['cmdline']
664
-
665
- # Check if the command matches the process command-line arguments
666
- if process_cmdline == command.split():
667
- if notSilent:
668
- print("Killing process with PID", process_info['pid'])
669
- proc.kill()
670
- except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
671
- pass
672
- if notSilent:
673
- print("Starting process with command", command)
674
- Popen(command, shell=shell, cwd=cwd, env=env)
675
-