mirror of
https://github.com/th3r00t/pyShelf.git
synced 2026-04-28 01:59:35 -04:00
Began implementing on-demand websocket server
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from loguru import logger
|
||||
|
||||
@@ -14,10 +15,10 @@ class Config:
|
||||
"""
|
||||
Initialize main configuration options
|
||||
"""
|
||||
self.root = root
|
||||
self._fp = "config.json"
|
||||
self._cp = pathlib.Path.joinpath(root, self._fp)
|
||||
self._data = self.open_file()
|
||||
self.root = root
|
||||
self.logger = self.get_logger()
|
||||
self.book_path = self._data["BOOKPATH"]
|
||||
self.TITLE = self._data["TITLE"]
|
||||
@@ -53,5 +54,10 @@ class Config:
|
||||
data = json.load(read_file)
|
||||
return data
|
||||
|
||||
def path(self):
|
||||
rstr = "pyShelf/src"
|
||||
r = re.template(rstr)
|
||||
_pathre = re.match("pyShelf/src")
|
||||
|
||||
def django_secret(self):
|
||||
pass
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import websockets
|
||||
|
||||
from .config import Config
|
||||
from .library import Catalogue
|
||||
from .storage import Storage
|
||||
|
||||
|
||||
class InitFiles:
|
||||
"""First run file creation operations"""
|
||||
|
||||
def __init__(self, file_array):
|
||||
for _pointer in file_array:
|
||||
time.sleep(1)
|
||||
@@ -35,18 +36,40 @@ class Server:
|
||||
:TODO: Document this
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.loop = asyncio.get_event_loop()
|
||||
async def __init__(self, root):
|
||||
self.root = root
|
||||
self.config = Config(self.root)
|
||||
self.instance = None
|
||||
self.serve = await websockets.serve(socketio, "127.0.0.1", 1337)
|
||||
|
||||
async def entrypoint(self, websocket, path):
|
||||
_str = await websocket.recv()
|
||||
greeting = f"{_str}"
|
||||
await websocket.send(greeting)
|
||||
async def __aexit__(self, *args, **kwargs):
|
||||
await self.serve.__aexit__(*args, **kwargs)
|
||||
|
||||
async def start(self):
|
||||
try:
|
||||
self.instance = await websockets.serve(self.entrypoint, "localhost", 1337)
|
||||
return True
|
||||
except Exception:
|
||||
raise
|
||||
async def runImport(self):
|
||||
_start_time = time.time()
|
||||
InitFiles(self.config.file_array)
|
||||
_storage = Storage(self.config)
|
||||
_storage.check_ownership()
|
||||
Catalogue(self.config).import_books()
|
||||
_storage.make_collections()
|
||||
_total_time = round(time.time() - _start_time)
|
||||
|
||||
async def socketio(self, websocket, path):
|
||||
async for message in websocket:
|
||||
if message == "ping":
|
||||
config.logger.info("<< Ping")
|
||||
tx = self.pong()
|
||||
elif message == "importBooks":
|
||||
config.logger.info("Starting Import")
|
||||
tx = "Starting Import . . ."
|
||||
await websocket.send(tx)
|
||||
await runImport()
|
||||
tx = "complete"
|
||||
await websocket.send(tx)
|
||||
|
||||
def pong(self):
|
||||
self.config.logger.info(">> Pong")
|
||||
return "pong"
|
||||
|
||||
def start(self):
|
||||
asyncio.get_event_loop().run_until_complete(self.serve)
|
||||
|
||||
@@ -172,6 +172,14 @@ $(document).ready(function(){
|
||||
});
|
||||
$(document).on('click', '.logout-btn', function(){window.location.href = '/logout'});
|
||||
$(document).on('click', '.import-btn', async function(){
|
||||
$.ajax({
|
||||
type: "GET", url: "/live", data: {hook: 'import_books'},
|
||||
success: function (response) {
|
||||
},
|
||||
error: function (response) {
|
||||
customlog(["Failure", response]);
|
||||
}
|
||||
});
|
||||
let connection = await ImportBooks(server);
|
||||
popover.html('<div id="psout" class="container">');
|
||||
let psout = $('#psout')
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import asyncio
|
||||
|
||||
from base64 import b64decode, b64encode
|
||||
from pathlib import Path
|
||||
|
||||
from backend.lib.config import Config
|
||||
|
||||
from backend.lib.pyShelf import Server
|
||||
from django.conf import settings
|
||||
from django.contrib import auth
|
||||
from django.contrib.auth import authenticate, get_user_model, login, logout
|
||||
@@ -23,7 +24,7 @@ from .forms import SignUpForm, UserLoginForm
|
||||
from .models import Books, Collections, Favorites, Navigation, User
|
||||
|
||||
config = Config(Path("../"))
|
||||
|
||||
server = None
|
||||
|
||||
|
||||
def index(request, query=None, _set=1, _limit=None, _order='title'):
|
||||
@@ -410,14 +411,28 @@ def live(request, **kwargs):
|
||||
return JsonResponse({"data": html})
|
||||
|
||||
elif hook == "import_books":
|
||||
"""TODO: Spawn websocket server"""
|
||||
breakpoint()
|
||||
filename = "../data/{}-{}.sock".format(request.user.username, time.strftime("%H:%M:%S"))
|
||||
catalogue = ACatalogue()
|
||||
async def responder(socket):
|
||||
await catalogue.import_books(socket=socket)
|
||||
return JsonResponse({"data": filename})
|
||||
asyncio.run(responder(filename))
|
||||
|
||||
###################################################
|
||||
# async def responder(socket): #
|
||||
# await catalogue.import_books(socket=socket) #
|
||||
# return JsonResponse({"data": None}) #
|
||||
# pass #
|
||||
# asyncio.run(responder(None)) #
|
||||
###################################################
|
||||
def test_connection(host):
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.connect(host)
|
||||
s.sendall(b"ping")
|
||||
data = s.recv(1024)
|
||||
return data
|
||||
_host = ("127.0.0.1", 1337)
|
||||
try:
|
||||
_server_response = test_connection(_host)
|
||||
except ConnectionRefusedError as e:
|
||||
config.logger.info(e)
|
||||
if e.errno == 111:
|
||||
request.server = Server(Path.absolute(Path.cwd().parent)).start()
|
||||
|
||||
else: return JsonResponse(err_txt, status=404)
|
||||
|
||||
@@ -513,3 +528,6 @@ def payload(request, query, _set, _limit, _order, **kwargs):
|
||||
"SearchLen": _r_len,
|
||||
"Order": _order,
|
||||
}
|
||||
|
||||
def start_server(request, **kwargs):
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user