This repository has been archived on 2024-07-30. You can view files and clone it, but cannot push or open issues or pull requests.
python-aternos/python_aternos/atfm.py

102 lines
2.3 KiB
Python
Raw Normal View History

import lxml.html
2022-03-18 17:38:36 +03:00
from typing import Union, List
2021-10-15 18:31:47 +03:00
from typing import TYPE_CHECKING
2022-03-18 17:38:36 +03:00
from .atfile import AternosFile, FileType
2021-10-15 18:31:47 +03:00
if TYPE_CHECKING:
2022-03-18 17:38:36 +03:00
from .atserver import AternosServer
2021-10-15 18:31:47 +03:00
2022-03-18 17:38:36 +03:00
class FileManager:
2021-10-15 18:31:47 +03:00
def __init__(self, atserv:'AternosServer') -> None:
self.atserv = atserv
2022-03-18 17:38:36 +03:00
def listdir(self, path:str='') -> List[AternosFile]:
path = path.lstrip('/')
filesreq = self.atserv.atserver_request(
2022-03-18 17:38:36 +03:00
f'https://aternos.org/files/{path}', 'GET'
)
filestree = lxml.html.fromstring(filesreq.content)
fileslist = filestree.xpath('//div[contains(concat(" ",normalize-space(@class)," ")," file ")]')
files = []
for f in fileslist:
2022-03-25 15:45:38 +03:00
ftype_raw = f.xpath('@data-type')[0]
2022-03-18 17:38:36 +03:00
ftype = FileType.file \
if ftype_raw == 'file' \
2022-03-18 17:38:36 +03:00
else FileType.directory
2022-03-25 15:45:38 +03:00
fsize_raw = f.xpath('./div[@class="filesize"]')
fsize = 0
if len(fsize_raw) > 0:
fsize_text = fsize_raw[0].text.strip()
fsize_num = fsize_text[:fsize_text.rfind(' ')]
fsize_msr = fsize_text[fsize_text.rfind(' ')+1:]
2021-10-14 17:41:57 +03:00
try:
2022-03-18 17:38:36 +03:00
fsize = self.convert_size(float(fsize_num), fsize_msr)
2021-10-14 17:41:57 +03:00
except ValueError:
fsize = -1
2022-03-25 15:45:38 +03:00
fullpath = f.xpath('@data-path')[0]
filepath = fullpath[:fullpath.rfind('/')]
filename = fullpath[fullpath.rfind('/'):]
files.append(
2022-03-18 17:38:36 +03:00
AternosFile(
self.atserv,
filepath, filename,
2022-03-25 15:45:38 +03:00
ftype, fsize
)
)
return files
def convert_size(self, num:Union[int,float], measure:str) -> float:
measure_match = {
'B': 1,
'kB': 1000,
'MB': 1000000,
'GB': 1000000000
}
try:
return num * measure_match[measure]
except KeyError:
return -1
2022-03-18 17:38:36 +03:00
def get_file(self, path:str) -> Union[AternosFile,None]:
filepath = path[:path.rfind('/')]
filename = path[path.rfind('/'):]
2022-03-18 17:38:36 +03:00
filedir = self.listdir(filepath)
for file in filedir:
if file.name == filename:
return file
return None
def dl_file(self, path:str) -> bytes:
file = self.atserv.atserver_request(
f'https://aternos.org/panel/ajax/files/download.php?' + \
f'file={path.replace("/","%2F")}',
2022-03-18 17:38:36 +03:00
'GET'
)
return file.content
def dl_world(self, world:str='world') -> bytes:
world = self.atserv.atserver_request(
f'https://aternos.org/panel/ajax/worlds/download.php?' + \
f'world={world.replace("/","%2F")}',
2022-03-18 17:38:36 +03:00
'GET'
)
return world.content