Pass common into ShareModeWeb and ReceiveModeWeb

This commit is contained in:
Micah Lee 2018-09-21 11:41:49 -07:00
parent 4127aa4d71
commit 5003d44cfb
3 changed files with 38 additions and 31 deletions

View File

@ -12,7 +12,10 @@ class ReceiveModeWeb(object):
""" """
All of the web logic for receive mode All of the web logic for receive mode
""" """
def __init__(self, web): def __init__(self, common, web):
self.common = common
self.common.log('ReceiveModeWeb', '__init__')
self.web = web self.web = web
self.upload_count = 0 self.upload_count = 0
@ -26,7 +29,7 @@ class ReceiveModeWeb(object):
def index_logic(): def index_logic():
self.web.add_request(self.web.REQUEST_LOAD, request.path) self.web.add_request(self.web.REQUEST_LOAD, request.path)
if self.web.common.settings.get('public_mode'): if self.common.settings.get('public_mode'):
upload_action = '/upload' upload_action = '/upload'
close_action = '/close' close_action = '/close'
else: else:
@ -37,7 +40,7 @@ class ReceiveModeWeb(object):
'receive.html', 'receive.html',
upload_action=upload_action, upload_action=upload_action,
close_action=close_action, close_action=close_action,
receive_allow_receiver_shutdown=self.web.common.settings.get('receive_allow_receiver_shutdown'))) receive_allow_receiver_shutdown=self.common.settings.get('receive_allow_receiver_shutdown')))
return self.web.add_security_headers(r) return self.web.add_security_headers(r)
@self.web.app.route("/<slug_candidate>") @self.web.app.route("/<slug_candidate>")
@ -47,7 +50,7 @@ class ReceiveModeWeb(object):
@self.web.app.route("/") @self.web.app.route("/")
def index_public(): def index_public():
if not self.web.common.settings.get('public_mode'): if not self.common.settings.get('public_mode'):
return self.web.error404() return self.web.error404()
return index_logic() return index_logic()
@ -59,18 +62,18 @@ class ReceiveModeWeb(object):
# Make sure downloads_dir exists # Make sure downloads_dir exists
valid = True valid = True
try: try:
self.web.common.validate_downloads_dir() self.common.validate_downloads_dir()
except DownloadsDirErrorCannotCreate: except DownloadsDirErrorCannotCreate:
self.web.add_request(self.web.REQUEST_ERROR_DOWNLOADS_DIR_CANNOT_CREATE, request.path) self.web.add_request(self.web.REQUEST_ERROR_DOWNLOADS_DIR_CANNOT_CREATE, request.path)
print(strings._('error_cannot_create_downloads_dir').format(self.web.common.settings.get('downloads_dir'))) print(strings._('error_cannot_create_downloads_dir').format(self.common.settings.get('downloads_dir')))
valid = False valid = False
except DownloadsDirErrorNotWritable: except DownloadsDirErrorNotWritable:
self.web.add_request(self.web.REQUEST_ERROR_DOWNLOADS_DIR_NOT_WRITABLE, request.path) self.web.add_request(self.web.REQUEST_ERROR_DOWNLOADS_DIR_NOT_WRITABLE, request.path)
print(strings._('error_downloads_dir_not_writable').format(self.web.common.settings.get('downloads_dir'))) print(strings._('error_downloads_dir_not_writable').format(self.common.settings.get('downloads_dir')))
valid = False valid = False
if not valid: if not valid:
flash('Error uploading, please inform the OnionShare user', 'error') flash('Error uploading, please inform the OnionShare user', 'error')
if self.web.common.settings.get('public_mode'): if self.common.settings.get('public_mode'):
return redirect('/') return redirect('/')
else: else:
return redirect('/{}'.format(slug_candidate)) return redirect('/{}'.format(slug_candidate))
@ -83,7 +86,7 @@ class ReceiveModeWeb(object):
# Automatically rename the file, if a file of the same name already exists # Automatically rename the file, if a file of the same name already exists
filename = secure_filename(f.filename) filename = secure_filename(f.filename)
filenames.append(filename) filenames.append(filename)
local_path = os.path.join(self.web.common.settings.get('downloads_dir'), filename) local_path = os.path.join(self.common.settings.get('downloads_dir'), filename)
if os.path.exists(local_path): if os.path.exists(local_path):
if '.' in filename: if '.' in filename:
# Add "-i", e.g. change "foo.txt" to "foo-2.txt" # Add "-i", e.g. change "foo.txt" to "foo-2.txt"
@ -95,7 +98,7 @@ class ReceiveModeWeb(object):
valid = False valid = False
while not valid: while not valid:
new_filename = '{}-{}.{}'.format('.'.join(name), i, ext) new_filename = '{}-{}.{}'.format('.'.join(name), i, ext)
local_path = os.path.join(self.web.common.settings.get('downloads_dir'), new_filename) local_path = os.path.join(self.common.settings.get('downloads_dir'), new_filename)
if os.path.exists(local_path): if os.path.exists(local_path):
i += 1 i += 1
else: else:
@ -106,7 +109,7 @@ class ReceiveModeWeb(object):
valid = False valid = False
while not valid: while not valid:
new_filename = '{}-{}'.format(filename, i) new_filename = '{}-{}'.format(filename, i)
local_path = os.path.join(self.web.common.settings.get('downloads_dir'), new_filename) local_path = os.path.join(self.common.settings.get('downloads_dir'), new_filename)
if os.path.exists(local_path): if os.path.exists(local_path):
i += 1 i += 1
else: else:
@ -121,7 +124,7 @@ class ReceiveModeWeb(object):
'new_filename': basename 'new_filename': basename
}) })
self.web.common.log('Web', 'receive_routes', '/upload, uploaded {}, saving to {}'.format(f.filename, local_path)) self.common.log('ReceiveModeWeb', 'define_routes', '/upload, uploaded {}, saving to {}'.format(f.filename, local_path))
print(strings._('receive_mode_received_file').format(local_path)) print(strings._('receive_mode_received_file').format(local_path))
f.save(local_path) f.save(local_path)
@ -133,7 +136,7 @@ class ReceiveModeWeb(object):
for filename in filenames: for filename in filenames:
flash('Sent {}'.format(filename), 'info') flash('Sent {}'.format(filename), 'info')
if self.web.common.settings.get('public_mode'): if self.common.settings.get('public_mode'):
return redirect('/') return redirect('/')
else: else:
return redirect('/{}'.format(slug_candidate)) return redirect('/{}'.format(slug_candidate))
@ -145,13 +148,13 @@ class ReceiveModeWeb(object):
@self.web.app.route("/upload", methods=['POST']) @self.web.app.route("/upload", methods=['POST'])
def upload_public(): def upload_public():
if not self.web.common.settings.get('public_mode'): if not self.common.settings.get('public_mode'):
return self.web.error404() return self.web.error404()
return upload_logic() return upload_logic()
def close_logic(slug_candidate=''): def close_logic(slug_candidate=''):
if self.web.common.settings.get('receive_allow_receiver_shutdown'): if self.common.settings.get('receive_allow_receiver_shutdown'):
self.web.force_shutdown() self.web.force_shutdown()
r = make_response(render_template('closed.html')) r = make_response(render_template('closed.html'))
self.web.add_request(self.web.REQUEST_CLOSE_SERVER, request.path) self.web.add_request(self.web.REQUEST_CLOSE_SERVER, request.path)
@ -166,7 +169,7 @@ class ReceiveModeWeb(object):
@self.web.app.route("/close", methods=['POST']) @self.web.app.route("/close", methods=['POST'])
def close_public(): def close_public():
if not self.web.common.settings.get('public_mode'): if not self.common.settings.get('public_mode'):
return self.web.error404() return self.web.error404()
return close_logic() return close_logic()

View File

@ -12,7 +12,10 @@ class ShareModeWeb(object):
""" """
All of the web logic for share mode All of the web logic for share mode
""" """
def __init__(self, web): def __init__(self, common, web):
self.common = common
self.common.log('ShareModeWeb', '__init__')
self.web = web self.web = web
# Information about the file to be shared # Information about the file to be shared
@ -46,7 +49,7 @@ class ShareModeWeb(object):
@self.web.app.route("/") @self.web.app.route("/")
def index_public(): def index_public():
if not self.web.common.settings.get('public_mode'): if not self.common.settings.get('public_mode'):
return self.web.error404() return self.web.error404()
return index_logic() return index_logic()
@ -71,7 +74,7 @@ class ShareModeWeb(object):
file_info=self.file_info, file_info=self.file_info,
filename=os.path.basename(self.download_filename), filename=os.path.basename(self.download_filename),
filesize=self.download_filesize, filesize=self.download_filesize,
filesize_human=self.web.common.human_readable_filesize(self.download_filesize), filesize_human=self.common.human_readable_filesize(self.download_filesize),
is_zipped=self.is_zipped)) is_zipped=self.is_zipped))
else: else:
# If download is allowed to continue, serve download page # If download is allowed to continue, serve download page
@ -80,7 +83,7 @@ class ShareModeWeb(object):
file_info=self.file_info, file_info=self.file_info,
filename=os.path.basename(self.download_filename), filename=os.path.basename(self.download_filename),
filesize=self.download_filesize, filesize=self.download_filesize,
filesize_human=self.web.common.human_readable_filesize(self.download_filesize), filesize_human=self.common.human_readable_filesize(self.download_filesize),
is_zipped=self.is_zipped)) is_zipped=self.is_zipped))
return self.web.add_security_headers(r) return self.web.add_security_headers(r)
@ -91,7 +94,7 @@ class ShareModeWeb(object):
@self.web.app.route("/download") @self.web.app.route("/download")
def download_public(): def download_public():
if not self.web.common.settings.get('public_mode'): if not self.common.settings.get('public_mode'):
return self.web.error404() return self.web.error404()
return download_logic() return download_logic()
@ -156,9 +159,9 @@ class ShareModeWeb(object):
percent = (1.0 * downloaded_bytes / self.download_filesize) * 100 percent = (1.0 * downloaded_bytes / self.download_filesize) * 100
# only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304)
if not self.web.is_gui or self.web.common.platform == 'Linux' or self.web.common.platform == 'BSD': if not self.web.is_gui or self.common.platform == 'Linux' or self.common.platform == 'BSD':
sys.stdout.write( sys.stdout.write(
"\r{0:s}, {1:.2f}% ".format(self.web.common.human_readable_filesize(downloaded_bytes), percent)) "\r{0:s}, {1:.2f}% ".format(self.common.human_readable_filesize(downloaded_bytes), percent))
sys.stdout.flush() sys.stdout.flush()
self.web.add_request(self.web.REQUEST_PROGRESS, path, { self.web.add_request(self.web.REQUEST_PROGRESS, path, {
@ -178,7 +181,7 @@ class ShareModeWeb(object):
fp.close() fp.close()
if self.web.common.platform != 'Darwin': if self.common.platform != 'Darwin':
sys.stdout.write("\n") sys.stdout.write("\n")
# Download is finished # Download is finished
@ -212,7 +215,7 @@ class ShareModeWeb(object):
page will need to display. This includes zipping up the file in order to page will need to display. This includes zipping up the file in order to
get the zip file's name and size. get the zip file's name and size.
""" """
self.web.common.log("Web", "set_file_info") self.common.log("ShareModeWeb", "set_file_info")
self.web.cancel_compression = False self.web.cancel_compression = False
# build file info list # build file info list
@ -224,11 +227,11 @@ class ShareModeWeb(object):
} }
if os.path.isfile(filename): if os.path.isfile(filename):
info['size'] = os.path.getsize(filename) info['size'] = os.path.getsize(filename)
info['size_human'] = self.web.common.human_readable_filesize(info['size']) info['size_human'] = self.common.human_readable_filesize(info['size'])
self.file_info['files'].append(info) self.file_info['files'].append(info)
if os.path.isdir(filename): if os.path.isdir(filename):
info['size'] = self.web.common.dir_size(filename) info['size'] = self.common.dir_size(filename)
info['size_human'] = self.web.common.human_readable_filesize(info['size']) info['size_human'] = self.common.human_readable_filesize(info['size'])
self.file_info['dirs'].append(info) self.file_info['dirs'].append(info)
self.file_info['files'] = sorted(self.file_info['files'], key=lambda k: k['basename']) self.file_info['files'] = sorted(self.file_info['files'], key=lambda k: k['basename'])
self.file_info['dirs'] = sorted(self.file_info['dirs'], key=lambda k: k['basename']) self.file_info['dirs'] = sorted(self.file_info['dirs'], key=lambda k: k['basename'])
@ -240,7 +243,7 @@ class ShareModeWeb(object):
self.download_filesize = self.file_info['files'][0]['size'] self.download_filesize = self.file_info['files'][0]['size']
else: else:
# Zip up the files and folders # Zip up the files and folders
self.zip_writer = ZipWriter(self.web.common, processed_size_callback=processed_size_callback) self.zip_writer = ZipWriter(self.common, processed_size_callback=processed_size_callback)
self.download_filename = self.zip_writer.zip_filename self.download_filename = self.zip_writer.zip_filename
for info in self.file_info['files']: for info in self.file_info['files']:
self.zip_writer.add_file(info['filename']) self.zip_writer.add_file(info['filename'])

View File

@ -43,6 +43,7 @@ class Web(object):
def __init__(self, common, is_gui, mode='share'): def __init__(self, common, is_gui, mode='share'):
self.common = common self.common = common
self.common.log('Web', '__init__', 'is_gui={}, mode={}'.format(is_gui, mode))
# The flask app # The flask app
self.app = Flask(__name__, self.app = Flask(__name__,
@ -101,9 +102,9 @@ class Web(object):
self.share_mode = None self.share_mode = None
self.receive_mode = None self.receive_mode = None
if self.mode == 'receive': if self.mode == 'receive':
self.receive_mode = ReceiveModeWeb(self) self.receive_mode = ReceiveModeWeb(self.common, self)
elif self.mode == 'share': elif self.mode == 'share':
self.share_mode = ShareModeWeb(self) self.share_mode = ShareModeWeb(self.common, self)
def define_common_routes(self): def define_common_routes(self):