Onionr/src/httpapi/onionrsitesapi/sitefiles.py

73 lines
2.3 KiB
Python
Raw Normal View History

2019-11-16 04:18:38 +00:00
"""
Onionr - Private P2P Communication
Read onionr site files
"""
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
2019-11-04 10:52:38 +00:00
from typing import Union, Tuple
2019-10-31 09:29:03 +00:00
import tarfile
import io
import os
2019-10-31 09:29:03 +00:00
2019-11-12 05:32:18 +00:00
import unpaddedbase32
2019-10-31 09:29:03 +00:00
from coredb import blockmetadb
from onionrblocks import onionrblockapi
from onionrblocks import insert
2019-11-04 10:52:38 +00:00
# Import types. Just for type hiting
from onionrtypes import UserID, DeterministicKeyPassphrase, BlockHash
from onionrcrypto import generate_deterministic
2019-10-31 09:29:03 +00:00
2019-11-12 05:32:18 +00:00
def find_site_gzip(user_id: str)->tarfile.TarFile:
"""Return verified site tar object"""
2019-10-31 09:29:03 +00:00
sites = blockmetadb.get_blocks_by_type('osite')
user_site = None
2019-11-12 05:32:18 +00:00
user_id = unpaddedbase32.repad(user_id)
2019-10-31 09:29:03 +00:00
for site in sites:
block = onionrblockapi.Block(site)
if block.isSigner(user_id):
user_site = block
if not user_site is None:
return tarfile.open(fileobj=io.BytesIO(user_site.bcontent), mode='r')
2019-10-31 09:29:03 +00:00
return None
def get_file(user_id, file)->Union[bytes, None]:
2019-11-12 05:32:18 +00:00
"""Get a site file content"""
2019-10-31 09:29:03 +00:00
ret_data = ""
site = find_site_gzip(user_id)
if site is None: return None
2019-11-12 05:32:18 +00:00
for t_file in site.getmembers():
if t_file.name.replace('./', '') == file:
return site.extractfile(t_file)
2019-10-31 09:29:03 +00:00
return None
2019-11-04 10:52:38 +00:00
def create_site(admin_pass: DeterministicKeyPassphrase, directory:str='.')->Tuple[UserID, BlockHash]:
public_key, private_key = generate_deterministic(admin_pass)
raw_tar = io.BytesIO()
tar = tarfile.open(mode='x:gz', fileobj=raw_tar)
tar.add(directory)
tar.close()
raw_tar.seek(0)
2019-11-12 05:32:18 +00:00
block_hash = insert(raw_tar.read(), header='osite', signing_key=private_key, sign=True)
2019-11-04 10:52:38 +00:00
return (public_key, block_hash)