Update notifier, VIP only access

This commit is contained in:
Egor Guslyancev 2024-04-30 12:08:00 -03:00
parent 7adda1fffb
commit d4725ce5cf
GPG Key ID: D7E709AA465A55F9
2 changed files with 66 additions and 14 deletions

View File

@ -14,6 +14,11 @@ from markdown import markdown
import db_classes
import timeout as tmo
# Simple config
GET_ONLY_FOR_VIP = True
POST_ONLY_FOR_VIP = True
VERSION = "20240430.1"
CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
db = db_classes.PickleDB(".db")
@ -32,6 +37,10 @@ def resolve_logs(tries = 3, backup = True, backup_name = None):
db.pop("pending")
except KeyError:
pass
try:
db.pop("contributors")
except KeyError:
pass
print("Resolved")
return
pending = db.read("pending", [])
@ -85,12 +94,14 @@ def resolve_logs(tries = 3, backup = True, backup_name = None):
case "[":
pass
case "{":
if len(incorrect[a[0]]) == (2**a[3] - 2): # Exclude empty and unknown
if len(incorrect[a[0]]) == (2**a[3] - 2): # [- 2]: Exclude empty and unknown
for c in comb(CHARSET[:a[3]]):
if c not in incorrect[a[0]]:
correct[a[0]] = c
break
incorrect.pop(a[0])
if len(incorrect[a[0]]) > (2**a[3] - 2):
incorrect[a[0]] = []
case _:
if len(incorrect[a[0]]) == (a[3] - 1):
for c in CHARSET[:a[3]]:
@ -130,6 +141,8 @@ def parse_request(r):
user_id = results['uid']
blacklist = db.read('users.blacklist', set())
vip = db.read('users.vip', set())
if user_id not in vip and POST_ONLY_FOR_VIP:
return 403
if user_id in blacklist:
return 403
match rtype:
@ -190,7 +203,16 @@ class S(BaseHTTPRequestHandler):
self.send_response(status)
def do_GET(self):
match self.path:
sp = self.path.split('?')
parameters = {}
if len(sp) < 2:
self_path = sp[0]
else:
self_path, params = sp[:2]
for p in params.split('&'):
p = p.split('=')
parameters[p[0]] = p[1]
match self_path:
case "/":
self._set_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
@ -215,11 +237,11 @@ class S(BaseHTTPRequestHandler):
'https://git.disroot.org/electromagneticcyclone/sorryops'
)
self.end_headers()
case _ if self.path.startswith("/TOS."):
case _ if self_path.startswith("/TOS."):
self._set_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
path = self.path[1:] + ("" if self.path.endswith(".md") else ".md")
path = self_path[1:] + ("" if self_path.endswith(".md") else ".md")
if path in listdir("./"):
with open(path, "r", encoding='utf-8') as fi:
self.wfile.write(
@ -230,9 +252,9 @@ class S(BaseHTTPRequestHandler):
self._set_response(404)
self.end_headers()
self.wfile.write("404 Not found".encode('utf-8'))
case _ if self.path.startswith("/assets/"):
case _ if self_path.startswith("/assets/"):
self._set_response(200)
with open(self.path[1:], "rb") as fi:
with open(self_path[1:], "rb") as fi:
data = fi.read()
self.send_header('Accept-Ranges', 'bytes')
self.send_header('Content-Disposition', 'attachment')
@ -240,18 +262,26 @@ class S(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(data)
case _:
db_path = 'tests.' + '.'.join(self.path[1:].split('/'))
db_path = 'tests.' + '.'.join(self_path[1:].split('/'))
data = db.read(db_path, None)
if data is None:
user = ""
if 'uid' in parameters:
user = parameters['uid']
if user not in db.read('users.vip') and GET_ONLY_FOR_VIP:
self._set_response(403)
self.end_headers()
self.wfile.write("403 Forbidden".encode('utf-8'))
elif data is None:
self._set_response(404)
self.end_headers()
self.wfile.write("404 Not found".encode('utf-8'))
else:
send_data = dict()
send_data = {}
if 'correct' in data:
send_data['correct'] = data['correct']
if 'incorrect' in data:
send_data['incorrect'] = data['incorrect']
send_data['version'] = VERSION
self._set_response(200)
self.send_header('Content-type', 'text/json; charset=utf-8')
self.end_headers()
@ -261,17 +291,27 @@ class S(BaseHTTPRequestHandler):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
self._set_response(parse_request(post_data))
self.wfile.write(f"POST request for {self.path}".encode('utf-8'))
# self.wfile.write(f"POST request for {self.path}".encode('utf-8'))
def run_resolver():
p2_tmo = tmo.Timeout(2 * 60)
while True:
p2_tmo.check(resolve_logs, lambda: None)
try:
p2_tmo.check(resolve_logs, lambda: None)
except:
pass
def run_http_server(httpd):
while True:
try:
httpd.serve_forever()
except:
pass
def run(server_class=HTTPServer, handler_class=S, port=8000):
server_address = ('127.0.0.1', port)
httpd = server_class(server_address, handler_class)
funcs = [httpd.serve_forever, run_resolver]
funcs = [lambda: run_http_server(httpd), run_resolver]
threads = map(lambda x: Thread(target=x), funcs)
for thread in threads:
thread.daemon = True

16
user.js
View File

@ -2,7 +2,7 @@
// @name Sorryops
// @name:ru Сориупс
// @namespace https://git.disroot.org/electromagneticcyclone/sorryops
// @version 20240429.3
// @version 20240430.1
// @description Collect and reuse ORIOKS test answers
// @description:ru Скрипт для сбора и переиспользования ответов на тесты ОРИОКС
// @icon https://orioks.miet.ru/favicon.ico
@ -16,6 +16,7 @@
// @grant GM_registerMenuCommand
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @require https://openuserjs.org/src/libs/sizzle/GM_config.js
// @connect sorryops.ru
// @run-at document-start
@ -23,6 +24,10 @@
// @updateURL https://update.greasyfork.org/scripts/481036/Sorryops.meta.js
// ==/UserScript==
/* Version */
const VERSION = "20240430.1";
/* End Version */
/* Charset */
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/* End Charset */
@ -275,7 +280,7 @@ function fetch_from_server(path, func) {
if (server != '') {
GM_xmlhttpRequest({
method: 'GET',
url: 'https://' + server + '/' + path,
url: 'https://' + server + '/' + path + '?uid=' + config.get('user_id'),
onload: function (response) {
var text = response.responseText;
if (!text.includes("{")) {
@ -534,6 +539,13 @@ function update_variant() {
function test_form_handler(server_data) {
var i, key, answer, sorry_val;
var version = server_data.version;
if (version !== VERSION && version !== undefined) {
console.warn("Sorryops is outdated");
server_data = {};
GM_openInTab("https://greasyfork.org/en/scripts/481036-sorryops");
config.set('auto_continue', false);
}
var boxes = [];
var sorted_objects;
var objects_hash = new Object();