summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.circleci/config.yml55
-rw-r--r--.github/CODEOWNERS8
-rw-r--r--.gitignore1
-rw-r--r--.travis.yml22
-rw-r--r--BUILD.md54
-rw-r--r--LICENSE2
-rw-r--r--MANIFEST.in5
-rw-r--r--README.md30
-rwxr-xr-xdev_scripts/onionshare2
-rwxr-xr-xdev_scripts/onionshare-gui2
-rwxr-xr-xinstall/build_rpm.sh2
-rw-r--r--install/check_lacked_trans.py15
-rw-r--r--install/get-tor-osx.py12
-rw-r--r--install/get-tor-windows.py8
-rw-r--r--install/licenses/license-onionshare.txt3
-rw-r--r--install/onionshare.desktop5
-rw-r--r--install/onionshare.nsi392
-rw-r--r--install/pyinstaller.spec7
-rw-r--r--install/requirements-tests.txt10
-rw-r--r--install/requirements-windows.txt14
-rw-r--r--install/requirements.txt34
-rwxr-xr-xinstall/scripts/onionshare2
-rwxr-xr-xinstall/scripts/onionshare-gui2
-rw-r--r--install/scripts/onionshare-pyinstaller2
-rw-r--r--onionshare/__init__.py182
-rw-r--r--onionshare/common.py647
-rw-r--r--onionshare/onion.py146
-rw-r--r--onionshare/onionshare.py42
-rw-r--r--onionshare/settings.py79
-rw-r--r--onionshare/socks.py530
-rw-r--r--onionshare/strings.py49
-rw-r--r--onionshare/web.py454
-rw-r--r--onionshare/web/__init__.py (renamed from onionshare_gui/alert.py)22
-rw-r--r--onionshare/web/receive_mode.py343
-rw-r--r--onionshare/web/share_mode.py384
-rw-r--r--onionshare/web/web.py269
-rw-r--r--onionshare_gui/__init__.py61
-rw-r--r--onionshare_gui/downloads.py134
-rw-r--r--onionshare_gui/mode/__init__.py337
-rw-r--r--onionshare_gui/mode/history.py559
-rw-r--r--onionshare_gui/mode/receive_mode/__init__.py214
-rw-r--r--onionshare_gui/mode/share_mode/__init__.py382
-rw-r--r--onionshare_gui/mode/share_mode/file_selection.py (renamed from onionshare_gui/file_selection.py)91
-rw-r--r--onionshare_gui/mode/share_mode/threads.py63
-rw-r--r--onionshare_gui/onionshare_gui.py882
-rw-r--r--onionshare_gui/server_status.py188
-rw-r--r--onionshare_gui/settings_dialog.py621
-rw-r--r--onionshare_gui/threads.py77
-rw-r--r--onionshare_gui/tor_connection_dialog.py53
-rw-r--r--onionshare_gui/update_checker.py60
-rw-r--r--onionshare_gui/widgets.py65
-rw-r--r--screenshots/client.pngbin40602 -> 0 bytes
-rw-r--r--screenshots/onionshare-receive-client.pngbin0 -> 59463 bytes
-rw-r--r--screenshots/onionshare-receive-server.pngbin0 -> 68038 bytes
-rw-r--r--screenshots/onionshare-share-client.pngbin0 -> 42423 bytes
-rw-r--r--screenshots/onionshare-share-server.pngbin0 -> 55027 bytes
-rw-r--r--screenshots/server.pngbin45923 -> 0 bytes
-rw-r--r--setup.py18
-rw-r--r--share/html/404.html16
-rw-r--r--share/html/denied.html19
-rw-r--r--share/html/index.html208
-rw-r--r--share/images/downloads.pngbin0 -> 2120 bytes
-rw-r--r--share/images/downloads_toggle.pngbin0 -> 380 bytes
-rw-r--r--share/images/downloads_toggle_selected.pngbin0 -> 468 bytes
-rw-r--r--share/images/downloads_transparent.pngbin0 -> 2138 bytes
-rw-r--r--share/images/open_folder.pngbin0 -> 221 bytes
-rw-r--r--share/images/settings.pngbin411 -> 443 bytes
-rw-r--r--share/images/share_completed.png (renamed from share/images/download_completed.png)bin646 -> 646 bytes
-rw-r--r--share/images/share_completed_none.png (renamed from share/images/download_completed_none.png)bin437 -> 437 bytes
-rw-r--r--share/images/share_in_progress.png (renamed from share/images/download_in_progress.png)bin638 -> 638 bytes
-rw-r--r--share/images/share_in_progress_none.png (renamed from share/images/download_in_progress_none.png)bin412 -> 412 bytes
-rw-r--r--share/images/uploads.pngbin0 -> 2076 bytes
-rw-r--r--share/images/uploads_toggle.pngbin0 -> 389 bytes
-rw-r--r--share/images/uploads_toggle_selected.pngbin0 -> 473 bytes
-rw-r--r--share/images/uploads_transparent.pngbin0 -> 2096 bytes
-rw-r--r--share/locale/cs.json31
-rw-r--r--share/locale/da.json35
-rw-r--r--share/locale/de.json15
-rw-r--r--share/locale/en.json231
-rw-r--r--share/locale/eo.json33
-rw-r--r--share/locale/es.json15
-rw-r--r--share/locale/fi.json22
-rw-r--r--share/locale/fr.json17
-rw-r--r--share/locale/it.json22
-rw-r--r--share/locale/nl.json30
-rw-r--r--share/locale/no.json3
-rw-r--r--share/locale/pt_BR.json (renamed from share/locale/pt.json)3
-rw-r--r--share/locale/pt_PT.json7
-rw-r--r--share/locale/ru.json3
-rw-r--r--share/locale/tr.json22
-rw-r--r--share/static/css/style.css194
-rw-r--r--share/static/img/favicon.ico (renamed from share/images/favicon.ico)bin4286 -> 4286 bytes
-rw-r--r--share/static/img/logo.pngbin0 -> 3824 bytes
-rw-r--r--share/static/img/logo_large.pngbin0 -> 9663 bytes
-rw-r--r--share/static/img/web_file.png (renamed from share/images/web_file.png)bin251 -> 251 bytes
-rw-r--r--share/static/img/web_folder.png (renamed from share/images/web_folder.png)bin338 -> 338 bytes
-rw-r--r--share/static/js/send.js75
-rw-r--r--share/templates/403.html16
-rw-r--r--share/templates/404.html16
-rw-r--r--share/templates/denied.html10
-rw-r--r--share/templates/receive.html38
-rw-r--r--share/templates/send.html56
-rw-r--r--share/templates/thankyou.html22
-rw-r--r--share/version.txt2
-rw-r--r--stdeb.cfg8
-rw-r--r--tests/GuiBaseTest.py323
-rw-r--r--tests/GuiReceiveTest.py124
-rw-r--r--tests/GuiShareTest.py204
-rw-r--r--tests/SettingsGuiBaseTest.py44
-rw-r--r--tests/TorGuiBaseTest.py173
-rw-r--r--tests/TorGuiReceiveTest.py59
-rw-r--r--tests/TorGuiShareTest.py95
-rw-r--r--tests/__init__.py (renamed from test/__init__.py)0
-rw-r--r--tests/conftest.py (renamed from test/conftest.py)46
-rw-r--r--tests/local_onionshare_404_public_mode_skips_ratelimit_test.py25
-rw-r--r--tests/local_onionshare_404_triggers_ratelimit_test.py24
-rw-r--r--tests/local_onionshare_quitting_during_share_prompts_warning_test.py31
-rw-r--r--tests/local_onionshare_receive_mode_sender_closed_test.py24
-rw-r--r--tests/local_onionshare_receive_mode_timer_test.py24
-rw-r--r--tests/local_onionshare_receive_mode_upload_non_writable_dir_test.py23
-rw-r--r--tests/local_onionshare_receive_mode_upload_public_mode_non_writable_dir_test.py24
-rw-r--r--tests/local_onionshare_receive_mode_upload_public_mode_test.py24
-rw-r--r--tests/local_onionshare_receive_mode_upload_test.py23
-rw-r--r--tests/local_onionshare_settings_dialog_test.py172
-rw-r--r--tests/local_onionshare_share_mode_download_public_mode_test.py23
-rw-r--r--tests/local_onionshare_share_mode_download_stay_open_test.py23
-rw-r--r--tests/local_onionshare_share_mode_download_test.py22
-rw-r--r--tests/local_onionshare_share_mode_large_download_test.py22
-rw-r--r--tests/local_onionshare_share_mode_slug_persistent_test.py26
-rw-r--r--tests/local_onionshare_share_mode_timer_test.py24
-rw-r--r--tests/local_onionshare_share_mode_timer_too_short_test.py31
-rw-r--r--tests/local_onionshare_share_mode_unreadable_file_test.py22
-rw-r--r--tests/onionshare_790_cancel_on_second_share_test.py29
-rw-r--r--tests/onionshare_receive_mode_upload_public_mode_test.py26
-rw-r--r--tests/onionshare_receive_mode_upload_test.py25
-rw-r--r--tests/onionshare_share_mode_cancel_share_test.py25
-rw-r--r--tests/onionshare_share_mode_download_public_mode_test.py25
-rw-r--r--tests/onionshare_share_mode_download_stay_open_test.py25
-rw-r--r--tests/onionshare_share_mode_download_test.py24
-rw-r--r--tests/onionshare_share_mode_persistent_test.py29
-rw-r--r--tests/onionshare_share_mode_stealth_test.py29
-rw-r--r--tests/onionshare_share_mode_timer_test.py26
-rw-r--r--tests/onionshare_share_mode_tor_connection_killed_test.py25
-rw-r--r--tests/onionshare_share_mode_v2_onion_test.py26
-rw-r--r--tests/test_helpers.py (renamed from test/test_helpers.py)2
-rw-r--r--tests/test_onionshare.py (renamed from test/test_onionshare.py)7
-rw-r--r--tests/test_onionshare_common.py (renamed from test/test_onionshare_common.py)163
-rw-r--r--tests/test_onionshare_settings.py (renamed from test/test_onionshare_settings.py)38
-rw-r--r--tests/test_onionshare_strings.py (renamed from test/test_onionshare_strings.py)41
-rw-r--r--tests/test_onionshare_web.py226
150 files changed, 7483 insertions, 3773 deletions
diff --git a/.circleci/config.yml b/.circleci/config.yml
new file mode 100644
index 00000000..70fa3b7c
--- /dev/null
+++ b/.circleci/config.yml
@@ -0,0 +1,55 @@
+# Python CircleCI 2.0 configuration file
+#
+# Check https://circleci.com/docs/2.0/language-python/ for more details
+#
+version: 2
+workflows:
+ version: 2
+ test:
+ jobs:
+ - test-3.5
+ - test-3.6
+ - test-3.7
+
+jobs:
+ test-3.5: &test-template
+ docker:
+ - image: circleci/python:3.5.6
+
+ working_directory: ~/repo
+
+ steps:
+ - checkout
+
+ - run:
+ name: install dependencies
+ command: |
+ sudo apt-get update
+ sudo apt-get install -y python3-pip python3-flask python3-stem python3-pyqt5 python3-crypto python3-socks python3-stdeb python3-all python-nautilus xvfb obfs4proxy
+ sudo pip3 install -r install/requirements.txt
+ sudo pip3 install -r install/requirements-tests.txt
+ sudo pip3 install pytest-cov flake8
+
+ # run tests!
+ - run:
+ name: run flake tests
+ command: |
+ # stop the build if there are Python syntax errors or undefined names
+ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
+ # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
+ flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
+
+ - run:
+ name: run tests
+ command: |
+ xvfb-run pytest --cov=onionshare --cov=onionshare_gui --cov-report=term-missing -vvv tests/
+
+ test-3.6:
+ <<: *test-template
+ docker:
+ - image: circleci/python:3.6.6
+
+ test-3.7:
+ <<: *test-template
+ docker:
+ - image: circleci/python:3.7.1
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 1cd5a1f6..42d1840f 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -1 +1,9 @@
* @micahflee
+
+# localization
+/share/locale/ @emmapeel2
+
+# tests
+/tests/ @mig5
+/tests_gui_local/ @mig5
+/tests_gui_tor/ @mig5
diff --git a/.gitignore b/.gitignore
index b202993b..12201adb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+__pycache__
*.py[cod]
# C extensions
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 9010e77a..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-language: python
-# sudo: required
-dist: trusty
-python:
- - "3.4"
- - "3.5"
- - "3.6"
- - "3.6-dev"
- - "3.7-dev"
- - "nightly"
-# command to install dependencies
-install:
- - pip install Flask==0.12 stem==1.5.4 pytest-cov coveralls flake8
-before_script:
- # stop the build if there are Python syntax errors or undefined names
- - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
- # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
- - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
-# command to run tests
-script: pytest --cov=onionshare test/
-after_success:
- - coveralls
diff --git a/BUILD.md b/BUILD.md
index 77d5ee0e..7663ec23 100644
--- a/BUILD.md
+++ b/BUILD.md
@@ -11,9 +11,17 @@ cd onionshare
Install the needed dependencies:
-For Debian-like distros: `apt install -y build-essential fakeroot python3-all python3-stdeb dh-python python3-flask python3-stem python3-pyqt5 python-nautilus python3-pytest tor obfs4proxy`
+For Debian-like distros:
-For Fedora-like distros: `dnf install -y rpm-build python3-flask python3-stem python3-qt5 python3-pytest nautilus-python tor obfs4`
+```
+apt install -y python3-flask python3-stem python3-pyqt5 python3-crypto python3-socks python-nautilus tor obfs4proxy python3-pytest build-essential fakeroot python3-all python3-stdeb dh-python
+```
+
+For Fedora-like distros:
+
+```
+dnf install -y python3-flask python3-stem python3-qt5 python3-crypto python3-pysocks nautilus-python tor obfs4 python3-pytest rpm-build
+```
After that you can try both the CLI and the GUI version of OnionShare:
@@ -28,6 +36,8 @@ Create a .deb on Debian-like distros: `./install/build_deb.sh`
Create a .rpm on Fedora-like distros: `./install/build_rpm.sh`
+For OpenSuSE: There are instructions for building [in the wiki](https://github.com/micahflee/onionshare/wiki/Linux-Distribution-Support#opensuse-leap-150).
+
For ArchLinux: There is a PKBUILD available [here](https://aur.archlinux.org/packages/onionshare/) that can be used to install OnionShare.
If you find that these instructions don't work for your Linux distribution or version, consult the [Linux Distribution Support wiki guide](https://github.com/micahflee/onionshare/wiki/Linux-Distribution-Support), which might contain extra instructions.
@@ -36,16 +46,16 @@ If you find that these instructions don't work for your Linux distribution or ve
Install Xcode from the Mac App Store. Once it's installed, run it for the first time to set it up. Also, run this to make sure command line tools are installed: `xcode-select --install`. And finally, open Xcode, go to Preferences > Locations, and make sure under Command Line Tools you select an installed version from the dropdown. (This is required for installing Qt5.)
-Download and install Python 3.6.4 from https://www.python.org/downloads/release/python-364/. I downloaded `python-3.6.4-macosx10.6.pkg`.
+Download and install Python 3.7.0 from https://www.python.org/downloads/release/python-370/. I downloaded `python-3.7.0-macosx10.9.pkg`.
-You may also need to run the command `/Applications/Python\ 3.6/Install\ Certificates.command` to update Python 3.6's internal certificate store. Otherwise, you may find that fetching the Tor Browser .dmg file fails later due to a certificate validation error.
+You may also need to run the command `/Applications/Python\ 3.7/Install\ Certificates.command` to update Python 3.6's internal certificate store. Otherwise, you may find that fetching the Tor Browser .dmg file fails later due to a certificate validation error.
-Download and install Qt5 from https://www.qt.io/download-open-source/. I downloaded `qt-unified-mac-x64-3.0.2-online.dmg`. There's no need to login to a Qt account during installation. Make sure you install the latest Qt 5.x. I installed Qt 5.10.0 -- all you need is to check `Qt > Qt 5.10.0 > macOS`.
+Download and install Qt5 from https://www.qt.io/download-open-source/. I downloaded `qt-unified-mac-x64-3.0.5-online.dmg`. There's no need to login to a Qt account during installation. When you select components, install the `macOS` component from Qt 5.11.1 (or whatever the latest Qt version is).
Now install some python dependencies with pip (note, there's issues building a .app if you install this in a virtualenv):
```sh
-sudo pip3 install -r install/requirements.txt
+pip3 install -r install/requirements.txt
```
You can run both the CLI and GUI versions of OnionShare without building an bundle:
@@ -75,17 +85,15 @@ Now you should have `dist/OnionShare.pkg`.
### Setting up your dev environment
-Download Python 3.6.4, 32-bit (x86) from https://www.python.org/downloads/release/python-364/. I downloaded `python-3.6.4.exe`. When installing it, make sure to check the "Add Python 3.6 to PATH" checkbox on the first page of the installer.
+Download Python 3.7.0, 32-bit (x86) from https://www.python.org/downloads/release/python-370/. I downloaded `python-3.7.0.exe`. When installing it, make sure to check the "Add Python 3.7 to PATH" checkbox on the first page of the installer.
Open a command prompt, cd to the onionshare folder, and install dependencies with pip:
```cmd
-pip3 install -r install\requirements-windows.txt
+pip install -r install\requirements.txt
```
-Download and install pywin32 (build 221, x86, for python 3.6) from https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/. I downloaded `pywin32-221.win32-py3.6.exe`.
-
-Download and install Qt5 from https://www.qt.io/download-open-source/. I downloaded `qt-unified-windows-x86-3.0.4-online.exe`. There's no need to login to a Qt account during installation. Make sure you install the latest Qt 5.x. I installed Qt 5.11.0. You only need to install the `MSVC 2015 32-bit` component, as well as all of the the `Qt` components, for that that version.
+Download and install Qt5 from https://www.qt.io/download-open-source/. I downloaded `qt-unified-windows-x86-3.0.5-online.exe`. There's no need to login to a Qt account during installation. When you can select components, install the `MSVC 2015 32-bit` component from Qt 5.11.1 (or whatever the latest Qt version is).
After that you can try both the CLI and the GUI version of OnionShare:
@@ -135,8 +143,28 @@ This will prompt you to codesign three binaries and execute one unsigned binary.
## Tests
-OnionShare includes PyTest unit tests. To run the tests:
+OnionShare includes PyTest unit tests. To run the tests, first install some dependencies:
+
+```sh
+pip3 install -r install/requirements-tests.txt
+```
+
+Then you can run `pytest` against the `tests/` directory.
+
+```sh
+pytest tests/
+```
+
+If you would like to also run the GUI unit tests in 'tor' mode, start Tor Browser in the background, then run:
+
+```sh
+pytest --runtor tests/
+```
+
+Keep in mind that the Tor tests take a lot longer to run than local mode, but they are also more comprehensive.
+
+You can also choose to wrap the tests in `xvfb-run` so that a ton of OnionShare windows don't pop up on your desktop (you may need to install the `xorg-x11-server-Xvfb` package), like this:
```sh
-pytest test/
+xvfb-run pytest tests/
```
diff --git a/LICENSE b/LICENSE
index 5a03b106..668a10f0 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,7 +1,7 @@
(Note: Third-party licenses can be found under install/licenses/.)
OnionShare
-Copyright © 2018 Micah Lee <micah@micahflee.com>
+Copyright © 2014-2018 Micah Lee <micah@micahflee.com>
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
diff --git a/MANIFEST.in b/MANIFEST.in
index f4d1c078..71af3740 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -4,9 +4,10 @@ include BUILD.md
include share/*
include share/images/*
include share/locale/*
-include share/html/*
+include share/templates/*
+include share/static/*
include install/onionshare.desktop
include install/onionshare.appdata.xml
include install/onionshare80.xpm
include install/scripts/onionshare-nautilus.py
-include test/*.py
+include tests/*.py
diff --git a/README.md b/README.md
index 55487045..caa4cb62 100644
--- a/README.md
+++ b/README.md
@@ -1,22 +1,38 @@
# OnionShare
-[![Build Status](https://travis-ci.org/micahflee/onionshare.png)](https://travis-ci.org/micahflee/onionshare)
-
[OnionShare](https://onionshare.org) lets you securely and anonymously share files of any size. It works by starting a web server, making it accessible as a Tor Onion Service, and generating an unguessable URL to access and download the files. It does _not_ require setting up a separate server or using a third party file-sharing service. You host the files on your own computer and use a Tor Onion Service to make it temporarily accessible over the internet. The receiving user just needs to open the URL in Tor Browser to download the file.
## Documentation
To learn how OnionShare works, what its security properties are, and how to use it, check out the [wiki](https://github.com/micahflee/onionshare/wiki).
-## Downloading Onionshare
+## Downloading OnionShare
+
+You can download OnionShare for Windows and macOS from the [OnionShare website](https://onionshare.org).
+
+For Ubuntu-like distributions, you could use this PPA to get the latest version:
+
+```
+sudo add-apt-repository ppa:micahflee/ppa
+sudo apt install -y onionshare
+```
+
+OnionShare also may be available in your operating system's package manager:
-You can download OnionShare for Windows and macOS from the [OnionShare website](https://onionshare.org). It should be available in your package manager for Linux, and it's included by default in [Tails](https://tails.boum.org).
+[![Packaging status](https://repology.org/badge/vertical-allrepos/onionshare.svg)](https://repology.org/metapackage/onionshare/versions)
## Developing OnionShare
You can set up your development environment to build OnionShare yourself by following [these instructions](/BUILD.md). You may also subscribe to our developers mailing list [here](https://lists.riseup.net/www/info/onionshare-dev).
-# Screenshots
+Test status: [![CircleCI](https://circleci.com/gh/micahflee/onionshare.svg?style=svg)](https://circleci.com/gh/micahflee/onionshare)
+
+# Screenshots
+
+![Share mode OnionShare](/screenshots/onionshare-share-server.png)
+
+![Share mode Tor Browser](/screenshots/onionshare-share-client.png)
+
+![Receive mode OnionShare](/screenshots/onionshare-receive-server.png)
-![Server Screenshot](/screenshots/server.png)
-![Client Screenshot](/screenshots/client.png)
+![Receive mode Tor Browser](/screenshots/onionshare-receive-client.png)
diff --git a/dev_scripts/onionshare b/dev_scripts/onionshare
index 358293e1..29cdedcc 100755
--- a/dev_scripts/onionshare
+++ b/dev_scripts/onionshare
@@ -3,7 +3,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
diff --git a/dev_scripts/onionshare-gui b/dev_scripts/onionshare-gui
index 4e008809..40ab742c 100755
--- a/dev_scripts/onionshare-gui
+++ b/dev_scripts/onionshare-gui
@@ -3,7 +3,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
diff --git a/install/build_rpm.sh b/install/build_rpm.sh
index c103262c..7a34b271 100755
--- a/install/build_rpm.sh
+++ b/install/build_rpm.sh
@@ -9,7 +9,7 @@ VERSION=`cat share/version.txt`
rm -r build dist >/dev/null 2>&1
# build binary package
-python3 setup.py bdist_rpm --requires="python3-flask, python3-stem, python3-qt5, nautilus-python, tor, obfs4"
+python3 setup.py bdist_rpm --requires="python3-flask, python3-stem, python3-qt5, python3-cryptography, python3-crypto, python3-pysocks, nautilus-python, tor, obfs4"
# install it
echo ""
diff --git a/install/check_lacked_trans.py b/install/check_lacked_trans.py
index 3313db7c..1caa6b27 100644
--- a/install/check_lacked_trans.py
+++ b/install/check_lacked_trans.py
@@ -54,7 +54,12 @@ def main():
dir = args.onionshare_dir
- src = files_in(dir, 'onionshare') + files_in(dir, 'onionshare_gui')
+ src = files_in(dir, 'onionshare') + \
+ files_in(dir, 'onionshare_gui') + \
+ files_in(dir, 'onionshare_gui/share_mode') + \
+ files_in(dir, 'onionshare_gui/receive_mode') + \
+ files_in(dir, 'install/scripts') + \
+ files_in(dir, 'tests')
pysrc = [p for p in src if p.endswith('.py')]
lang_code = args.lang_code
@@ -64,11 +69,11 @@ def main():
for line in fileinput.input(pysrc, openhook=fileinput.hook_encoded('utf-8')):
# search `strings._('translate_key')`
# `strings._('translate_key', True)`
- m = re.search(r'strings\._\((.*?)\)', line)
+ m = re.findall(r'strings\._\((.*?)\)', line)
if m:
- arg = m.group(1)
- key = arg.split(',')[0].strip('''"' ''')
- translate_keys.add(key)
+ for match in m:
+ key = match.split(',')[0].strip('''"' ''')
+ translate_keys.add(key)
if args.show_all_keys:
for k in sorted(translate_keys):
diff --git a/install/get-tor-osx.py b/install/get-tor-osx.py
index 3c498dfe..ae20fd74 100644
--- a/install/get-tor-osx.py
+++ b/install/get-tor-osx.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -35,14 +35,14 @@ import subprocess
import requests
def main():
- dmg_url = 'https://archive.torproject.org/tor-package-archive/torbrowser/7.5.5/TorBrowser-7.5.5-osx64_en-US.dmg'
- dmg_filename = 'TorBrowser-7.5.5-osx64_en-US.dmg'
- expected_dmg_sha256 = '2b445e4237cdd9be0e71e65f76db5d36f0d6c37532982d642803b57e388e4636'
+ dmg_url = 'https://archive.torproject.org/tor-package-archive/torbrowser/8.0.1/TorBrowser-8.0.1-osx64_en-US.dmg'
+ dmg_filename = 'TorBrowser-8.0.1-osx64_en-US.dmg'
+ expected_dmg_sha256 = 'fb1be2a0f850a65bae38747c3abbf9061742c5d7799e1693405078aaf38d2b08'
# Build paths
root_path = os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
working_path = os.path.join(root_path, 'build', 'tor')
- dmg_tor_path = os.path.join('/Volumes', 'Tor Browser', 'TorBrowser.app', 'Contents')
+ dmg_tor_path = os.path.join('/Volumes', 'Tor Browser', 'Tor Browser.app', 'Contents')
dmg_path = os.path.join(working_path, dmg_filename)
dist_path = os.path.join(root_path, 'dist', 'OnionShare.app', 'Contents')
@@ -88,7 +88,7 @@ def main():
shutil.copyfile(os.path.join(dmg_tor_path, 'Resources', 'TorBrowser', 'Tor', 'geoip6'), os.path.join(dist_path, 'Resources', 'Tor', 'geoip6'))
os.chmod(os.path.join(dist_path, 'Resources', 'Tor', 'tor'), 0o755)
shutil.copyfile(os.path.join(dmg_tor_path, 'MacOS', 'Tor', 'tor.real'), os.path.join(dist_path, 'MacOS', 'Tor', 'tor.real'))
- shutil.copyfile(os.path.join(dmg_tor_path, 'MacOS', 'Tor', 'libevent-2.0.5.dylib'), os.path.join(dist_path, 'MacOS', 'Tor', 'libevent-2.0.5.dylib'))
+ shutil.copyfile(os.path.join(dmg_tor_path, 'MacOS', 'Tor', 'libevent-2.1.6.dylib'), os.path.join(dist_path, 'MacOS', 'Tor', 'libevent-2.1.6.dylib'))
os.chmod(os.path.join(dist_path, 'MacOS', 'Tor', 'tor.real'), 0o755)
# obfs4proxy binary
shutil.copyfile(os.path.join(dmg_tor_path, 'MacOS', 'Tor', 'PluggableTransports', 'obfs4proxy'), os.path.join(dist_path, 'Resources', 'Tor', 'obfs4proxy'))
diff --git a/install/get-tor-windows.py b/install/get-tor-windows.py
index 44c4ac23..e5a24be9 100644
--- a/install/get-tor-windows.py
+++ b/install/get-tor-windows.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -33,9 +33,9 @@ import subprocess
import requests
def main():
- exe_url = 'https://archive.torproject.org/tor-package-archive/torbrowser/7.5.5/torbrowser-install-7.5.5_en-US.exe'
- exe_filename = 'torbrowser-install-7.5.5_en-US.exe'
- expected_exe_sha256 = '992f9a6658001c3419ed3695a908eef4fb7feb1cd549389bdacbadb7f8cb08a7'
+ exe_url = 'https://archive.torproject.org/tor-package-archive/torbrowser/8.0.1/torbrowser-install-8.0.1_en-US.exe'
+ exe_filename = 'torbrowser-install-8.0.1_en-US.exe'
+ expected_exe_sha256 = 'bdf81d4282b991a6425c213c7b03b3f5c1f17bb02986b7fe9a1891e577e51639'
# Build paths
root_path = os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
working_path = os.path.join(os.path.join(root_path, 'build'), 'tor')
diff --git a/install/licenses/license-onionshare.txt b/install/licenses/license-onionshare.txt
index dc049cff..77d05583 100644
--- a/install/licenses/license-onionshare.txt
+++ b/install/licenses/license-onionshare.txt
@@ -1,5 +1,4 @@
-OnionShare
-Copyright © 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
diff --git a/install/onionshare.desktop b/install/onionshare.desktop
index fbac3660..3a55e498 100644
--- a/install/onionshare.desktop
+++ b/install/onionshare.desktop
@@ -1,11 +1,14 @@
[Desktop Entry]
Name=OnionShare
+GenericName=OnionShare Client
Comment=Share a file securely and anonymously over Tor
Comment[da]=Del en fil sikkert og anonymt over Tor
+Comment[de]=Teile Dateien sicher und anonym über das Tor-Netzwerk
Exec=/usr/bin/onionshare-gui
Terminal=false
Type=Application
Icon=/usr/share/pixmaps/onionshare80.xpm
-Categories=Network;
+Categories=Network;FileTransfer;
Keywords=tor;anonymity;privacy;onion service;file sharing;file hosting;
Keywords[da]=tor;anonymitet;privatliv;onion-tjeneste;fildeling;filhosting;
+Keywords[de]=tor;Anonymität;Privatsphäre;Onion-Service;File-Sharing;File-Hosting;
diff --git a/install/onionshare.nsi b/install/onionshare.nsi
index 279f4803..f0b28535 100644
--- a/install/onionshare.nsi
+++ b/install/onionshare.nsi
@@ -59,202 +59,7 @@ FunctionEnd
Section "install"
SetOutPath "$INSTDIR"
File "onionshare.ico"
- File "${BINPATH}\api-ms-win-core-console-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-datetime-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-debug-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-errorhandling-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-file-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-file-l1-2-0.dll"
- File "${BINPATH}\api-ms-win-core-file-l2-1-0.dll"
- File "${BINPATH}\api-ms-win-core-handle-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-heap-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-interlocked-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-libraryloader-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-localization-l1-2-0.dll"
- File "${BINPATH}\api-ms-win-core-memory-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-namedpipe-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-processenvironment-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-processthreads-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-processthreads-l1-1-1.dll"
- File "${BINPATH}\api-ms-win-core-profile-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-rtlsupport-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-string-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-synch-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-synch-l1-2-0.dll"
- File "${BINPATH}\api-ms-win-core-sysinfo-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-timezone-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-core-util-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-conio-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-convert-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-environment-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-filesystem-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-heap-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-locale-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-math-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-multibyte-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-process-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-runtime-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-stdio-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-string-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-time-l1-1-0.dll"
- File "${BINPATH}\api-ms-win-crt-utility-l1-1-0.dll"
- File "${BINPATH}\base_library.zip"
- File "${BINPATH}\mfc140u.dll"
- File "${BINPATH}\MSVCP140.dll"
- File "${BINPATH}\onionshare-gui.exe"
- File "${BINPATH}\onionshare-gui.exe.manifest"
- File "${BINPATH}\pyexpat.pyd"
- File "${BINPATH}\PyQt5.Qt.pyd"
- File "${BINPATH}\PyQt5.QtCore.pyd"
- File "${BINPATH}\PyQt5.QtGui.pyd"
- File "${BINPATH}\PyQt5.QtPrintSupport.pyd"
- File "${BINPATH}\PyQt5.QtWidgets.pyd"
- File "${BINPATH}\python3.dll"
- File "${BINPATH}\python36.dll"
- File "${BINPATH}\pythoncom36.dll"
- File "${BINPATH}\pywintypes36.dll"
- File "${BINPATH}\Qt5Core.dll"
- File "${BINPATH}\Qt5Gui.dll"
- File "${BINPATH}\Qt5PrintSupport.dll"
- File "${BINPATH}\Qt5Svg.dll"
- File "${BINPATH}\Qt5Widgets.dll"
- File "${BINPATH}\select.pyd"
- File "${BINPATH}\sip.pyd"
- File "${BINPATH}\ucrtbase.dll"
- File "${BINPATH}\unicodedata.pyd"
- File "${BINPATH}\VCRUNTIME140.dll"
- File "${BINPATH}\win32api.pyd"
- File "${BINPATH}\win32com.shell.shell.pyd"
- File "${BINPATH}\win32trace.pyd"
- File "${BINPATH}\win32ui.pyd"
- File "${BINPATH}\win32wnet.pyd"
- File "${BINPATH}\_asyncio.pyd"
- File "${BINPATH}\_bz2.pyd"
- File "${BINPATH}\_ctypes.pyd"
- File "${BINPATH}\_decimal.pyd"
- File "${BINPATH}\_hashlib.pyd"
- File "${BINPATH}\_lzma.pyd"
- File "${BINPATH}\_multiprocessing.pyd"
- File "${BINPATH}\_overlapped.pyd"
- File "${BINPATH}\_socket.pyd"
- File "${BINPATH}\_ssl.pyd"
- File "${BINPATH}\_win32sysloader.pyd"
-
- SetOutPath "$INSTDIR\Include"
- File "${BINPATH}\Include\pyconfig.h"
-
- SetOutPath "$INSTDIR\lib2to3"
- File "${BINPATH}\lib2to3\Grammar.txt"
- File "${BINPATH}\lib2to3\Grammar3.6.2.candidate.2.pickle"
- File "${BINPATH}\lib2to3\Grammar3.6.2.final.0.pickle"
- File "${BINPATH}\lib2to3\Grammar3.6.3.candidate.1.pickle"
- File "${BINPATH}\lib2to3\Grammar3.6.3.final.0.pickle"
- File "${BINPATH}\lib2to3\Grammar3.6.4.candidate.1.pickle"
- File "${BINPATH}\lib2to3\Grammar3.6.4.final.0.pickle"
- File "${BINPATH}\lib2to3\PatternGrammar.txt"
- File "${BINPATH}\lib2to3\PatternGrammar3.6.2.candidate.2.pickle"
- File "${BINPATH}\lib2to3\PatternGrammar3.6.2.final.0.pickle"
- File "${BINPATH}\lib2to3\PatternGrammar3.6.3.candidate.1.pickle"
- File "${BINPATH}\lib2to3\PatternGrammar3.6.3.final.0.pickle"
- File "${BINPATH}\lib2to3\PatternGrammar3.6.4.candidate.1.pickle"
- File "${BINPATH}\lib2to3\PatternGrammar3.6.4.final.0.pickle"
-
- SetOutPath "$INSTDIR\lib2to3\tests\data"
- File "${BINPATH}\lib2to3\tests\data\README"
-
- SetOutPath "$INSTDIR\licenses"
- File "${BINPATH}\licenses\license-obfs4.txt"
- File "${BINPATH}\licenses\license-onionshare.txt"
- File "${BINPATH}\licenses\license-tor.txt"
- File "${BINPATH}\licenses\readme.txt"
-
- SetOutPath "$INSTDIR\PyQt5\Qt\bin"
- File "${BINPATH}\PyQt5\Qt\bin\qt.conf"
-
- SetOutPath "$INSTDIR\PyQt5\Qt\plugins\iconengines"
- File "${BINPATH}\PyQt5\Qt\plugins\iconengines\qsvgicon.dll"
-
- SetOutPath "$INSTDIR\PyQt5\Qt\plugins\imageformats"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qgif.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qicns.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qico.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qjpeg.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qsvg.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qtga.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qtiff.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qwbmp.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\imageformats\qwebp.dll"
-
- SetOutPath "$INSTDIR\PyQt5\Qt\plugins\platforms"
- File "${BINPATH}\PyQt5\Qt\plugins\platforms\qminimal.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\platforms\qoffscreen.dll"
- File "${BINPATH}\PyQt5\Qt\plugins\platforms\qwindows.dll"
-
- SetOutPath "$INSTDIR\PyQt5\Qt\plugins\printsupport"
- File "${BINPATH}\PyQt5\Qt\plugins\printsupport\windowsprintersupport.dll"
-
- SetOutPath "$INSTDIR\share"
- File "${BINPATH}\share\torrc_template"
- File "${BINPATH}\share\torrc_template-windows"
- File "${BINPATH}\share\torrc_template-obfs4"
- File "${BINPATH}\share\torrc_template-meek_lite_amazon"
- File "${BINPATH}\share\torrc_template-meek_lite_azure"
- File "${BINPATH}\share\version.txt"
- File "${BINPATH}\share\wordlist.txt"
-
- SetOutPath "$INSTDIR\share\html"
- File "${BINPATH}\share\html\404.html"
- File "${BINPATH}\share\html\denied.html"
- File "${BINPATH}\share\html\index.html"
-
- SetOutPath "$INSTDIR\share\images"
- File "${BINPATH}\share\images\download_completed.png"
- File "${BINPATH}\share\images\download_completed_none.png"
- File "${BINPATH}\share\images\download_in_progress.png"
- File "${BINPATH}\share\images\download_in_progress_none.png"
- File "${BINPATH}\share\images\favicon.ico"
- File "${BINPATH}\share\images\file_delete.png"
- File "${BINPATH}\share\images\info.png"
- File "${BINPATH}\share\images\logo.png"
- File "${BINPATH}\share\images\logo_transparent.png"
- File "${BINPATH}\share\images\logo_grayscale.png"
- File "${BINPATH}\share\images\server_started.png"
- File "${BINPATH}\share\images\server_stopped.png"
- File "${BINPATH}\share\images\server_working.png"
- File "${BINPATH}\share\images\settings.png"
- File "${BINPATH}\share\images\web_file.png"
- File "${BINPATH}\share\images\web_folder.png"
-
- SetOutPath "$INSTDIR\share\locale"
- File "${BINPATH}\share\locale\cs.json"
- File "${BINPATH}\share\locale\de.json"
- File "${BINPATH}\share\locale\en.json"
- File "${BINPATH}\share\locale\eo.json"
- File "${BINPATH}\share\locale\es.json"
- File "${BINPATH}\share\locale\fi.json"
- File "${BINPATH}\share\locale\fr.json"
- File "${BINPATH}\share\locale\it.json"
- File "${BINPATH}\share\locale\nl.json"
- File "${BINPATH}\share\locale\no.json"
- File "${BINPATH}\share\locale\pt.json"
- File "${BINPATH}\share\locale\ru.json"
- File "${BINPATH}\share\locale\tr.json"
-
- SetOutPath "$INSTDIR\tor\Data\Tor"
- File "${BINPATH}\tor\Data\Tor\geoip"
- File "${BINPATH}\tor\Data\Tor\geoip6"
-
- SetOutPath "$INSTDIR\tor\Tor"
- File "${BINPATH}\tor\Tor\libeay32.dll"
- File "${BINPATH}\tor\Tor\libevent-2-0-5.dll"
- File "${BINPATH}\tor\Tor\libevent_core-2-0-5.dll"
- File "${BINPATH}\tor\Tor\libevent_extra-2-0-5.dll"
- File "${BINPATH}\tor\Tor\libgcc_s_sjlj-1.dll"
- File "${BINPATH}\tor\Tor\libssp-0.dll"
- File "${BINPATH}\tor\Tor\obfs4proxy.exe"
- File "${BINPATH}\tor\Tor\ssleay32.dll"
- File "${BINPATH}\tor\Tor\tor.exe"
- File "${BINPATH}\tor\Tor\zlib1.dll"
+ File /a /r "${BINPATH}\"
# uninstaller
!ifndef INNER
@@ -298,200 +103,7 @@ FunctionEnd
Delete "$SMPROGRAMS\${APPNAME}.lnk"
# remove files
- Delete "$INSTDIR\api-ms-win-core-console-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-datetime-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-debug-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-errorhandling-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-file-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-file-l1-2-0.dll"
- Delete "$INSTDIR\api-ms-win-core-file-l2-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-handle-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-heap-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-interlocked-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-libraryloader-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-localization-l1-2-0.dll"
- Delete "$INSTDIR\api-ms-win-core-memory-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-namedpipe-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-processenvironment-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-processthreads-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-processthreads-l1-1-1.dll"
- Delete "$INSTDIR\api-ms-win-core-profile-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-rtlsupport-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-string-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-synch-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-synch-l1-2-0.dll"
- Delete "$INSTDIR\api-ms-win-core-sysinfo-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-timezone-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-core-util-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-conio-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-convert-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-environment-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-filesystem-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-heap-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-locale-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-math-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-multibyte-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-process-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-runtime-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-stdio-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-string-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-time-l1-1-0.dll"
- Delete "$INSTDIR\api-ms-win-crt-utility-l1-1-0.dll"
- Delete "$INSTDIR\base_library.zip"
- Delete "$INSTDIR\Include\pyconfig.h"
- Delete "$INSTDIR\lib2to3\Grammar.txt"
- Delete "$INSTDIR\lib2to3\Grammar3.6.2.candidate.2.pickle"
- Delete "$INSTDIR\lib2to3\Grammar3.6.2.final.0.pickle"
- Delete "$INSTDIR\lib2to3\Grammar3.6.3.candidate.1.pickle"
- Delete "$INSTDIR\lib2to3\Grammar3.6.3.final.0.pickle"
- Delete "$INSTDIR\lib2to3\Grammar3.6.4.candidate.1.pickle"
- Delete "$INSTDIR\lib2to3\Grammar3.6.4.final.0.pickle"
- Delete "$INSTDIR\lib2to3\PatternGrammar.txt"
- Delete "$INSTDIR\lib2to3\PatternGrammar3.6.2.candidate.2.pickle"
- Delete "$INSTDIR\lib2to3\PatternGrammar3.6.2.final.0.pickle"
- Delete "$INSTDIR\lib2to3\PatternGrammar3.6.3.candidate.1.pickle"
- Delete "$INSTDIR\lib2to3\PatternGrammar3.6.3.final.0.pickle"
- Delete "$INSTDIR\lib2to3\PatternGrammar3.6.4.candidate.1.pickle"
- Delete "$INSTDIR\lib2to3\PatternGrammar3.6.4.final.0.pickle"
- Delete "$INSTDIR\lib2to3\tests"
- Delete "$INSTDIR\lib2to3\tests\data"
- Delete "$INSTDIR\lib2to3\tests\data\README"
- Delete "$INSTDIR\licenses\license-obfs4.txt"
- Delete "$INSTDIR\licenses\license-onionshare.txt"
- Delete "$INSTDIR\licenses\license-tor.txt"
- Delete "$INSTDIR\licenses\readme.txt"
- Delete "$INSTDIR\mfc140u.dll"
- Delete "$INSTDIR\MSVCP140.dll"
- Delete "$INSTDIR\onionshare-gui.exe"
- Delete "$INSTDIR\onionshare-gui.exe.manifest"
- Delete "$INSTDIR\pyexpat.pyd"
- Delete "$INSTDIR\PyQt5\Qt\bin\qt.conf"
- Delete "$INSTDIR\PyQt5\Qt\plugins\iconengines\qsvgicon.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qgif.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qicns.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qico.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qjpeg.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qsvg.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qtga.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qtiff.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qwbmp.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\imageformats\qwebp.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\platforms\qminimal.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\platforms\qoffscreen.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\platforms\qwindows.dll"
- Delete "$INSTDIR\PyQt5\Qt\plugins\printsupport\windowsprintersupport.dll"
- Delete "$INSTDIR\PyQt5.Qt.pyd"
- Delete "$INSTDIR\PyQt5.QtCore.pyd"
- Delete "$INSTDIR\PyQt5.QtGui.pyd"
- Delete "$INSTDIR\PyQt5.QtPrintSupport.pyd"
- Delete "$INSTDIR\PyQt5.QtWidgets.pyd"
- Delete "$INSTDIR\python3.dll"
- Delete "$INSTDIR\python36.dll"
- Delete "$INSTDIR\pythoncom36.dll"
- Delete "$INSTDIR\pywintypes36.dll"
- Delete "$INSTDIR\Qt5Core.dll"
- Delete "$INSTDIR\Qt5Gui.dll"
- Delete "$INSTDIR\Qt5PrintSupport.dll"
- Delete "$INSTDIR\Qt5Svg.dll"
- Delete "$INSTDIR\Qt5Widgets.dll"
- Delete "$INSTDIR\select.pyd"
- Delete "$INSTDIR\share\html\404.html"
- Delete "$INSTDIR\share\html\denied.html"
- Delete "$INSTDIR\share\html\index.html"
- Delete "$INSTDIR\share\images\download_completed.png"
- Delete "$INSTDIR\share\images\download_completed_none.png"
- Delete "$INSTDIR\share\images\download_in_progress.png"
- Delete "$INSTDIR\share\images\download_in_progress_none.png"
- Delete "$INSTDIR\share\images\favicon.ico"
- Delete "$INSTDIR\share\images\file_delete.png"
- Delete "$INSTDIR\share\images\info.png"
- Delete "$INSTDIR\share\images\logo.png"
- Delete "$INSTDIR\share\images\logo_transparent.png"
- Delete "$INSTDIR\share\images\logo_grayscale.png"
- Delete "$INSTDIR\share\images\server_started.png"
- Delete "$INSTDIR\share\images\server_stopped.png"
- Delete "$INSTDIR\share\images\server_working.png"
- Delete "$INSTDIR\share\images\settings.png"
- Delete "$INSTDIR\share\images\web_file.png"
- Delete "$INSTDIR\share\images\web_folder.png"
- Delete "$INSTDIR\share\locale\cs.json"
- Delete "$INSTDIR\share\locale\de.json"
- Delete "$INSTDIR\share\locale\en.json"
- Delete "$INSTDIR\share\locale\eo.json"
- Delete "$INSTDIR\share\locale\es.json"
- Delete "$INSTDIR\share\locale\fi.json"
- Delete "$INSTDIR\share\locale\fr.json"
- Delete "$INSTDIR\share\locale\it.json"
- Delete "$INSTDIR\share\locale\nl.json"
- Delete "$INSTDIR\share\locale\no.json"
- Delete "$INSTDIR\share\locale\pt.json"
- Delete "$INSTDIR\share\locale\ru.json"
- Delete "$INSTDIR\share\locale\tr.json"
- Delete "$INSTDIR\share\torrc_template"
- Delete "$INSTDIR\share\torrc_template-windows"
- Delete "$INSTDIR\share\torrc_template-obfs4"
- Delete "$INSTDIR\share\torrc_template-meek_lite_amazon"
- Delete "$INSTDIR\share\torrc_template-meek_lite_azure"
- Delete "$INSTDIR\share\version.txt"
- Delete "$INSTDIR\share\wordlist.txt"
- Delete "$INSTDIR\sip.pyd"
- Delete "$INSTDIR\tor\Data\Tor\geoip"
- Delete "$INSTDIR\tor\Data\Tor\geoip6"
- Delete "$INSTDIR\tor\Tor\libeay32.dll"
- Delete "$INSTDIR\tor\Tor\libevent-2-0-5.dll"
- Delete "$INSTDIR\tor\Tor\libevent_core-2-0-5.dll"
- Delete "$INSTDIR\tor\Tor\libevent_extra-2-0-5.dll"
- Delete "$INSTDIR\tor\Tor\libgcc_s_sjlj-1.dll"
- Delete "$INSTDIR\tor\Tor\libssp-0.dll"
- Delete "$INSTDIR\tor\Tor\obfs4proxy.exe"
- Delete "$INSTDIR\tor\Tor\ssleay32.dll"
- Delete "$INSTDIR\tor\Tor\tor.exe"
- Delete "$INSTDIR\tor\Tor\zlib1.dll"
- Delete "$INSTDIR\ucrtbase.dll"
- Delete "$INSTDIR\unicodedata.pyd"
- Delete "$INSTDIR\VCRUNTIME140.dll"
- Delete "$INSTDIR\win32api.pyd"
- Delete "$INSTDIR\win32com.shell.shell.pyd"
- Delete "$INSTDIR\win32trace.pyd"
- Delete "$INSTDIR\win32ui.pyd"
- Delete "$INSTDIR\win32wnet.pyd"
- Delete "$INSTDIR\_asyncio.pyd"
- Delete "$INSTDIR\_bz2.pyd"
- Delete "$INSTDIR\_ctypes.pyd"
- Delete "$INSTDIR\_decimal.pyd"
- Delete "$INSTDIR\_hashlib.pyd"
- Delete "$INSTDIR\_lzma.pyd"
- Delete "$INSTDIR\_multiprocessing.pyd"
- Delete "$INSTDIR\_overlapped.pyd"
- Delete "$INSTDIR\_socket.pyd"
- Delete "$INSTDIR\_ssl.pyd"
- Delete "$INSTDIR\_win32sysloader.pyd"
-
- Delete "$INSTDIR\onionshare.ico"
- Delete "$INSTDIR\uninstall.exe"
-
- rmDir "$INSTDIR\Include"
- rmDir "$INSTDIR\lib2to3\tests\data"
- rmDir "$INSTDIR\lib2to3\tests"
- rmDir "$INSTDIR\lib2to3"
- rmDir "$INSTDIR\licenses"
- rmDir "$INSTDIR\PyQt5\Qt\bin"
- rmDir "$INSTDIR\PyQt5\Qt\plugins\iconengines"
- rmDir "$INSTDIR\PyQt5\Qt\plugins\imageformats"
- rmDir "$INSTDIR\PyQt5\Qt\plugins\platforms"
- rmDir "$INSTDIR\PyQt5\Qt\plugins\printsupport"
- rmDir "$INSTDIR\PyQt5\Qt\plugins"
- rmDir "$INSTDIR\PyQt5\Qt"
- rmDir "$INSTDIR\PyQt5"
- rmDir "$INSTDIR\share\html"
- rmDir "$INSTDIR\share\images"
- rmDir "$INSTDIR\share\locale"
- rmDir "$INSTDIR\share"
- rmDir "$INSTDIR\tor\Data\Tor"
- rmDir "$INSTDIR\tor\Data"
- rmDir "$INSTDIR\tor\Tor"
- rmDir "$INSTDIR\tor"
- rmDir "$INSTDIR"
+ RMDir /r $INSTDIR
# remove uninstaller information from the registry
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APPNAME}"
diff --git a/install/pyinstaller.spec b/install/pyinstaller.spec
index 9c233cf4..6811997b 100644
--- a/install/pyinstaller.spec
+++ b/install/pyinstaller.spec
@@ -14,12 +14,15 @@ a = Analysis(
('../share/wordlist.txt', 'share'),
('../share/torrc_template', 'share'),
('../share/torrc_template-obfs4', 'share'),
- ('../share/torrc_template-meek_lite_amazon', 'share'),
('../share/torrc_template-meek_lite_azure', 'share'),
('../share/torrc_template-windows', 'share'),
('../share/images/*', 'share/images'),
('../share/locale/*', 'share/locale'),
- ('../share/html/*', 'share/html'),
+ ('../share/static/*', 'share/static'),
+ ('../share/templates/*', 'share/templates'),
+ ('../share/static/css/*', 'share/static/css'),
+ ('../share/static/img/*', 'share/static/img'),
+ ('../share/static/js/*', 'share/static/js'),
('../install/licenses/*', 'licenses')
],
hiddenimports=[],
diff --git a/install/requirements-tests.txt b/install/requirements-tests.txt
new file mode 100644
index 00000000..89f37572
--- /dev/null
+++ b/install/requirements-tests.txt
@@ -0,0 +1,10 @@
+atomicwrites==1.2.1
+attrs==18.2.0
+more-itertools==4.3.0
+pluggy==0.8.0
+py==1.7.0
+pytest==4.0.1
+pytest-faulthandler==1.5.0
+pytest-qt==3.2.1
+six==1.11.0
+urllib3==1.24.1
diff --git a/install/requirements-windows.txt b/install/requirements-windows.txt
deleted file mode 100644
index 6e03f6e8..00000000
--- a/install/requirements-windows.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-click==6.7
-Flask==0.12.2
-future==0.16.0
-itsdangerous==0.24
-Jinja2==2.10
-MarkupSafe==1.0
-pefile==2017.11.5
-PyInstaller==3.3.1
-PyQt5==5.9.2
-PySocks==1.6.7
-requests==2.19.1
-sip==4.19.6
-stem==1.6.0
-Werkzeug==0.14.1
diff --git a/install/requirements.txt b/install/requirements.txt
index ed83b995..81430398 100644
--- a/install/requirements.txt
+++ b/install/requirements.txt
@@ -1,12 +1,26 @@
-click==6.7
-Flask==0.12.2
-itsdangerous==0.24
+altgraph==0.16.1
+asn1crypto==0.24.0
+certifi==2018.10.15
+cffi==1.11.5
+chardet==3.0.4
+Click==7.0
+cryptography==2.4.2
+Flask==1.0.2
+future==0.17.1
+idna==2.7
+itsdangerous==1.1.0
Jinja2==2.10
-MarkupSafe==1.0
-PyInstaller==3.3.1
-PyQt5==5.9.2
-PySocks==1.6.7
-requests==2.19.1
-sip==4.19.6
-stem==1.6.0
+macholib==1.11
+MarkupSafe==1.1.0
+pefile==2018.8.8
+pycparser==2.19
+pycryptodome==3.7.2
+PyInstaller==3.4
+PyQt5==5.11.3
+PyQt5-sip==4.19.13
+PySocks==1.6.8
+requests==2.20.1
+six==1.11.0
+stem==1.7.0
+urllib3==1.24.1
Werkzeug==0.14.1
diff --git a/install/scripts/onionshare b/install/scripts/onionshare
index 6c560aec..e2205e04 100755
--- a/install/scripts/onionshare
+++ b/install/scripts/onionshare
@@ -3,7 +3,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
diff --git a/install/scripts/onionshare-gui b/install/scripts/onionshare-gui
index 6b9fb21b..fed29d83 100755
--- a/install/scripts/onionshare-gui
+++ b/install/scripts/onionshare-gui
@@ -3,7 +3,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
diff --git a/install/scripts/onionshare-pyinstaller b/install/scripts/onionshare-pyinstaller
index d026e1bf..bd59b421 100644
--- a/install/scripts/onionshare-pyinstaller
+++ b/install/scripts/onionshare-pyinstaller
@@ -3,7 +3,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
diff --git a/onionshare/__init__.py b/onionshare/__init__.py
index 032b4acc..0d064639 100644
--- a/onionshare/__init__.py
+++ b/onionshare/__init__.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -20,21 +20,32 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import os, sys, time, argparse, threading
-from . import strings, common, web
+from . import strings
+from .common import Common
+from .web import Web
from .onion import *
from .onionshare import OnionShare
-from .settings import Settings
def main(cwd=None):
"""
The main() function implements all of the logic that the command-line version of
onionshare uses.
"""
+ common = Common()
+
+ # Load the default settings and strings early, for the sake of being able to parse options.
+ # These won't be in the user's chosen locale necessarily, but we need to parse them
+ # early in order to even display the option to pass alternate settings (which might
+ # contain a preferred locale).
+ # If an alternate --config is passed, we'll reload strings later.
+ common.load_settings()
strings.load_strings(common)
- print(strings._('version_string').format(common.get_version()))
+
+ # Display OnionShare banner
+ print(strings._('version_string').format(common.version))
# OnionShare CLI in OSX needs to change current working directory (#132)
- if common.get_platform() == 'Darwin':
+ if common.platform == 'Darwin':
if cwd:
os.chdir(cwd)
@@ -44,9 +55,10 @@ def main(cwd=None):
parser.add_argument('--stay-open', action='store_true', dest='stay_open', help=strings._("help_stay_open"))
parser.add_argument('--shutdown-timeout', metavar='<int>', dest='shutdown_timeout', default=0, help=strings._("help_shutdown_timeout"))
parser.add_argument('--stealth', action='store_true', dest='stealth', help=strings._("help_stealth"))
- parser.add_argument('--debug', action='store_true', dest='debug', help=strings._("help_debug"))
+ parser.add_argument('--receive', action='store_true', dest='receive', help=strings._("help_receive"))
parser.add_argument('--config', metavar='config', default=False, help=strings._('help_config'))
- parser.add_argument('filename', metavar='filename', nargs='+', help=strings._('help_filename'))
+ parser.add_argument('--debug', action='store_true', dest='debug', help=strings._("help_debug"))
+ parser.add_argument('filename', metavar='filename', nargs='*', help=strings._('help_filename'))
args = parser.parse_args()
filenames = args.filename
@@ -58,65 +70,86 @@ def main(cwd=None):
stay_open = bool(args.stay_open)
shutdown_timeout = int(args.shutdown_timeout)
stealth = bool(args.stealth)
+ receive = bool(args.receive)
config = args.config
- # Debug mode?
- if debug:
- common.set_debug(debug)
- web.debug_mode()
-
- # Validation
- valid = True
- for filename in filenames:
- if not os.path.isfile(filename) and not os.path.isdir(filename):
- print(strings._("not_a_file").format(filename))
- valid = False
- if not os.access(filename, os.R_OK):
- print(strings._("not_a_readable_file").format(filename))
- valid = False
- if not valid:
+ if receive:
+ mode = 'receive'
+ else:
+ mode = 'share'
+
+ # Make sure filenames given if not using receiver mode
+ if mode == 'share' and len(filenames) == 0:
+ parser.print_help()
sys.exit()
+ # Validate filenames
+ if mode == 'share':
+ valid = True
+ for filename in filenames:
+ if not os.path.isfile(filename) and not os.path.isdir(filename):
+ print(strings._("not_a_file").format(filename))
+ valid = False
+ if not os.access(filename, os.R_OK):
+ print(strings._("not_a_readable_file").format(filename))
+ valid = False
+ if not valid:
+ sys.exit()
+
+ # Re-load settings, if a custom config was passed in
+ if config:
+ common.load_settings(config)
+ # Re-load the strings, in case the provided config has changed locale
+ strings.load_strings(common)
- settings = Settings(config)
+ # Debug mode?
+ common.debug = debug
+
+ # Create the Web object
+ web = Web(common, False, mode)
# Start the Onion object
- onion = Onion()
+ onion = Onion(common)
try:
- onion.connect(settings=False, config=config)
- except (TorTooOld, TorErrorInvalidSetting, TorErrorAutomatic, TorErrorSocketPort, TorErrorSocketFile, TorErrorMissingPassword, TorErrorUnreadableCookieFile, TorErrorAuthError, TorErrorProtocolError, BundledTorNotSupported, BundledTorTimeout) as e:
- sys.exit(e.args[0])
+ onion.connect(custom_settings=False, config=config)
except KeyboardInterrupt:
print("")
sys.exit()
+ except Exception as e:
+ sys.exit(e.args[0])
# Start the onionshare app
try:
- app = OnionShare(onion, local_only, stay_open, shutdown_timeout)
+ app = OnionShare(common, onion, local_only, shutdown_timeout)
app.set_stealth(stealth)
+ app.choose_port()
app.start_onion_service()
except KeyboardInterrupt:
print("")
sys.exit()
+ except (TorTooOld, TorErrorProtocolError) as e:
+ print("")
+ print(e.args[0])
+ sys.exit()
- # Prepare files to share
- print(strings._("preparing_files"))
- try:
- web.set_file_info(filenames)
- app.cleanup_filenames.append(web.zip_filename)
- except OSError as e:
- print(e.strerror)
- sys.exit(1)
-
- # Warn about sending large files over Tor
- if web.zip_filesize >= 157286400: # 150mb
- print('')
- print(strings._("large_filesize"))
- print('')
+ if mode == 'share':
+ # Prepare files to share
+ print(strings._("preparing_files"))
+ try:
+ web.share_mode.set_file_info(filenames)
+ app.cleanup_filenames += web.share_mode.cleanup_filenames
+ except OSError as e:
+ print(e.strerror)
+ sys.exit(1)
+
+ # Warn about sending large files over Tor
+ if web.share_mode.download_filesize >= 157286400: # 150mb
+ print('')
+ print(strings._("large_filesize"))
+ print('')
# Start OnionShare http service in new thread
- settings.load()
- t = threading.Thread(target=web.start, args=(app.port, app.stay_open, settings.get('slug')))
+ t = threading.Thread(target=web.start, args=(app.port, stay_open, common.settings.get('public_mode'), common.settings.get('slug')))
t.daemon = True
t.start()
@@ -129,18 +162,39 @@ def main(cwd=None):
app.shutdown_timer.start()
# Save the web slug if we are using a persistent private key
- if settings.get('save_private_key'):
- if not settings.get('slug'):
- settings.set('slug', web.slug)
- settings.save()
-
- if(stealth):
- print(strings._("give_this_url_stealth"))
- print('http://{0:s}/{1:s}'.format(app.onion_host, web.slug))
- print(app.auth_string)
+ if common.settings.get('save_private_key'):
+ if not common.settings.get('slug'):
+ common.settings.set('slug', web.slug)
+ common.settings.save()
+
+ # Build the URL
+ if common.settings.get('public_mode'):
+ url = 'http://{0:s}'.format(app.onion_host)
+ else:
+ url = 'http://{0:s}/{1:s}'.format(app.onion_host, web.slug)
+
+ print('')
+ if mode == 'receive':
+ print(strings._('receive_mode_downloads_dir').format(common.settings.get('downloads_dir')))
+ print('')
+ print(strings._('receive_mode_warning'))
+ print('')
+
+ if stealth:
+ print(strings._("give_this_url_receive_stealth"))
+ print(url)
+ print(app.auth_string)
+ else:
+ print(strings._("give_this_url_receive"))
+ print(url)
else:
- print(strings._("give_this_url"))
- print('http://{0:s}/{1:s}'.format(app.onion_host, web.slug))
+ if stealth:
+ print(strings._("give_this_url_stealth"))
+ print(url)
+ print(app.auth_string)
+ else:
+ print(strings._("give_this_url"))
+ print(url)
print('')
print(strings._("ctrlc_to_stop"))
@@ -149,11 +203,19 @@ def main(cwd=None):
if app.shutdown_timeout > 0:
# if the shutdown timer was set and has run out, stop the server
if not app.shutdown_timer.is_alive():
- # If there were no attempts to download the share, or all downloads are done, we can stop
- if web.download_count == 0 or web.done:
- print(strings._("close_on_timeout"))
- web.stop(app.port)
- break
+ if mode == 'share':
+ # If there were no attempts to download the share, or all downloads are done, we can stop
+ if web.share_mode.download_count == 0 or web.done:
+ print(strings._("close_on_timeout"))
+ web.stop(app.port)
+ break
+ if mode == 'receive':
+ if web.receive_mode.upload_count == 0 or not web.receive_mode.uploads_in_progress:
+ print(strings._("close_on_timeout"))
+ web.stop(app.port)
+ break
+ else:
+ web.receive_mode.can_upload = False
# Allow KeyboardInterrupt exception to be handled with threads
# https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception
time.sleep(0.2)
diff --git a/onionshare/common.py b/onionshare/common.py
index ca6c667d..ffa6529f 100644
--- a/onionshare/common.py
+++ b/onionshare/common.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -28,262 +28,451 @@ import sys
import tempfile
import threading
import time
-import zipfile
-debug = False
+from .settings import Settings
-def log(module, func, msg=None):
+class Common(object):
"""
- If debug mode is on, log error messages to stdout
+ The Common object is shared amongst all parts of OnionShare.
"""
- global debug
- if debug:
- timestamp = time.strftime("%b %d %Y %X")
+ def __init__(self, debug=False):
+ self.debug = debug
- final_msg = "[{}] {}.{}".format(timestamp, module, func)
- if msg:
- final_msg = '{}: {}'.format(final_msg, msg)
- print(final_msg)
+ # The platform OnionShare is running on
+ self.platform = platform.system()
+ if self.platform.endswith('BSD'):
+ self.platform = 'BSD'
+ # The current version of OnionShare
+ with open(self.get_resource_path('version.txt')) as f:
+ self.version = f.read().strip()
-def set_debug(new_debug):
- global debug
- debug = new_debug
-
-
-def get_platform():
- """
- Returns the platform OnionShare is running on.
- """
- plat = platform.system()
- if plat.endswith('BSD'):
- plat = 'BSD'
- return plat
-
-
-def get_resource_path(filename):
- """
- Returns the absolute path of a resource, regardless of whether OnionShare is installed
- systemwide, and whether regardless of platform
- """
- p = get_platform()
-
- # On Windows, and in Windows dev mode, switch slashes in incoming filename to backslackes
- if p == 'Windows':
- filename = filename.replace('/', '\\')
-
- if getattr(sys, 'onionshare_dev_mode', False):
- # Look for resources directory relative to python file
- prefix = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))), 'share')
- if not os.path.exists(prefix):
- # While running tests during stdeb bdist_deb, look 3 directories up for the share folder
- prefix = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(prefix)))), 'share')
-
- elif p == 'BSD' or p == 'Linux':
- # Assume OnionShare is installed systemwide in Linux, since we're not running in dev mode
- prefix = os.path.join(sys.prefix, 'share/onionshare')
-
- elif getattr(sys, 'frozen', False):
- # Check if app is "frozen"
- # https://pythonhosted.org/PyInstaller/#run-time-information
- if p == 'Darwin':
- prefix = os.path.join(sys._MEIPASS, 'share')
- elif p == 'Windows':
- prefix = os.path.join(os.path.dirname(sys.executable), 'share')
-
- return os.path.join(prefix, filename)
-
-
-def get_tor_paths():
- p = get_platform()
- if p == 'Linux':
- tor_path = '/usr/bin/tor'
- tor_geo_ip_file_path = '/usr/share/tor/geoip'
- tor_geo_ipv6_file_path = '/usr/share/tor/geoip6'
- obfs4proxy_file_path = '/usr/bin/obfs4proxy'
- elif p == 'Windows':
- base_path = os.path.join(os.path.dirname(os.path.dirname(get_resource_path(''))), 'tor')
- tor_path = os.path.join(os.path.join(base_path, 'Tor'), 'tor.exe')
- obfs4proxy_file_path = os.path.join(os.path.join(base_path, 'Tor'), 'obfs4proxy.exe')
- tor_geo_ip_file_path = os.path.join(os.path.join(os.path.join(base_path, 'Data'), 'Tor'), 'geoip')
- tor_geo_ipv6_file_path = os.path.join(os.path.join(os.path.join(base_path, 'Data'), 'Tor'), 'geoip6')
- elif p == 'Darwin':
- base_path = os.path.dirname(os.path.dirname(os.path.dirname(get_resource_path(''))))
- tor_path = os.path.join(base_path, 'Resources', 'Tor', 'tor')
- tor_geo_ip_file_path = os.path.join(base_path, 'Resources', 'Tor', 'geoip')
- tor_geo_ipv6_file_path = os.path.join(base_path, 'Resources', 'Tor', 'geoip6')
- obfs4proxy_file_path = os.path.join(base_path, 'Resources', 'Tor', 'obfs4proxy')
- elif p == 'BSD':
- tor_path = '/usr/local/bin/tor'
- tor_geo_ip_file_path = '/usr/local/share/tor/geoip'
- tor_geo_ipv6_file_path = '/usr/local/share/tor/geoip6'
- obfs4proxy_file_path = '/usr/local/bin/obfs4proxy'
-
- return (tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path, obfs4proxy_file_path)
-
-
-def get_version():
- """
- Returns the version of OnionShare that is running.
- """
- with open(get_resource_path('version.txt')) as f:
- version = f.read().strip()
- return version
-
-
-def random_string(num_bytes, output_len=None):
- """
- Returns a random string with a specified number of bytes.
- """
- b = os.urandom(num_bytes)
- h = hashlib.sha256(b).digest()[:16]
- s = base64.b32encode(h).lower().replace(b'=', b'').decode('utf-8')
- if not output_len:
- return s
- return s[:output_len]
-
-
-def build_slug():
- """
- Returns a random string made from two words from the wordlist, such as "deter-trig".
- """
- with open(get_resource_path('wordlist.txt')) as f:
- wordlist = f.read().split()
+ def load_settings(self, config=None):
+ """
+ Loading settings, optionally from a custom config json file.
+ """
+ self.settings = Settings(self, config)
+ self.settings.load()
- r = random.SystemRandom()
- return '-'.join(r.choice(wordlist) for _ in range(2))
+ def log(self, module, func, msg=None):
+ """
+ If debug mode is on, log error messages to stdout
+ """
+ if self.debug:
+ timestamp = time.strftime("%b %d %Y %X")
+ final_msg = "[{}] {}.{}".format(timestamp, module, func)
+ if msg:
+ final_msg = '{}: {}'.format(final_msg, msg)
+ print(final_msg)
-def human_readable_filesize(b):
- """
- Returns filesize in a human readable format.
- """
- thresh = 1024.0
- if b < thresh:
- return '{:.1f} B'.format(b)
- units = ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
- u = 0
- b /= thresh
- while b >= thresh:
- b /= thresh
- u += 1
- return '{:.1f} {}'.format(b, units[u])
-
-
-def format_seconds(seconds):
- """Return a human-readable string of the format 1d2h3m4s"""
- days, seconds = divmod(seconds, 86400)
- hours, seconds = divmod(seconds, 3600)
- minutes, seconds = divmod(seconds, 60)
-
- human_readable = []
- if days:
- human_readable.append("{:.0f}d".format(days))
- if hours:
- human_readable.append("{:.0f}h".format(hours))
- if minutes:
- human_readable.append("{:.0f}m".format(minutes))
- if seconds or not human_readable:
- human_readable.append("{:.0f}s".format(seconds))
- return ''.join(human_readable)
-
-
-def estimated_time_remaining(bytes_downloaded, total_bytes, started):
- now = time.time()
- time_elapsed = now - started # in seconds
- download_rate = bytes_downloaded / time_elapsed
- remaining_bytes = total_bytes - bytes_downloaded
- eta = remaining_bytes / download_rate
- return format_seconds(eta)
-
-
-def get_available_port(min_port, max_port):
- """
- Find a random available port within the given range.
- """
- with socket.socket() as tmpsock:
- while True:
- try:
- tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port)))
- break
- except OSError as e:
- raise OSError(e)
- _, port = tmpsock.getsockname()
- return port
-
-
-def dir_size(start_path):
- """
- Calculates the total size, in bytes, of all of the files in a directory.
- """
- total_size = 0
- for dirpath, dirnames, filenames in os.walk(start_path):
- for f in filenames:
- fp = os.path.join(dirpath, f)
- if not os.path.islink(fp):
- total_size += os.path.getsize(fp)
- return total_size
+ def get_resource_path(self, filename):
+ """
+ Returns the absolute path of a resource, regardless of whether OnionShare is installed
+ systemwide, and whether regardless of platform
+ """
+ # On Windows, and in Windows dev mode, switch slashes in incoming filename to backslackes
+ if self.platform == 'Windows':
+ filename = filename.replace('/', '\\')
+
+ if getattr(sys, 'onionshare_dev_mode', False):
+ # Look for resources directory relative to python file
+ prefix = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))), 'share')
+ if not os.path.exists(prefix):
+ # While running tests during stdeb bdist_deb, look 3 directories up for the share folder
+ prefix = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(prefix)))), 'share')
+
+ elif self.platform == 'BSD' or self.platform == 'Linux':
+ # Assume OnionShare is installed systemwide in Linux, since we're not running in dev mode
+ prefix = os.path.join(sys.prefix, 'share/onionshare')
+
+ elif getattr(sys, 'frozen', False):
+ # Check if app is "frozen"
+ # https://pythonhosted.org/PyInstaller/#run-time-information
+ if self.platform == 'Darwin':
+ prefix = os.path.join(sys._MEIPASS, 'share')
+ elif self.platform == 'Windows':
+ prefix = os.path.join(os.path.dirname(sys.executable), 'share')
+
+ return os.path.join(prefix, filename)
+
+ def get_tor_paths(self):
+ if self.platform == 'Linux':
+ tor_path = '/usr/bin/tor'
+ tor_geo_ip_file_path = '/usr/share/tor/geoip'
+ tor_geo_ipv6_file_path = '/usr/share/tor/geoip6'
+ obfs4proxy_file_path = '/usr/bin/obfs4proxy'
+ elif self.platform == 'Windows':
+ base_path = os.path.join(os.path.dirname(os.path.dirname(self.get_resource_path(''))), 'tor')
+ tor_path = os.path.join(os.path.join(base_path, 'Tor'), 'tor.exe')
+ obfs4proxy_file_path = os.path.join(os.path.join(base_path, 'Tor'), 'obfs4proxy.exe')
+ tor_geo_ip_file_path = os.path.join(os.path.join(os.path.join(base_path, 'Data'), 'Tor'), 'geoip')
+ tor_geo_ipv6_file_path = os.path.join(os.path.join(os.path.join(base_path, 'Data'), 'Tor'), 'geoip6')
+ elif self.platform == 'Darwin':
+ base_path = os.path.dirname(os.path.dirname(os.path.dirname(self.get_resource_path(''))))
+ tor_path = os.path.join(base_path, 'Resources', 'Tor', 'tor')
+ tor_geo_ip_file_path = os.path.join(base_path, 'Resources', 'Tor', 'geoip')
+ tor_geo_ipv6_file_path = os.path.join(base_path, 'Resources', 'Tor', 'geoip6')
+ obfs4proxy_file_path = os.path.join(base_path, 'Resources', 'Tor', 'obfs4proxy')
+ elif self.platform == 'BSD':
+ tor_path = '/usr/local/bin/tor'
+ tor_geo_ip_file_path = '/usr/local/share/tor/geoip'
+ tor_geo_ipv6_file_path = '/usr/local/share/tor/geoip6'
+ obfs4proxy_file_path = '/usr/local/bin/obfs4proxy'
+
+ return (tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path, obfs4proxy_file_path)
+
+ def build_slug(self):
+ """
+ Returns a random string made from two words from the wordlist, such as "deter-trig".
+ """
+ with open(self.get_resource_path('wordlist.txt')) as f:
+ wordlist = f.read().split()
+ r = random.SystemRandom()
+ return '-'.join(r.choice(wordlist) for _ in range(2))
-class ZipWriter(object):
- """
- ZipWriter accepts files and directories and compresses them into a zip file
- with. If a zip_filename is not passed in, it will use the default onionshare
- filename.
- """
- def __init__(self, zip_filename=None, processed_size_callback=None):
- if zip_filename:
- self.zip_filename = zip_filename
- else:
- self.zip_filename = '{0:s}/onionshare_{1:s}.zip'.format(tempfile.mkdtemp(), random_string(4, 6))
-
- self.z = zipfile.ZipFile(self.zip_filename, 'w', allowZip64=True)
- self.processed_size_callback = processed_size_callback
- if self.processed_size_callback is None:
- self.processed_size_callback = lambda _: None
- self._size = 0
- self.processed_size_callback(self._size)
-
- def add_file(self, filename):
+ def define_css(self):
"""
- Add a file to the zip archive.
+ This defines all of the stylesheets used in GUI mode, to avoid repeating code.
+ This method is only called in GUI mode.
"""
- self.z.write(filename, os.path.basename(filename), zipfile.ZIP_DEFLATED)
- self._size += os.path.getsize(filename)
- self.processed_size_callback(self._size)
-
- def add_dir(self, filename):
+ self.css = {
+ # OnionShareGui styles
+ 'mode_switcher_selected_style': """
+ QPushButton {
+ color: #ffffff;
+ background-color: #4e064f;
+ border: 0;
+ border-right: 1px solid #69266b;
+ font-weight: bold;
+ border-radius: 0;
+ }""",
+
+ 'mode_switcher_unselected_style': """
+ QPushButton {
+ color: #ffffff;
+ background-color: #601f61;
+ border: 0;
+ font-weight: normal;
+ border-radius: 0;
+ }""",
+
+ 'settings_button': """
+ QPushButton {
+ background-color: #601f61;
+ border: 0;
+ border-left: 1px solid #69266b;
+ border-radius: 0;
+ }""",
+
+ 'server_status_indicator_label': """
+ QLabel {
+ font-style: italic;
+ color: #666666;
+ padding: 2px;
+ }""",
+
+ 'status_bar': """
+ QStatusBar {
+ font-style: italic;
+ color: #666666;
+ }
+ QStatusBar::item {
+ border: 0px;
+ }""",
+
+ # Common styles between ShareMode and ReceiveMode and their child widgets
+ 'mode_info_label': """
+ QLabel {
+ font-size: 12px;
+ color: #666666;
+ }
+ """,
+
+ 'server_status_url': """
+ QLabel {
+ background-color: #ffffff;
+ color: #000000;
+ padding: 10px;
+ border: 1px solid #666666;
+ font-size: 12px;
+ }
+ """,
+
+ 'server_status_url_buttons': """
+ QPushButton {
+ color: #3f7fcf;
+ }
+ """,
+
+ 'server_status_button_stopped': """
+ QPushButton {
+ background-color: #5fa416;
+ color: #ffffff;
+ padding: 10px;
+ border: 0;
+ border-radius: 5px;
+ }""",
+
+ 'server_status_button_working': """
+ QPushButton {
+ background-color: #4c8211;
+ color: #ffffff;
+ padding: 10px;
+ border: 0;
+ border-radius: 5px;
+ font-style: italic;
+ }""",
+
+ 'server_status_button_started': """
+ QPushButton {
+ background-color: #d0011b;
+ color: #ffffff;
+ padding: 10px;
+ border: 0;
+ border-radius: 5px;
+ }""",
+
+ 'downloads_uploads_empty': """
+ QWidget {
+ background-color: #ffffff;
+ border: 1px solid #999999;
+ }
+ QWidget QLabel {
+ background-color: none;
+ border: 0px;
+ }
+ """,
+
+ 'downloads_uploads_empty_text': """
+ QLabel {
+ color: #999999;
+ }""",
+
+ 'downloads_uploads_label': """
+ QLabel {
+ font-weight: bold;
+ font-size 14px;
+ text-align: center;
+ background-color: none;
+ border: none;
+ }""",
+
+ 'downloads_uploads_clear': """
+ QPushButton {
+ color: #3f7fcf;
+ }
+ """,
+
+ 'download_uploads_indicator': """
+ QLabel {
+ color: #ffffff;
+ background-color: #f44449;
+ font-weight: bold;
+ font-size: 10px;
+ padding: 2px;
+ border-radius: 7px;
+ text-align: center;
+ }""",
+
+ 'downloads_uploads_progress_bar': """
+ QProgressBar {
+ border: 1px solid #4e064f;
+ background-color: #ffffff !important;
+ text-align: center;
+ color: #9b9b9b;
+ font-size: 14px;
+ }
+ QProgressBar::chunk {
+ background-color: #4e064f;
+ width: 10px;
+ }""",
+
+ # Share mode and child widget styles
+ 'share_zip_progess_bar': """
+ QProgressBar {
+ border: 1px solid #4e064f;
+ background-color: #ffffff !important;
+ text-align: center;
+ color: #9b9b9b;
+ }
+ QProgressBar::chunk {
+ border: 0px;
+ background-color: #4e064f;
+ width: 10px;
+ }""",
+
+ 'share_filesize_warning': """
+ QLabel {
+ padding: 10px 0;
+ font-weight: bold;
+ color: #333333;
+ }
+ """,
+
+ 'share_file_selection_drop_here_label': """
+ QLabel {
+ color: #999999;
+ }""",
+
+ 'share_file_selection_drop_count_label': """
+ QLabel {
+ color: #ffffff;
+ background-color: #f44449;
+ font-weight: bold;
+ padding: 5px 10px;
+ border-radius: 10px;
+ }""",
+
+ 'share_file_list_drag_enter': """
+ FileList {
+ border: 3px solid #538ad0;
+ }
+ """,
+
+ 'share_file_list_drag_leave': """
+ FileList {
+ border: none;
+ }
+ """,
+
+ 'share_file_list_item_size': """
+ QLabel {
+ color: #666666;
+ font-size: 11px;
+ }""",
+
+ # Receive mode and child widget styles
+ 'receive_file': """
+ QWidget {
+ background-color: #ffffff;
+ }
+ """,
+
+ 'receive_file_size': """
+ QLabel {
+ color: #666666;
+ font-size: 11px;
+ }""",
+
+ # Settings dialog
+ 'settings_version': """
+ QLabel {
+ color: #666666;
+ }""",
+
+ 'settings_tor_status': """
+ QLabel {
+ background-color: #ffffff;
+ color: #000000;
+ padding: 10px;
+ }""",
+
+ 'settings_whats_this': """
+ QLabel {
+ font-size: 12px;
+ }"""
+ }
+
+ @staticmethod
+ def random_string(num_bytes, output_len=None):
"""
- Add a directory, and all of its children, to the zip archive.
+ Returns a random string with a specified number of bytes.
"""
- dir_to_strip = os.path.dirname(filename.rstrip('/'))+'/'
- for dirpath, dirnames, filenames in os.walk(filename):
- for f in filenames:
- full_filename = os.path.join(dirpath, f)
- if not os.path.islink(full_filename):
- arc_filename = full_filename[len(dir_to_strip):]
- self.z.write(full_filename, arc_filename, zipfile.ZIP_DEFLATED)
- self._size += os.path.getsize(full_filename)
- self.processed_size_callback(self._size)
-
- def close(self):
+ b = os.urandom(num_bytes)
+ h = hashlib.sha256(b).digest()[:16]
+ s = base64.b32encode(h).lower().replace(b'=', b'').decode('utf-8')
+ if not output_len:
+ return s
+ return s[:output_len]
+
+ @staticmethod
+ def human_readable_filesize(b):
+ """
+ Returns filesize in a human readable format.
+ """
+ thresh = 1024.0
+ if b < thresh:
+ return '{:.1f} B'.format(b)
+ units = ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
+ u = 0
+ b /= thresh
+ while b >= thresh:
+ b /= thresh
+ u += 1
+ return '{:.1f} {}'.format(b, units[u])
+
+ @staticmethod
+ def format_seconds(seconds):
+ """Return a human-readable string of the format 1d2h3m4s"""
+ days, seconds = divmod(seconds, 86400)
+ hours, seconds = divmod(seconds, 3600)
+ minutes, seconds = divmod(seconds, 60)
+
+ human_readable = []
+ if days:
+ human_readable.append("{:.0f}d".format(days))
+ if hours:
+ human_readable.append("{:.0f}h".format(hours))
+ if minutes:
+ human_readable.append("{:.0f}m".format(minutes))
+ if seconds or not human_readable:
+ human_readable.append("{:.0f}s".format(seconds))
+ return ''.join(human_readable)
+
+ @staticmethod
+ def estimated_time_remaining(bytes_downloaded, total_bytes, started):
+ now = time.time()
+ time_elapsed = now - started # in seconds
+ download_rate = bytes_downloaded / time_elapsed
+ remaining_bytes = total_bytes - bytes_downloaded
+ eta = remaining_bytes / download_rate
+ return Common.format_seconds(eta)
+
+ @staticmethod
+ def get_available_port(min_port, max_port):
"""
- Close the zip archive.
+ Find a random available port within the given range.
"""
- self.z.close()
+ with socket.socket() as tmpsock:
+ while True:
+ try:
+ tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port)))
+ break
+ except OSError as e:
+ pass
+ _, port = tmpsock.getsockname()
+ return port
+
+ @staticmethod
+ def dir_size(start_path):
+ """
+ Calculates the total size, in bytes, of all of the files in a directory.
+ """
+ total_size = 0
+ for dirpath, dirnames, filenames in os.walk(start_path):
+ for f in filenames:
+ fp = os.path.join(dirpath, f)
+ if not os.path.islink(fp):
+ total_size += os.path.getsize(fp)
+ return total_size
-class close_after_seconds(threading.Thread):
+class ShutdownTimer(threading.Thread):
"""
Background thread sleeps t hours and returns.
"""
- def __init__(self, time):
+ def __init__(self, common, time):
threading.Thread.__init__(self)
+
+ self.common = common
+
self.setDaemon(True)
self.time = time
def run(self):
- log('Shutdown Timer', 'Server will shut down after {} seconds'.format(self.time))
+ self.common.log('Shutdown Timer', 'Server will shut down after {} seconds'.format(self.time))
time.sleep(self.time)
return 1
diff --git a/onionshare/onion.py b/onionshare/onion.py
index 4d159d94..6066f059 100644
--- a/onionshare/onion.py
+++ b/onionshare/onion.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -21,9 +21,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
from stem.control import Controller
from stem import ProtocolError, SocketClosed
from stem.connection import MissingPassword, UnreadableCookieFile, AuthenticationFailure
-import os, sys, tempfile, shutil, urllib, platform, subprocess, time, shlex
+from Crypto.PublicKey import RSA
+import base64, os, sys, tempfile, shutil, urllib, platform, subprocess, time, shlex
-from . import socks
+from distutils.version import LooseVersion as Version
from . import common, strings
from .settings import Settings
@@ -125,22 +126,22 @@ class Onion(object):
call this function and pass in a status string while connecting to tor. This
is necessary for status updates to reach the GUI.
"""
- def __init__(self):
- common.log('Onion', '__init__')
+ def __init__(self, common):
+ self.common = common
+
+ self.common.log('Onion', '__init__')
self.stealth = False
self.service_id = None
- self.system = common.get_platform()
-
# Is bundled tor supported?
- if (self.system == 'Windows' or self.system == 'Darwin') and getattr(sys, 'onionshare_dev_mode', False):
+ if (self.common.platform == 'Windows' or self.common.platform == 'Darwin') and getattr(sys, 'onionshare_dev_mode', False):
self.bundle_tor_supported = False
else:
self.bundle_tor_supported = True
# Set the path of the tor binary, for bundled tor
- (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = common.get_tor_paths()
+ (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = self.common.get_tor_paths()
# The tor process
self.tor_proc = None
@@ -148,15 +149,14 @@ class Onion(object):
# Start out not connected to Tor
self.connected_to_tor = False
- def connect(self, settings=False, config=False, tor_status_update_func=None):
- common.log('Onion', 'connect')
+ def connect(self, custom_settings=False, config=False, tor_status_update_func=None):
+ self.common.log('Onion', 'connect')
- # Either use settings that are passed in, or load them from disk
- if settings:
- self.settings = settings
+ # Either use settings that are passed in, or use them from common
+ if custom_settings:
+ self.settings = custom_settings
else:
- self.settings = Settings(config)
- self.settings.load()
+ self.settings = self.common.settings
# The Tor controller
self.c = None
@@ -168,29 +168,29 @@ class Onion(object):
# Create a torrc for this session
self.tor_data_directory = tempfile.TemporaryDirectory()
- if self.system == 'Windows':
+ if self.common.platform == 'Windows':
# Windows needs to use network ports, doesn't support unix sockets
- torrc_template = open(common.get_resource_path('torrc_template-windows')).read()
+ torrc_template = open(self.common.get_resource_path('torrc_template-windows')).read()
try:
- self.tor_control_port = common.get_available_port(1000, 65535)
+ self.tor_control_port = self.common.get_available_port(1000, 65535)
except:
raise OSError(strings._('no_available_port'))
self.tor_control_socket = None
self.tor_cookie_auth_file = os.path.join(self.tor_data_directory.name, 'cookie')
try:
- self.tor_socks_port = common.get_available_port(1000, 65535)
+ self.tor_socks_port = self.common.get_available_port(1000, 65535)
except:
raise OSError(strings._('no_available_port'))
self.tor_torrc = os.path.join(self.tor_data_directory.name, 'torrc')
else:
# Linux, Mac and BSD can use unix sockets
- with open(common.get_resource_path('torrc_template')) as f:
+ with open(self.common.get_resource_path('torrc_template')) as f:
torrc_template = f.read()
self.tor_control_port = None
self.tor_control_socket = os.path.join(self.tor_data_directory.name, 'control_socket')
self.tor_cookie_auth_file = os.path.join(self.tor_data_directory.name, 'cookie')
try:
- self.tor_socks_port = common.get_available_port(1000, 65535)
+ self.tor_socks_port = self.common.get_available_port(1000, 65535)
except:
raise OSError(strings._('no_available_port'))
self.tor_torrc = os.path.join(self.tor_data_directory.name, 'torrc')
@@ -208,17 +208,12 @@ class Onion(object):
# Bridge support
if self.settings.get('tor_bridges_use_obfs4'):
f.write('ClientTransportPlugin obfs4 exec {}\n'.format(self.obfs4proxy_file_path))
- with open(common.get_resource_path('torrc_template-obfs4')) as o:
- for line in o:
- f.write(line)
- elif self.settings.get('tor_bridges_use_meek_lite_amazon'):
- f.write('ClientTransportPlugin meek_lite exec {}\n'.format(self.obfs4proxy_file_path))
- with open(common.get_resource_path('torrc_template-meek_lite_amazon')) as o:
+ with open(self.common.get_resource_path('torrc_template-obfs4')) as o:
for line in o:
f.write(line)
elif self.settings.get('tor_bridges_use_meek_lite_azure'):
f.write('ClientTransportPlugin meek_lite exec {}\n'.format(self.obfs4proxy_file_path))
- with open(common.get_resource_path('torrc_template-meek_lite_azure')) as o:
+ with open(self.common.get_resource_path('torrc_template-meek_lite_azure')) as o:
for line in o:
f.write(line)
@@ -232,7 +227,7 @@ class Onion(object):
# Execute a tor subprocess
start_ts = time.time()
- if self.system == 'Windows':
+ if self.common.platform == 'Windows':
# In Windows, hide console window when opening tor.exe subprocess
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
@@ -245,14 +240,14 @@ class Onion(object):
# Connect to the controller
try:
- if self.system == 'Windows':
+ if self.common.platform == 'Windows':
self.c = Controller.from_port(port=self.tor_control_port)
self.c.authenticate()
else:
self.c = Controller.from_socket_file(path=self.tor_control_socket)
self.c.authenticate()
except Exception as e:
- raise BundledTorBroken(strings._('settings_error_bundled_tor_broken', True).format(e.args[0]))
+ raise BundledTorBroken(strings._('settings_error_bundled_tor_broken').format(e.args[0]))
while True:
try:
@@ -270,7 +265,7 @@ class Onion(object):
if callable(tor_status_update_func):
if not tor_status_update_func(progress, summary):
# If the dialog was canceled, stop connecting to Tor
- common.log('Onion', 'connect', 'tor_status_update_func returned false, canceling connecting to Tor')
+ self.common.log('Onion', 'connect', 'tor_status_update_func returned false, canceling connecting to Tor')
print()
return False
@@ -282,7 +277,6 @@ class Onion(object):
# If using bridges, it might take a bit longer to connect to Tor
if self.settings.get('tor_bridges_use_custom_bridges') or \
self.settings.get('tor_bridges_use_obfs4') or \
- self.settings.get('tor_bridges_use_meek_lite_amazon') or \
self.settings.get('tor_bridges_use_meek_lite_azure'):
connect_timeout = 150
else:
@@ -322,7 +316,7 @@ class Onion(object):
socket_file_path = ''
if not found_tor:
try:
- if self.system == 'Darwin':
+ if self.common.platform == 'Darwin':
socket_file_path = os.path.expanduser('~/Library/Application Support/TorBrowser-Data/Tor/control.socket')
self.c = Controller.from_socket_file(path=socket_file_path)
@@ -334,11 +328,11 @@ class Onion(object):
# guessing the socket file name next
if not found_tor:
try:
- if self.system == 'Linux' or self.system == 'BSD':
+ if self.common.platform == 'Linux' or self.common.platform == 'BSD':
socket_file_path = '/run/user/{}/Tor/control.socket'.format(os.geteuid())
- elif self.system == 'Darwin':
+ elif self.common.platform == 'Darwin':
socket_file_path = '/run/user/{}/Tor/control.socket'.format(os.geteuid())
- elif self.system == 'Windows':
+ elif self.common.platform == 'Windows':
# Windows doesn't support unix sockets
raise TorErrorAutomatic(strings._('settings_error_automatic'))
@@ -408,6 +402,8 @@ class Onion(object):
# ephemeral stealth onion services are not supported
self.supports_stealth = False
+ # Does this version of Tor support next-gen ('v3') onions?
+ self.supports_next_gen_onions = self.tor_version > Version('0.3.3.1')
def is_authenticated(self):
"""
@@ -424,7 +420,7 @@ class Onion(object):
Start a onion service on port 80, pointing to the given port, and
return the onion hostname.
"""
- common.log('Onion', 'start_onion_service')
+ self.common.log('Onion', 'start_onion_service')
self.auth_string = None
if not self.supports_ephemeral:
@@ -433,7 +429,6 @@ class Onion(object):
raise TorTooOld(strings._('error_stealth_not_supported'))
print(strings._("config_onion_service").format(int(port)))
- print(strings._('using_ephemeral'))
if self.stealth:
if self.settings.get('hidservauth_string'):
@@ -445,23 +440,53 @@ class Onion(object):
basic_auth = None
if self.settings.get('private_key'):
- key_type = "RSA1024"
key_content = self.settings.get('private_key')
- common.log('Onion', 'Starting a hidden service with a saved private key')
+ if self.is_v2_key(key_content):
+ key_type = "RSA1024"
+ # The below section is commented out because re-publishing
+ # a pre-prepared v3 private key is currently unstable in Tor.
+ # This is fixed upstream but won't reach stable until 0.3.5
+ # (expected in December 2018)
+ # See https://trac.torproject.org/projects/tor/ticket/25552
+ # Until then, we will deliberately not work with 'persistent'
+ # v3 onions, which should not be possible via the GUI settings
+ # anyway.
+ # Our ticket: https://github.com/micahflee/onionshare/issues/677
+ #
+ # Assume it was a v3 key
+ # key_type = "ED25519-V3"
+ else:
+ raise TorErrorProtocolError(strings._('error_invalid_private_key'))
+
else:
key_type = "NEW"
- key_content = "RSA1024"
- common.log('Onion', 'Starting a hidden service with a new private key')
+ # Work out if we can support v3 onion services, which are preferred
+ if Version(self.tor_version) >= Version('0.3.3.1') and not self.settings.get('use_legacy_v2_onions'):
+ key_content = "ED25519-V3"
+ else:
+ # fall back to v2 onion services
+ key_content = "RSA1024"
+
+ # v3 onions don't yet support basic auth. Our ticket:
+ # https://github.com/micahflee/onionshare/issues/697
+ if key_type == "NEW" and key_content == "ED25519-V3" and not self.settings.get('use_legacy_v2_onions'):
+ basic_auth = None
+ self.stealth = False
+ debug_message = 'key_type={}'.format(key_type)
+ if key_type == "NEW":
+ debug_message += ', key_content={}'.format(key_content)
+ self.common.log('Onion', 'start_onion_service', '{}'.format(debug_message))
+ await_publication = True
try:
if basic_auth != None:
- res = self.c.create_ephemeral_hidden_service({ 80: port }, await_publication=True, basic_auth=basic_auth, key_type = key_type, key_content=key_content)
+ res = self.c.create_ephemeral_hidden_service({ 80: port }, await_publication=await_publication, basic_auth=basic_auth, key_type=key_type, key_content=key_content)
else:
# if the stem interface is older than 1.5.0, basic_auth isn't a valid keyword arg
- res = self.c.create_ephemeral_hidden_service({ 80: port }, await_publication=True, key_type = key_type, key_content=key_content)
+ res = self.c.create_ephemeral_hidden_service({ 80: port }, await_publication=await_publication, key_type=key_type, key_content=key_content)
- except ProtocolError:
- raise TorErrorProtocolError(strings._('error_tor_protocol_error'))
+ except ProtocolError as e:
+ raise TorErrorProtocolError(strings._('error_tor_protocol_error').format(e.args[0]))
self.service_id = res.service_id
onion_host = self.service_id + '.onion'
@@ -492,23 +517,23 @@ class Onion(object):
self.settings.save()
return onion_host
else:
- raise TorErrorProtocolError(strings._('error_tor_protocol_error'))
+ raise TorErrorProtocolError(strings._('error_tor_protocol_error_unknown'))
def cleanup(self, stop_tor=True):
"""
Stop onion services that were created earlier. If there's a tor subprocess running, kill it.
"""
- common.log('Onion', 'cleanup')
+ self.common.log('Onion', 'cleanup')
# Cleanup the ephemeral onion services, if we have any
try:
onions = self.c.list_ephemeral_hidden_services()
for onion in onions:
try:
- common.log('Onion', 'cleanup', 'trying to remove onion {}'.format(onion))
+ self.common.log('Onion', 'cleanup', 'trying to remove onion {}'.format(onion))
self.c.remove_ephemeral_hidden_service(onion)
except:
- common.log('Onion', 'cleanup', 'could not remove onion {}.. moving on anyway'.format(onion))
+ self.common.log('Onion', 'cleanup', 'could not remove onion {}.. moving on anyway'.format(onion))
pass
except:
pass
@@ -545,7 +570,7 @@ class Onion(object):
"""
Returns a (address, port) tuple for the Tor SOCKS port
"""
- common.log('Onion', 'get_tor_socks_port')
+ self.common.log('Onion', 'get_tor_socks_port')
if self.settings.get('connection_type') == 'bundled':
return ('127.0.0.1', self.tor_socks_port)
@@ -553,3 +578,18 @@ class Onion(object):
return ('127.0.0.1', 9150)
else:
return (self.settings.get('socks_address'), self.settings.get('socks_port'))
+
+ def is_v2_key(self, key):
+ """
+ Helper function for determining if a key is RSA1024 (v2) or not.
+ """
+ try:
+ # Import the key
+ key = RSA.importKey(base64.b64decode(key))
+ # Is this a v2 Onion key? (1024 bits) If so, we should keep using it.
+ if key.n.bit_length() == 1024:
+ return True
+ else:
+ return False
+ except:
+ return False
diff --git a/onionshare/onionshare.py b/onionshare/onionshare.py
index b1760537..32e56ba0 100644
--- a/onionshare/onionshare.py
+++ b/onionshare/onionshare.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -21,20 +21,25 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import os, shutil
from . import common, strings
+from .onion import TorTooOld, TorErrorProtocolError
+from .common import ShutdownTimer
class OnionShare(object):
"""
OnionShare is the main application class. Pass in options and run
start_onion_service and it will do the magic.
"""
- def __init__(self, onion, local_only=False, stay_open=False, shutdown_timeout=0):
- common.log('OnionShare', '__init__')
+ def __init__(self, common, onion, local_only=False, shutdown_timeout=0):
+ self.common = common
+
+ self.common.log('OnionShare', '__init__')
# The Onion object
self.onion = onion
self.hidserv_dir = None
self.onion_host = None
+ self.port = None
self.stealth = None
# files and dirs to delete on shutdown
@@ -43,39 +48,42 @@ class OnionShare(object):
# do not use tor -- for development
self.local_only = local_only
- # automatically close when download is finished
- self.stay_open = stay_open
-
# optionally shut down after N hours
self.shutdown_timeout = shutdown_timeout
# init timing thread
self.shutdown_timer = None
def set_stealth(self, stealth):
- common.log('OnionShare', 'set_stealth', 'stealth={}'.format(stealth))
+ self.common.log('OnionShare', 'set_stealth', 'stealth={}'.format(stealth))
self.stealth = stealth
self.onion.stealth = stealth
- def start_onion_service(self):
+ def choose_port(self):
"""
- Start the onionshare onion service.
+ Choose a random port.
"""
- common.log('OnionShare', 'start_onion_service')
-
- # Choose a random port
try:
- self.port = common.get_available_port(17600, 17650)
+ self.port = self.common.get_available_port(17600, 17650)
except:
raise OSError(strings._('no_available_port'))
+ def start_onion_service(self):
+ """
+ Start the onionshare onion service.
+ """
+ self.common.log('OnionShare', 'start_onion_service')
+
+ if not self.port:
+ self.choose_port()
+
+ if self.shutdown_timeout > 0:
+ self.shutdown_timer = ShutdownTimer(self.common, self.shutdown_timeout)
+
if self.local_only:
self.onion_host = '127.0.0.1:{0:d}'.format(self.port)
return
- if self.shutdown_timeout > 0:
- self.shutdown_timer = common.close_after_seconds(self.shutdown_timeout)
-
self.onion_host = self.onion.start_onion_service(self.port)
if self.stealth:
@@ -85,7 +93,7 @@ class OnionShare(object):
"""
Shut everything down and clean up temporary files, etc.
"""
- common.log('OnionShare', 'cleanup')
+ self.common.log('OnionShare', 'cleanup')
# cleanup files
for filename in self.cleanup_filenames:
diff --git a/onionshare/settings.py b/onionshare/settings.py
index 034e863f..fc68ffc9 100644
--- a/onionshare/settings.py
+++ b/onionshare/settings.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -21,8 +21,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import os
import platform
+import locale
-from . import strings, common
+from . import strings
class Settings(object):
@@ -32,8 +33,10 @@ class Settings(object):
which is to attempt to connect automatically using default Tor Browser
settings.
"""
- def __init__(self, config=False):
- common.log('Settings', '__init__')
+ def __init__(self, common, config=False):
+ self.common = common
+
+ self.common.log('Settings', '__init__')
# Default config
self.filename = self.build_filename()
@@ -43,11 +46,31 @@ class Settings(object):
if os.path.isfile(config):
self.filename = config
else:
- common.log('Settings', '__init__', 'Supplied config does not exist or is unreadable. Falling back to default location')
+ self.common.log('Settings', '__init__', 'Supplied config does not exist or is unreadable. Falling back to default location')
+
+ # Dictionary of available languages in this version of OnionShare,
+ # mapped to the language name, in that language
+ self.available_locales = {
+ 'cs': 'Hrvatski', # Croatian
+ 'da': 'Dansk', # Danish
+ 'de': 'Deutsch', # German
+ 'en': 'English', # English
+ 'eo': 'Esperanto', # Esperanto
+ 'es': 'Español', # Spanish
+ 'fi': 'Suomi', # Finnish
+ 'fr': 'Français', # French
+ 'it': 'Italiano', # Italian
+ 'nl': 'Nederlands', # Dutch
+ 'no': 'Norsk', # Norwegian
+ 'pt_BR': 'Português Brasil', # Portuguese Brazil
+ 'pt_PT': 'Português Portugal', # Portuguese Portugal
+ 'ru': 'Русский', # Russian
+ 'tr': 'Türkçe' # Turkish
+ }
# These are the default settings. They will get overwritten when loading from disk
self.default_settings = {
- 'version': common.get_version(),
+ 'version': self.common.version,
'connection_type': 'bundled',
'control_port_address': '127.0.0.1',
'control_port_port': 9051,
@@ -57,20 +80,22 @@ class Settings(object):
'auth_type': 'no_auth',
'auth_password': '',
'close_after_first_download': True,
- 'systray_notifications': True,
'shutdown_timeout': False,
'use_stealth': False,
'use_autoupdate': True,
'autoupdate_timestamp': None,
'no_bridges': True,
'tor_bridges_use_obfs4': False,
- 'tor_bridges_use_meek_lite_amazon': False,
'tor_bridges_use_meek_lite_azure': False,
'tor_bridges_use_custom_bridges': '',
+ 'use_legacy_v2_onions': False,
'save_private_key': False,
'private_key': '',
+ 'public_mode': False,
'slug': '',
- 'hidservauth_string': ''
+ 'hidservauth_string': '',
+ 'downloads_dir': self.build_default_downloads_dir(),
+ 'locale': None # this gets defined in fill_in_defaults()
}
self._settings = {}
self.fill_in_defaults()
@@ -84,29 +109,53 @@ class Settings(object):
if key not in self._settings:
self._settings[key] = self.default_settings[key]
+ # Choose the default locale based on the OS preference, and fall-back to English
+ if self._settings['locale'] is None:
+ default_locale = locale.getdefaultlocale()[0][:2]
+ if default_locale not in self.available_locales:
+ default_locale = 'en'
+ self._settings['locale'] = default_locale
+
def build_filename(self):
"""
Returns the path of the settings file.
"""
p = platform.system()
if p == 'Windows':
- appdata = os.environ['APPDATA']
- return '{}\\OnionShare\\onionshare.json'.format(appdata)
+ try:
+ appdata = os.environ['APPDATA']
+ return '{}\\OnionShare\\onionshare.json'.format(appdata)
+ except:
+ # If for some reason we don't have the 'APPDATA' environment variable
+ # (like running tests in Linux while pretending to be in Windows)
+ return os.path.expanduser('~/.config/onionshare/onionshare.json')
elif p == 'Darwin':
return os.path.expanduser('~/Library/Application Support/OnionShare/onionshare.json')
else:
return os.path.expanduser('~/.config/onionshare/onionshare.json')
+ def build_default_downloads_dir(self):
+ """
+ Returns the path of the default Downloads directory for receive mode.
+ """
+ # On Windows, os.path.expanduser() needs to use backslash, or else it
+ # retains the forward slash, which breaks opening the folder in explorer.
+ p = platform.system()
+ if p == 'Windows':
+ return os.path.expanduser('~\OnionShare')
+ else:
+ return os.path.expanduser('~/OnionShare')
+
def load(self):
"""
Load the settings from file.
"""
- common.log('Settings', 'load')
+ self.common.log('Settings', 'load')
# If the settings file exists, load it
if os.path.exists(self.filename):
try:
- common.log('Settings', 'load', 'Trying to load {}'.format(self.filename))
+ self.common.log('Settings', 'load', 'Trying to load {}'.format(self.filename))
with open(self.filename, 'r') as f:
self._settings = json.load(f)
self.fill_in_defaults()
@@ -117,14 +166,14 @@ class Settings(object):
"""
Save settings to file.
"""
- common.log('Settings', 'save')
+ self.common.log('Settings', 'save')
try:
os.makedirs(os.path.dirname(self.filename))
except:
pass
open(self.filename, 'w').write(json.dumps(self._settings))
- print(strings._('settings_saved').format(self.filename))
+ self.common.log('Settings', 'save', 'Settings saved in {}'.format(self.filename))
def get(self, key):
return self._settings[key]
diff --git a/onionshare/socks.py b/onionshare/socks.py
deleted file mode 100644
index 809a4444..00000000
--- a/onionshare/socks.py
+++ /dev/null
@@ -1,530 +0,0 @@
-"""
-SocksiPy - Python SOCKS module.
-Version 1.5.0
-
-Copyright 2006 Dan-Haim. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-3. Neither the name of Dan Haim nor the names of his contributors may be used
- to endorse or promote products derived from this software without specific
- prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
-WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-
-This module provides a standard socket-like interface for Python
-for tunneling connections through SOCKS proxies.
-
-===============================================================================
-
-Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
-for use in PyLoris (http://pyloris.sourceforge.net/)
-
-Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
-mainly to merge bug fixes found in Sourceforge
-
-Modifications made by Anorov (https://github.com/Anorov)
--Forked and renamed to PySocks
--Fixed issue with HTTP proxy failure checking (same bug that was in the old ___recvall() method)
--Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler,
- courtesy of e000 (https://github.com/e000): https://gist.github.com/869791#file_socksipyhandler.py
--Re-styled code to make it readable
- -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc.
- -Improved exception handling and output
- -Removed irritating use of sequence indexes, replaced with tuple unpacked variables
- -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03"
- -Other general fixes
--Added clarification that the HTTP proxy connection method only supports CONNECT-style tunneling HTTP proxies
--Various small bug fixes
-"""
-
-__version__ = "1.5.0"
-
-import socket
-import struct
-
-PROXY_TYPE_SOCKS4 = SOCKS4 = 1
-PROXY_TYPE_SOCKS5 = SOCKS5 = 2
-PROXY_TYPE_HTTP = HTTP = 3
-
-PRINTABLE_PROXY_TYPES = {SOCKS4: "SOCKS4", SOCKS5: "SOCKS5", HTTP: "HTTP"}
-
-_orgsocket = _orig_socket = socket.socket
-
-
-class ProxyError(IOError):
- """
- socket_err contains original socket.error exception.
- """
- def __init__(self, msg, socket_err=None):
- self.msg = msg
- self.socket_err = socket_err
-
- if socket_err:
- self.msg = msg + ": {}".format(socket_err)
-
- def __str__(self):
- return self.msg
-
-
-class GeneralProxyError(ProxyError):
- pass
-
-
-class ProxyConnectionError(ProxyError):
- pass
-
-
-class SOCKS5AuthError(ProxyError):
- pass
-
-
-class SOCKS5Error(ProxyError):
- pass
-
-
-class SOCKS4Error(ProxyError):
- pass
-
-
-class HTTPError(ProxyError):
- pass
-
-
-SOCKS4_ERRORS = {
- 0x5B: "Request rejected or failed",
- 0x5C: "Request rejected because SOCKS server cannot connect to identd on the client",
- 0x5D: "Request rejected because the client program and identd report different user-ids",
-}
-
-SOCKS5_ERRORS = {
- 0x01: "General SOCKS server failure",
- 0x02: "Connection not allowed by ruleset",
- 0x03: "Network unreachable",
- 0x04: "Host unreachable",
- 0x05: "Connection refused",
- 0x06: "TTL expired",
- 0x07: "Command not supported, or protocol error",
- 0x08: "Address type not supported",
-}
-
-DEFAULT_PORTS = {
- SOCKS4: 1080,
- SOCKS5: 1080,
- HTTP: 8080,
-}
-
-
-def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
- """
- set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]])
-
- Sets a default proxy which all further socksocket objects will use,
- unless explicitly changed.
- """
- socksocket.default_proxy = (proxy_type, addr.encode(), port, rdns,
- username.encode() if username else None,
- password.encode() if password else None)
-
-setdefaultproxy = set_default_proxy
-
-
-def get_default_proxy():
- """
- Returns the default proxy, set by set_default_proxy.
- """
- return socksocket.default_proxy
-
-getdefaultproxy = get_default_proxy
-
-
-def wrap_module(module):
- """
- Attempts to replace a module's socket library with a SOCKS socket. Must set
- a default proxy using set_default_proxy(...) first.
- This will only work on modules that import socket directly into the namespace;
- most of the Python Standard Library falls into this category.
- """
- if socksocket.default_proxy:
- module.socket.socket = socksocket
- else:
- raise GeneralProxyError("No default proxy specified")
-
-wrapmodule = wrap_module
-
-
-def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
- proxy_port=None, proxy_username=None,
- proxy_password=None, timeout=None):
- """create_connection(dest_pair, **proxy_args) -> socket object
-
- Like socket.create_connection(), but connects to proxy
- before returning the socket object.
-
- dest_pair - 2-tuple of (IP/hostname, port).
- **proxy_args - Same args passed to socksocket.set_proxy().
- timeout - Optional socket timeout value, in seconds.
- """
- sock = socksocket()
- if isinstance(timeout, (int, float)):
- sock.settimeout(timeout)
- sock.set_proxy(proxy_type, proxy_addr, proxy_port,
- proxy_username, proxy_password)
- sock.connect(dest_pair)
- return sock
-
-
-class socksocket(socket.socket):
- """socksocket([family[, type[, proto]]]) -> socket object
-
- Open a SOCKS enabled socket. The parameters are the same as
- those of the standard socket init. In order for SOCKS to work,
- you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
- """
-
- default_proxy = None
-
- def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
- _orig_socket.__init__(self, family, type, proto, _sock)
-
- if self.default_proxy:
- self.proxy = self.default_proxy
- else:
- self.proxy = (None, None, None, None, None, None)
- self.proxy_sockname = None
- self.proxy_peername = None
-
- self.proxy_negotiators = {
- SOCKS4: self._negotiate_SOCKS4,
- SOCKS5: self._negotiate_SOCKS5,
- HTTP: self._negotiate_HTTP,
- }
-
- def _recvall(self, count):
- """
- Receive EXACTLY the number of bytes requested from the socket.
- Blocks until the required number of bytes have been received.
- """
- data = b""
- while len(data) < count:
- d = self.recv(count - len(data))
- if not d:
- raise GeneralProxyError("Connection closed unexpectedly")
- data += d
- return data
-
- def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
- """set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
- Sets the proxy to be used.
-
- proxy_type - The type of the proxy to be used. Three types
- are supported: PROXY_TYPE_SOCKS4 (including socks4a),
- PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
- addr - The address of the server (IP or DNS).
- port - The port of the server. Defaults to 1080 for SOCKS
- servers and 8080 for HTTP proxy servers.
- rdns - Should DNS queries be performed on the remote side
- (rather than the local side). The default is True.
- Note: This has no effect with SOCKS4 servers.
- username - Username to authenticate with to the server.
- The default is no authentication.
- password - Password to authenticate with to the server.
- Only relevant when username is also provided.
- """
- self.proxy = (proxy_type, addr.encode(), port, rdns,
- username.encode() if username else None,
- password.encode() if password else None)
-
- setproxy = set_proxy
-
- def get_proxy_sockname(self):
- """
- Returns the bound IP address and port number at the proxy.
- """
- return self.proxy_sockname
-
- getproxysockname = get_proxy_sockname
-
- def get_proxy_peername(self):
- """
- Returns the IP and port number of the proxy.
- """
- return _orig_socket.getpeername(self)
-
- getproxypeername = get_proxy_peername
-
- def get_peername(self):
- """
- Returns the IP address and port number of the destination
- machine (note: get_proxy_peername returns the proxy)
- """
- return self.proxy_peername
-
- getpeername = get_peername
-
- def _negotiate_SOCKS5(self, dest_addr, dest_port):
- """
- Negotiates a connection through a SOCKS5 server.
- """
- proxy_type, addr, port, rdns, username, password = self.proxy
-
- # First we'll send the authentication packages we support.
- if username and password:
- # The username/password details were supplied to the
- # set_proxy method so we support the USERNAME/PASSWORD
- # authentication (in addition to the standard none).
- self.sendall(b"\x05\x02\x00\x02")
- else:
- # No username/password were entered, therefore we
- # only support connections with no authentication.
- self.sendall(b"\x05\x01\x00")
-
- # We'll receive the server's response to determine which
- # method was selected
- chosen_auth = self._recvall(2)
-
- if chosen_auth[0:1] != b"\x05":
- # Note: string[i:i+1] is used because indexing of a bytestring
- # via bytestring[i] yields an integer in Python 3
- raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
-
- # Check the chosen authentication method
-
- if chosen_auth[1:2] == b"\x02":
- # Okay, we need to perform a basic username/password
- # authentication.
- self.sendall(b"\x01" + chr(len(username)).encode()
- + username
- + chr(len(password)).encode()
- + password)
- auth_status = self._recvall(2)
- if auth_status[0:1] != b"\x01":
- # Bad response
- raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
- if auth_status[1:2] != b"\x00":
- # Authentication failed
- raise SOCKS5AuthError("SOCKS5 authentication failed")
-
- # Otherwise, authentication succeeded
-
- # No authentication is required if 0x00
- elif chosen_auth[1:2] != b"\x00":
- # Reaching here is always bad
- if chosen_auth[1:2] == b"\xFF":
- raise SOCKS5AuthError("All offered SOCKS5 authentication methods were rejected")
- else:
- raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
-
- # Now we can request the actual connection
- req = b"\x05\x01\x00"
- # If the given destination address is an IP address, we'll
- # use the IPv4 address request even if remote resolving was specified.
- try:
- addr_bytes = socket.inet_aton(dest_addr)
- req += b"\x01" + addr_bytes
- except socket.error:
- # Well it's not an IP number, so it's probably a DNS name.
- if rdns:
- # Resolve remotely
- addr_bytes = None
- req += b"\x03" + chr(len(dest_addr)).encode() + dest_addr.encode()
- else:
- # Resolve locally
- addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr))
- req += b"\x01" + addr_bytes
-
- req += struct.pack(">H", dest_port)
- self.sendall(req)
-
- # Get the response
- resp = self._recvall(4)
- if resp[0:1] != b"\x05":
- raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
-
- status = ord(resp[1:2])
- if status != 0x00:
- # Connection failed: server returned an error
- error = SOCKS5_ERRORS.get(status, "Unknown error")
- raise SOCKS5Error("{:#04x}: {}".format(status, error))
-
- # Get the bound address/port
- if resp[3:4] == b"\x01":
- bound_addr = self._recvall(4)
- elif resp[3:4] == b"\x03":
- resp += self.recv(1)
- bound_addr = self._recvall(ord(resp[4:5]))
- else:
- raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
-
- bound_port = struct.unpack(">H", self._recvall(2))[0]
- self.proxy_sockname = bound_addr, bound_port
- if addr_bytes:
- self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port
- else:
- self.proxy_peername = dest_addr, dest_port
-
- def _negotiate_SOCKS4(self, dest_addr, dest_port):
- """
- Negotiates a connection through a SOCKS4 server.
- """
- proxy_type, addr, port, rdns, username, password = self.proxy
-
- # Check if the destination address provided is an IP address
- remote_resolve = False
- try:
- addr_bytes = socket.inet_aton(dest_addr)
- except socket.error:
- # It's a DNS name. Check where it should be resolved.
- if rdns:
- addr_bytes = b"\x00\x00\x00\x01"
- remote_resolve = True
- else:
- addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr))
-
- # Construct the request packet
- req = struct.pack(">BBH", 0x04, 0x01, dest_port) + addr_bytes
-
- # The username parameter is considered userid for SOCKS4
- if username:
- req += username
- req += b"\x00"
-
- # DNS name if remote resolving is required
- # NOTE: This is actually an extension to the SOCKS4 protocol
- # called SOCKS4A and may not be supported in all cases.
- if remote_resolve:
- req += dest_addr.encode() + b"\x00"
- self.sendall(req)
-
- # Get the response from the server
- resp = self._recvall(8)
- if resp[0:1] != b"\x00":
- # Bad data
- raise GeneralProxyError("SOCKS4 proxy server sent invalid data")
-
- status = ord(resp[1:2])
- if status != 0x5A:
- # Connection failed: server returned an error
- error = SOCKS4_ERRORS.get(status, "Unknown error")
- raise SOCKS4Error("{:#04x}: {}".format(status, error))
-
- # Get the bound address/port
- self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
- if remote_resolve:
- self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port
- else:
- self.proxy_peername = dest_addr, dest_port
-
- def _negotiate_HTTP(self, dest_addr, dest_port):
- """
- Negotiates a connection through an HTTP server.
- NOTE: This currently only supports HTTP CONNECT-style proxies.
- """
- proxy_type, addr, port, rdns, username, password = self.proxy
-
- # If we need to resolve locally, we do this now
- addr = dest_addr if rdns else socket.gethostbyname(dest_addr)
-
- self.sendall(b"CONNECT " + addr.encode() + b":" + str(dest_port).encode() +
- b" HTTP/1.1\r\n" + b"Host: " + dest_addr.encode() + b"\r\n\r\n")
-
- # We just need the first line to check if the connection was successful
- fobj = self.makefile()
- status_line = fobj.readline()
- fobj.close()
-
- if not status_line:
- raise GeneralProxyError("Connection closed unexpectedly")
-
- try:
- proto, status_code, status_msg = status_line.split(" ", 2)
- except ValueError:
- raise GeneralProxyError("HTTP proxy server sent invalid response")
-
- if not proto.startswith("HTTP/"):
- raise GeneralProxyError("Proxy server does not appear to be an HTTP proxy")
-
- try:
- status_code = int(status_code)
- except ValueError:
- raise HTTPError("HTTP proxy server did not return a valid HTTP status")
-
- if status_code != 200:
- error = "{}: {}".format(status_code, status_msg)
- if status_code in (400, 403, 405):
- # It's likely that the HTTP proxy server does not support the CONNECT tunneling method
- error += ("\n[*] Note: The HTTP proxy server may not be supported by PySocks"
- " (must be a CONNECT tunnel proxy)")
- raise HTTPError(error)
-
- self.proxy_sockname = (b"0.0.0.0", 0)
- self.proxy_peername = addr, dest_port
-
- def connect(self, dest_pair):
- """
- Connects to the specified destination through a proxy.
- Uses the same API as socket's connect().
- To select the proxy server, use set_proxy().
-
- dest_pair - 2-tuple of (IP/hostname, port).
- """
- proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy
- dest_addr, dest_port = dest_pair
-
- # Do a minimal input check first
- if (not isinstance(dest_pair, (list, tuple))
- or len(dest_pair) != 2
- or not isinstance(dest_addr, type(""))
- or not isinstance(dest_port, int)):
- raise GeneralProxyError("Invalid destination-connection (host, port) pair")
-
- if proxy_type is None:
- # Treat like regular socket object
- _orig_socket.connect(self, (dest_addr, dest_port))
- return
-
- proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type)
- if not proxy_port:
- raise GeneralProxyError("Invalid proxy type")
-
- try:
- # Initial connection to proxy server
- _orig_socket.connect(self, (proxy_addr, proxy_port))
-
- except socket.error as error:
- # Error while connecting to proxy
- self.close()
- proxy_server = "{}:{}".format(proxy_addr.decode(), proxy_port)
- printable_type = PRINTABLE_PROXY_TYPES[proxy_type]
-
- msg = "Error connecting to {} proxy {}".format(printable_type,
- proxy_server)
- raise ProxyConnectionError(msg, error)
-
- else:
- # Connected to proxy server, now negotiate
- try:
- # Calls negotiate_{SOCKS4, SOCKS5, HTTP}
- self.proxy_negotiators[proxy_type](dest_addr, dest_port)
- except socket.error as error:
- # Wrap socket errors
- self.close()
- raise GeneralProxyError("Socket error", error)
- except ProxyError:
- # Protocol error while negotiating with proxy
- self.close()
- raise
diff --git a/onionshare/strings.py b/onionshare/strings.py
index ccbfc37f..b730933d 100644
--- a/onionshare/strings.py
+++ b/onionshare/strings.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -22,39 +22,36 @@ import locale
import os
strings = {}
+translations = {}
-def load_strings(common, default="en"):
+def load_strings(common):
"""
Loads translated strings and fallback to English
if the translation does not exist.
"""
- global strings
+ global strings, translations
- # find locale dir
- locale_dir = common.get_resource_path('locale')
-
- # load all translations
+ # Load all translations
translations = {}
- for filename in os.listdir(locale_dir):
- abs_filename = os.path.join(locale_dir, filename)
- lang, ext = os.path.splitext(filename)
- if ext == '.json':
- with open(abs_filename, encoding='utf-8') as f:
- translations[lang] = json.load(f)
-
- strings = translations[default]
- lc, enc = locale.getdefaultlocale()
- if lc:
- lang = lc[:2]
- if lang in translations:
- # if a string doesn't exist, fallback to English
- for key in translations[default]:
- if key in translations[lang]:
- strings[key] = translations[lang][key]
-
-
-def translated(k, gui=False):
+ for locale in common.settings.available_locales:
+ locale_dir = common.get_resource_path('locale')
+ filename = os.path.join(locale_dir, "{}.json".format(locale))
+ with open(filename, encoding='utf-8') as f:
+ translations[locale] = json.load(f)
+
+ # Build strings
+ default_locale = 'en'
+ current_locale = common.settings.get('locale')
+ strings = {}
+ for s in translations[default_locale]:
+ if s in translations[current_locale]:
+ strings[s] = translations[current_locale][s]
+ else:
+ strings[s] = translations[default_locale][s]
+
+
+def translated(k):
"""
Returns a translated string.
"""
diff --git a/onionshare/web.py b/onionshare/web.py
deleted file mode 100644
index e9c4d43b..00000000
--- a/onionshare/web.py
+++ /dev/null
@@ -1,454 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-OnionShare | https://onionshare.org/
-
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
-
-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 <http://www.gnu.org/licenses/>.
-"""
-
-import hmac
-import logging
-import mimetypes
-import os
-import queue
-import socket
-import sys
-import tempfile
-import base64
-from distutils.version import LooseVersion as Version
-from urllib.request import urlopen
-
-from flask import (
- Flask, Response, request, render_template_string, abort, make_response,
- __version__ as flask_version
-)
-
-from . import strings, common
-
-
-def _safe_select_jinja_autoescape(self, filename):
- if filename is None:
- return True
- return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))
-
-# Starting in Flask 0.11, render_template_string autoescapes template variables
-# by default. To prevent content injection through template variables in
-# earlier versions of Flask, we force autoescaping in the Jinja2 template
-# engine if we detect a Flask version with insecure default behavior.
-if Version(flask_version) < Version('0.11'):
- # Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc
- Flask.select_jinja_autoescape = _safe_select_jinja_autoescape
-
-app = Flask(__name__)
-
-# information about the file
-file_info = []
-zip_filename = None
-zip_filesize = None
-
-security_headers = [
- ('Content-Security-Policy', 'default-src \'self\'; style-src \'unsafe-inline\'; script-src \'unsafe-inline\'; img-src \'self\' data:;'),
- ('X-Frame-Options', 'DENY'),
- ('X-Xss-Protection', '1; mode=block'),
- ('X-Content-Type-Options', 'nosniff'),
- ('Referrer-Policy', 'no-referrer'),
- ('Server', 'OnionShare')
-]
-
-
-def set_file_info(filenames, processed_size_callback=None):
- """
- Using the list of filenames being shared, fill in details that the web
- page will need to display. This includes zipping up the file in order to
- get the zip file's name and size.
- """
- global file_info, zip_filename, zip_filesize
-
- # build file info list
- file_info = {'files': [], 'dirs': []}
- for filename in filenames:
- info = {
- 'filename': filename,
- 'basename': os.path.basename(filename.rstrip('/'))
- }
- if os.path.isfile(filename):
- info['size'] = os.path.getsize(filename)
- info['size_human'] = common.human_readable_filesize(info['size'])
- file_info['files'].append(info)
- if os.path.isdir(filename):
- info['size'] = common.dir_size(filename)
- info['size_human'] = common.human_readable_filesize(info['size'])
- file_info['dirs'].append(info)
- file_info['files'] = sorted(file_info['files'], key=lambda k: k['basename'])
- file_info['dirs'] = sorted(file_info['dirs'], key=lambda k: k['basename'])
-
- # zip up the files and folders
- z = common.ZipWriter(processed_size_callback=processed_size_callback)
- for info in file_info['files']:
- z.add_file(info['filename'])
- for info in file_info['dirs']:
- z.add_dir(info['filename'])
- z.close()
- zip_filename = z.zip_filename
- zip_filesize = os.path.getsize(zip_filename)
-
-
-REQUEST_LOAD = 0
-REQUEST_DOWNLOAD = 1
-REQUEST_PROGRESS = 2
-REQUEST_OTHER = 3
-REQUEST_CANCELED = 4
-REQUEST_RATE_LIMIT = 5
-q = queue.Queue()
-
-
-def add_request(request_type, path, data=None):
- """
- Add a request to the queue, to communicate with the GUI.
- """
- global q
- q.put({
- 'type': request_type,
- 'path': path,
- 'data': data
- })
-
-
-# Load and base64 encode images to pass into templates
-favicon_b64 = base64.b64encode(open(common.get_resource_path('images/favicon.ico'), 'rb').read()).decode()
-logo_b64 = base64.b64encode(open(common.get_resource_path('images/logo.png'), 'rb').read()).decode()
-folder_b64 = base64.b64encode(open(common.get_resource_path('images/web_folder.png'), 'rb').read()).decode()
-file_b64 = base64.b64encode(open(common.get_resource_path('images/web_file.png'), 'rb').read()).decode()
-
-slug = None
-
-
-def generate_slug(persistent_slug=''):
- global slug
- if persistent_slug:
- slug = persistent_slug
- else:
- slug = common.build_slug()
-
-download_count = 0
-error404_count = 0
-
-stay_open = False
-
-
-def set_stay_open(new_stay_open):
- """
- Set stay_open variable.
- """
- global stay_open
- stay_open = new_stay_open
-
-
-def get_stay_open():
- """
- Get stay_open variable.
- """
- return stay_open
-
-
-# Are we running in GUI mode?
-gui_mode = False
-
-
-def set_gui_mode():
- """
- Tell the web service that we're running in GUI mode
- """
- global gui_mode
- gui_mode = True
-
-
-def debug_mode():
- """
- Turn on debugging mode, which will log flask errors to a debug file.
-
- This is commented out (it's only needed for debugging, and not needed
- for OnionShare 1.3.2) as a hotfix to resolve this issue:
- https://github.com/micahflee/onionshare/issues/837
- """
- pass
- """
- temp_dir = tempfile.gettempdir()
- log_handler = logging.FileHandler(
- os.path.join(temp_dir, 'onionshare_server.log'))
- log_handler.setLevel(logging.WARNING)
- app.logger.addHandler(log_handler)
- """
-
-
-def check_slug_candidate(slug_candidate, slug_compare=None):
- if not slug_compare:
- slug_compare = slug
- if not hmac.compare_digest(slug_compare, slug_candidate):
- abort(404)
-
-
-# If "Stop After First Download" is checked (stay_open == False), only allow
-# one download at a time.
-download_in_progress = False
-
-done = False
-
-@app.route("/<slug_candidate>")
-def index(slug_candidate):
- """
- Render the template for the onionshare landing page.
- """
- check_slug_candidate(slug_candidate)
-
- add_request(REQUEST_LOAD, request.path)
-
- # Deny new downloads if "Stop After First Download" is checked and there is
- # currently a download
- global stay_open, download_in_progress
- deny_download = not stay_open and download_in_progress
- if deny_download:
- r = make_response(render_template_string(
- open(common.get_resource_path('html/denied.html')).read(),
- favicon_b64=favicon_b64
- ))
- for header, value in security_headers:
- r.headers.set(header, value)
- return r
-
- # If download is allowed to continue, serve download page
-
- r = make_response(render_template_string(
- open(common.get_resource_path('html/index.html')).read(),
- favicon_b64=favicon_b64,
- logo_b64=logo_b64,
- folder_b64=folder_b64,
- file_b64=file_b64,
- slug=slug,
- file_info=file_info,
- filename=os.path.basename(zip_filename),
- filesize=zip_filesize,
- filesize_human=common.human_readable_filesize(zip_filesize)))
- for header, value in security_headers:
- r.headers.set(header, value)
- return r
-
-
-# If the client closes the OnionShare window while a download is in progress,
-# it should immediately stop serving the file. The client_cancel global is
-# used to tell the download function that the client is canceling the download.
-client_cancel = False
-
-
-@app.route("/<slug_candidate>/download")
-def download(slug_candidate):
- """
- Download the zip file.
- """
- check_slug_candidate(slug_candidate)
-
- # Deny new downloads if "Stop After First Download" is checked and there is
- # currently a download
- global stay_open, download_in_progress, done
- deny_download = not stay_open and download_in_progress
- if deny_download:
- r = make_response(render_template_string(
- open(common.get_resource_path('html/denied.html')).read(),
- favicon_b64=favicon_b64
- ))
- for header,value in security_headers:
- r.headers.set(header, value)
- return r
-
- global download_count
-
- # each download has a unique id
- download_id = download_count
- download_count += 1
-
- # prepare some variables to use inside generate() function below
- # which is outside of the request context
- shutdown_func = request.environ.get('werkzeug.server.shutdown')
- path = request.path
-
- # tell GUI the download started
- add_request(REQUEST_DOWNLOAD, path, {'id': download_id})
-
- dirname = os.path.dirname(zip_filename)
- basename = os.path.basename(zip_filename)
-
- def generate():
- # The user hasn't canceled the download
- global client_cancel, gui_mode
- client_cancel = False
-
- # Starting a new download
- global stay_open, download_in_progress, done
- if not stay_open:
- download_in_progress = True
-
- chunk_size = 102400 # 100kb
-
- fp = open(zip_filename, 'rb')
- done = False
- canceled = False
- while not done:
- # The user has canceled the download, so stop serving the file
- if client_cancel:
- add_request(REQUEST_CANCELED, path, {'id': download_id})
- break
-
- chunk = fp.read(chunk_size)
- if chunk == b'':
- done = True
- else:
- try:
- yield chunk
-
- # tell GUI the progress
- downloaded_bytes = fp.tell()
- percent = (1.0 * downloaded_bytes / zip_filesize) * 100
-
- # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304)
- plat = common.get_platform()
- if not gui_mode or plat == 'Linux' or plat == 'BSD':
- sys.stdout.write(
- "\r{0:s}, {1:.2f}% ".format(common.human_readable_filesize(downloaded_bytes), percent))
- sys.stdout.flush()
-
- add_request(REQUEST_PROGRESS, path, {'id': download_id, 'bytes': downloaded_bytes})
- done = False
- except:
- # looks like the download was canceled
- done = True
- canceled = True
-
- # tell the GUI the download has canceled
- add_request(REQUEST_CANCELED, path, {'id': download_id})
-
- fp.close()
-
- if common.get_platform() != 'Darwin':
- sys.stdout.write("\n")
-
- # Download is finished
- if not stay_open:
- download_in_progress = False
-
- # Close the server, if necessary
- if not stay_open and not canceled:
- print(strings._("closing_automatically"))
- if shutdown_func is None:
- raise RuntimeError('Not running with the Werkzeug Server')
- shutdown_func()
-
- r = Response(generate())
- r.headers.set('Content-Length', zip_filesize)
- r.headers.set('Content-Disposition', 'attachment', filename=basename)
- for header,value in security_headers:
- r.headers.set(header, value)
- # guess content type
- (content_type, _) = mimetypes.guess_type(basename, strict=False)
- if content_type is not None:
- r.headers.set('Content-Type', content_type)
- return r
-
-
-@app.errorhandler(404)
-def page_not_found(e):
- """
- 404 error page.
- """
- add_request(REQUEST_OTHER, request.path)
-
- global error404_count
- if request.path != '/favicon.ico':
- error404_count += 1
- if error404_count == 20:
- add_request(REQUEST_RATE_LIMIT, request.path)
- force_shutdown()
- print(strings._('error_rate_limit'))
-
- r = make_response(render_template_string(
- open(common.get_resource_path('html/404.html')).read(),
- favicon_b64=favicon_b64
- ), 404)
- for header, value in security_headers:
- r.headers.set(header, value)
- return r
-
-
-# shutting down the server only works within the context of flask, so the easiest way to do it is over http
-shutdown_slug = common.random_string(16)
-
-
-@app.route("/<slug_candidate>/shutdown")
-def shutdown(slug_candidate):
- """
- Stop the flask web server, from the context of an http request.
- """
- check_slug_candidate(slug_candidate, shutdown_slug)
- force_shutdown()
- return ""
-
-
-def force_shutdown():
- """
- Stop the flask web server, from the context of the flask app.
- """
- # shutdown the flask service
- func = request.environ.get('werkzeug.server.shutdown')
- if func is None:
- raise RuntimeError('Not running with the Werkzeug Server')
- func()
-
-
-def start(port, stay_open=False, persistent_slug=''):
- """
- Start the flask web server.
- """
- generate_slug(persistent_slug)
-
- set_stay_open(stay_open)
-
- # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220)
- if os.path.exists('/usr/share/anon-ws-base-files/workstation'):
- host = '0.0.0.0'
- else:
- host = '127.0.0.1'
-
- app.run(host=host, port=port, threaded=True)
-
-
-def stop(port):
- """
- Stop the flask web server by loading /shutdown.
- """
-
- # If the user cancels the download, let the download function know to stop
- # serving the file
- global client_cancel
- client_cancel = True
-
- # to stop flask, load http://127.0.0.1:<port>/<shutdown_slug>/shutdown
- try:
- s = socket.socket()
- s.connect(('127.0.0.1', port))
- s.sendall('GET /{0:s}/shutdown HTTP/1.1\r\n\r\n'.format(shutdown_slug))
- except:
- try:
- urlopen('http://127.0.0.1:{0:d}/{1:s}/shutdown'.format(port, shutdown_slug)).read()
- except:
- pass
diff --git a/onionshare_gui/alert.py b/onionshare/web/__init__.py
index 75975cfb..d45b4983 100644
--- a/onionshare_gui/alert.py
+++ b/onionshare/web/__init__.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -17,23 +17,5 @@ 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 <http://www.gnu.org/licenses/>.
"""
-from PyQt5 import QtCore, QtWidgets, QtGui
-from onionshare import common
-
-class Alert(QtWidgets.QMessageBox):
- """
- An alert box dialog.
- """
- def __init__(self, message, icon=QtWidgets.QMessageBox.NoIcon, buttons=QtWidgets.QMessageBox.Ok, autostart=True):
- super(Alert, self).__init__(None)
- common.log('Alert', '__init__')
-
- self.setWindowTitle("OnionShare")
- self.setWindowIcon(QtGui.QIcon(common.get_resource_path('images/logo.png')))
- self.setText(message)
- self.setIcon(icon)
- self.setStandardButtons(buttons)
-
- if autostart:
- self.exec_()
+from .web import Web
diff --git a/onionshare/web/receive_mode.py b/onionshare/web/receive_mode.py
new file mode 100644
index 00000000..6985f38a
--- /dev/null
+++ b/onionshare/web/receive_mode.py
@@ -0,0 +1,343 @@
+import os
+import tempfile
+from datetime import datetime
+from flask import Request, request, render_template, make_response, flash, redirect
+from werkzeug.utils import secure_filename
+
+from .. import strings
+
+
+class ReceiveModeWeb(object):
+ """
+ All of the web logic for receive mode
+ """
+ def __init__(self, common, web):
+ self.common = common
+ self.common.log('ReceiveModeWeb', '__init__')
+
+ self.web = web
+
+ self.can_upload = True
+ self.upload_count = 0
+ self.uploads_in_progress = []
+
+ self.define_routes()
+
+ def define_routes(self):
+ """
+ The web app routes for receiving files
+ """
+ def index_logic():
+ self.web.add_request(self.web.REQUEST_LOAD, request.path)
+
+ if self.common.settings.get('public_mode'):
+ upload_action = '/upload'
+ else:
+ upload_action = '/{}/upload'.format(self.web.slug)
+
+ r = make_response(render_template(
+ 'receive.html',
+ upload_action=upload_action))
+ return self.web.add_security_headers(r)
+
+ @self.web.app.route("/<slug_candidate>")
+ def index(slug_candidate):
+ if not self.can_upload:
+ return self.web.error403()
+ self.web.check_slug_candidate(slug_candidate)
+ return index_logic()
+
+ @self.web.app.route("/")
+ def index_public():
+ if not self.can_upload:
+ return self.web.error403()
+ if not self.common.settings.get('public_mode'):
+ return self.web.error404()
+ return index_logic()
+
+
+ def upload_logic(slug_candidate=''):
+ """
+ Upload files.
+ """
+ # Make sure the receive mode dir exists
+ now = datetime.now()
+ date_dir = now.strftime("%Y-%m-%d")
+ time_dir = now.strftime("%H.%M.%S")
+ receive_mode_dir = os.path.join(self.common.settings.get('downloads_dir'), date_dir, time_dir)
+ valid = True
+ try:
+ os.makedirs(receive_mode_dir, 0o700)
+ except PermissionError:
+ self.web.add_request(self.web.REQUEST_ERROR_DOWNLOADS_DIR_CANNOT_CREATE, request.path, {
+ "receive_mode_dir": receive_mode_dir
+ })
+ print(strings._('error_cannot_create_downloads_dir').format(receive_mode_dir))
+ valid = False
+ if not valid:
+ flash('Error uploading, please inform the OnionShare user', 'error')
+ if self.common.settings.get('public_mode'):
+ return redirect('/')
+ else:
+ return redirect('/{}'.format(slug_candidate))
+
+ files = request.files.getlist('file[]')
+ filenames = []
+ print('')
+ for f in files:
+ if f.filename != '':
+ # Automatically rename the file, if a file of the same name already exists
+ filename = secure_filename(f.filename)
+ filenames.append(filename)
+ local_path = os.path.join(receive_mode_dir, filename)
+ if os.path.exists(local_path):
+ if '.' in filename:
+ # Add "-i", e.g. change "foo.txt" to "foo-2.txt"
+ parts = filename.split('.')
+ name = parts[:-1]
+ ext = parts[-1]
+
+ i = 2
+ valid = False
+ while not valid:
+ new_filename = '{}-{}.{}'.format('.'.join(name), i, ext)
+ local_path = os.path.join(receive_mode_dir, new_filename)
+ if os.path.exists(local_path):
+ i += 1
+ else:
+ valid = True
+ else:
+ # If no extension, just add "-i", e.g. change "foo" to "foo-2"
+ i = 2
+ valid = False
+ while not valid:
+ new_filename = '{}-{}'.format(filename, i)
+ local_path = os.path.join(receive_mode_dir, new_filename)
+ if os.path.exists(local_path):
+ i += 1
+ else:
+ valid = True
+
+ basename = os.path.basename(local_path)
+ if f.filename != basename:
+ # Tell the GUI that the file has changed names
+ self.web.add_request(self.web.REQUEST_UPLOAD_FILE_RENAMED, request.path, {
+ 'id': request.upload_id,
+ 'old_filename': f.filename,
+ 'new_filename': basename
+ })
+
+ # Tell the GUI the receive mode directory for this file
+ self.web.add_request(self.web.REQUEST_UPLOAD_SET_DIR, request.path, {
+ 'id': request.upload_id,
+ 'filename': basename,
+ 'dir': receive_mode_dir
+ })
+
+ self.common.log('ReceiveModeWeb', 'define_routes', '/upload, uploaded {}, saving to {}'.format(f.filename, local_path))
+ print(strings._('receive_mode_received_file').format(local_path))
+ f.save(local_path)
+
+ # Note that flash strings are on English, and not translated, on purpose,
+ # to avoid leaking the locale of the OnionShare user
+ if len(filenames) == 0:
+ flash('No files uploaded', 'info')
+ else:
+ for filename in filenames:
+ flash('Sent {}'.format(filename), 'info')
+
+ if self.can_upload:
+ if self.common.settings.get('public_mode'):
+ path = '/'
+ else:
+ path = '/{}'.format(slug_candidate)
+
+ return redirect('{}'.format(path))
+ else:
+ # It was the last upload and the timer ran out
+ if self.common.settings.get('public_mode'):
+ return thankyou_logic(slug_candidate)
+ else:
+ return thankyou_logic()
+
+ def thankyou_logic(slug_candidate=''):
+ r = make_response(render_template(
+ 'thankyou.html'))
+ return self.web.add_security_headers(r)
+
+ @self.web.app.route("/<slug_candidate>/upload", methods=['POST'])
+ def upload(slug_candidate):
+ if not self.can_upload:
+ return self.web.error403()
+ self.web.check_slug_candidate(slug_candidate)
+ return upload_logic(slug_candidate)
+
+ @self.web.app.route("/upload", methods=['POST'])
+ def upload_public():
+ if not self.can_upload:
+ return self.web.error403()
+ if not self.common.settings.get('public_mode'):
+ return self.web.error404()
+ return upload_logic()
+
+
+
+class ReceiveModeWSGIMiddleware(object):
+ """
+ Custom WSGI middleware in order to attach the Web object to environ, so
+ ReceiveModeRequest can access it.
+ """
+ def __init__(self, app, web):
+ self.app = app
+ self.web = web
+
+ def __call__(self, environ, start_response):
+ environ['web'] = self.web
+ return self.app(environ, start_response)
+
+
+class ReceiveModeTemporaryFile(object):
+ """
+ A custom TemporaryFile that tells ReceiveModeRequest every time data gets
+ written to it, in order to track the progress of uploads.
+ """
+ def __init__(self, filename, write_func, close_func):
+ self.onionshare_filename = filename
+ self.onionshare_write_func = write_func
+ self.onionshare_close_func = close_func
+
+ # Create a temporary file
+ self.f = tempfile.TemporaryFile('wb+')
+
+ # Make all the file-like methods and attributes actually access the
+ # TemporaryFile, except for write
+ attrs = ['closed', 'detach', 'fileno', 'flush', 'isatty', 'mode',
+ 'name', 'peek', 'raw', 'read', 'read1', 'readable', 'readinto',
+ 'readinto1', 'readline', 'readlines', 'seek', 'seekable', 'tell',
+ 'truncate', 'writable', 'writelines']
+ for attr in attrs:
+ setattr(self, attr, getattr(self.f, attr))
+
+ def write(self, b):
+ """
+ Custom write method that calls out to onionshare_write_func
+ """
+ bytes_written = self.f.write(b)
+ self.onionshare_write_func(self.onionshare_filename, bytes_written)
+
+ def close(self):
+ """
+ Custom close method that calls out to onionshare_close_func
+ """
+ self.f.close()
+ self.onionshare_close_func(self.onionshare_filename)
+
+
+class ReceiveModeRequest(Request):
+ """
+ A custom flask Request object that keeps track of how much data has been
+ uploaded for each file, for receive mode.
+ """
+ def __init__(self, environ, populate_request=True, shallow=False):
+ super(ReceiveModeRequest, self).__init__(environ, populate_request, shallow)
+ self.web = environ['web']
+
+ # Is this a valid upload request?
+ self.upload_request = False
+ if self.method == 'POST':
+ if self.path == '/{}/upload'.format(self.web.slug):
+ self.upload_request = True
+ else:
+ if self.web.common.settings.get('public_mode'):
+ if self.path == '/upload':
+ self.upload_request = True
+
+ if self.upload_request:
+ # A dictionary that maps filenames to the bytes uploaded so far
+ self.progress = {}
+
+ # Prevent new uploads if we've said so (timer expired)
+ if self.web.receive_mode.can_upload:
+
+ # Create an upload_id, attach it to the request
+ self.upload_id = self.web.receive_mode.upload_count
+
+ self.web.receive_mode.upload_count += 1
+
+ # Figure out the content length
+ try:
+ self.content_length = int(self.headers['Content-Length'])
+ except:
+ self.content_length = 0
+
+ print("{}: {}".format(
+ datetime.now().strftime("%b %d, %I:%M%p"),
+ strings._("receive_mode_upload_starting").format(self.web.common.human_readable_filesize(self.content_length))
+ ))
+
+ # Tell the GUI
+ self.web.add_request(self.web.REQUEST_STARTED, self.path, {
+ 'id': self.upload_id,
+ 'content_length': self.content_length
+ })
+
+ self.web.receive_mode.uploads_in_progress.append(self.upload_id)
+
+ self.previous_file = None
+
+ def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None):
+ """
+ This gets called for each file that gets uploaded, and returns an file-like
+ writable stream.
+ """
+ if self.upload_request:
+ self.progress[filename] = {
+ 'uploaded_bytes': 0,
+ 'complete': False
+ }
+
+ return ReceiveModeTemporaryFile(filename, self.file_write_func, self.file_close_func)
+
+ def close(self):
+ """
+ Closing the request.
+ """
+ super(ReceiveModeRequest, self).close()
+ try:
+ upload_id = self.upload_id
+ # Inform the GUI that the upload has finished
+ self.web.add_request(self.web.REQUEST_UPLOAD_FINISHED, self.path, {
+ 'id': upload_id
+ })
+ self.web.receive_mode.uploads_in_progress.remove(upload_id)
+ except AttributeError:
+ pass
+
+ def file_write_func(self, filename, length):
+ """
+ This function gets called when a specific file is written to.
+ """
+ if self.upload_request:
+ self.progress[filename]['uploaded_bytes'] += length
+
+ if self.previous_file != filename:
+ if self.previous_file is not None:
+ print('')
+ self.previous_file = filename
+
+ print('\r=> {:15s} {}'.format(
+ self.web.common.human_readable_filesize(self.progress[filename]['uploaded_bytes']),
+ filename
+ ), end='')
+
+ # Update the GUI on the upload progress
+ self.web.add_request(self.web.REQUEST_PROGRESS, self.path, {
+ 'id': self.upload_id,
+ 'progress': self.progress
+ })
+
+ def file_close_func(self, filename):
+ """
+ This function gets called when a specific file is closed.
+ """
+ self.progress[filename]['complete'] = True
diff --git a/onionshare/web/share_mode.py b/onionshare/web/share_mode.py
new file mode 100644
index 00000000..a57d0a39
--- /dev/null
+++ b/onionshare/web/share_mode.py
@@ -0,0 +1,384 @@
+import os
+import sys
+import tempfile
+import zipfile
+import mimetypes
+import gzip
+from flask import Response, request, render_template, make_response
+
+from .. import strings
+
+
+class ShareModeWeb(object):
+ """
+ All of the web logic for share mode
+ """
+ def __init__(self, common, web):
+ self.common = common
+ self.common.log('ShareModeWeb', '__init__')
+
+ self.web = web
+
+ # Information about the file to be shared
+ self.file_info = []
+ self.is_zipped = False
+ self.download_filename = None
+ self.download_filesize = None
+ self.gzip_filename = None
+ self.gzip_filesize = None
+ self.zip_writer = None
+
+ self.download_count = 0
+
+ # If "Stop After First Download" is checked (stay_open == False), only allow
+ # one download at a time.
+ self.download_in_progress = False
+
+ # If the client closes the OnionShare window while a download is in progress,
+ # it should immediately stop serving the file. The client_cancel global is
+ # used to tell the download function that the client is canceling the download.
+ self.client_cancel = False
+
+ self.define_routes()
+
+ def define_routes(self):
+ """
+ The web app routes for sharing files
+ """
+ @self.web.app.route("/<slug_candidate>")
+ def index(slug_candidate):
+ self.web.check_slug_candidate(slug_candidate)
+ return index_logic()
+
+ @self.web.app.route("/")
+ def index_public():
+ if not self.common.settings.get('public_mode'):
+ return self.web.error404()
+ return index_logic()
+
+ def index_logic(slug_candidate=''):
+ """
+ Render the template for the onionshare landing page.
+ """
+ self.web.add_request(self.web.REQUEST_LOAD, request.path)
+
+ # Deny new downloads if "Stop After First Download" is checked and there is
+ # currently a download
+ deny_download = not self.web.stay_open and self.download_in_progress
+ if deny_download:
+ r = make_response(render_template('denied.html'))
+ return self.web.add_security_headers(r)
+
+ # If download is allowed to continue, serve download page
+ if self.should_use_gzip():
+ self.filesize = self.gzip_filesize
+ else:
+ self.filesize = self.download_filesize
+
+ if self.web.slug:
+ r = make_response(render_template(
+ 'send.html',
+ slug=self.web.slug,
+ file_info=self.file_info,
+ filename=os.path.basename(self.download_filename),
+ filesize=self.filesize,
+ filesize_human=self.common.human_readable_filesize(self.download_filesize),
+ is_zipped=self.is_zipped))
+ else:
+ # If download is allowed to continue, serve download page
+ r = make_response(render_template(
+ 'send.html',
+ file_info=self.file_info,
+ filename=os.path.basename(self.download_filename),
+ filesize=self.filesize,
+ filesize_human=self.common.human_readable_filesize(self.download_filesize),
+ is_zipped=self.is_zipped))
+ return self.web.add_security_headers(r)
+
+ @self.web.app.route("/<slug_candidate>/download")
+ def download(slug_candidate):
+ self.web.check_slug_candidate(slug_candidate)
+ return download_logic()
+
+ @self.web.app.route("/download")
+ def download_public():
+ if not self.common.settings.get('public_mode'):
+ return self.web.error404()
+ return download_logic()
+
+ def download_logic(slug_candidate=''):
+ """
+ Download the zip file.
+ """
+ # Deny new downloads if "Stop After First Download" is checked and there is
+ # currently a download
+ deny_download = not self.web.stay_open and self.download_in_progress
+ if deny_download:
+ r = make_response(render_template('denied.html'))
+ return self.web.add_security_headers(r)
+
+ # Each download has a unique id
+ download_id = self.download_count
+ self.download_count += 1
+
+ # Prepare some variables to use inside generate() function below
+ # which is outside of the request context
+ shutdown_func = request.environ.get('werkzeug.server.shutdown')
+ path = request.path
+
+ # If this is a zipped file, then serve as-is. If it's not zipped, then,
+ # if the http client supports gzip compression, gzip the file first
+ # and serve that
+ use_gzip = self.should_use_gzip()
+ if use_gzip:
+ file_to_download = self.gzip_filename
+ self.filesize = self.gzip_filesize
+ else:
+ file_to_download = self.download_filename
+ self.filesize = self.download_filesize
+
+ # Tell GUI the download started
+ self.web.add_request(self.web.REQUEST_STARTED, path, {
+ 'id': download_id,
+ 'use_gzip': use_gzip
+ })
+
+ basename = os.path.basename(self.download_filename)
+
+ def generate():
+ # The user hasn't canceled the download
+ self.client_cancel = False
+
+ # Starting a new download
+ if not self.web.stay_open:
+ self.download_in_progress = True
+
+ chunk_size = 102400 # 100kb
+
+ fp = open(file_to_download, 'rb')
+ self.web.done = False
+ canceled = False
+ while not self.web.done:
+ # The user has canceled the download, so stop serving the file
+ if self.client_cancel:
+ self.web.add_request(self.web.REQUEST_CANCELED, path, {
+ 'id': download_id
+ })
+ break
+
+ chunk = fp.read(chunk_size)
+ if chunk == b'':
+ self.web.done = True
+ else:
+ try:
+ yield chunk
+
+ # tell GUI the progress
+ downloaded_bytes = fp.tell()
+ percent = (1.0 * downloaded_bytes / self.filesize) * 100
+
+ # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304)
+ if not self.web.is_gui or self.common.platform == 'Linux' or self.common.platform == 'BSD':
+ sys.stdout.write(
+ "\r{0:s}, {1:.2f}% ".format(self.common.human_readable_filesize(downloaded_bytes), percent))
+ sys.stdout.flush()
+
+ self.web.add_request(self.web.REQUEST_PROGRESS, path, {
+ 'id': download_id,
+ 'bytes': downloaded_bytes
+ })
+ self.web.done = False
+ except:
+ # looks like the download was canceled
+ self.web.done = True
+ canceled = True
+
+ # tell the GUI the download has canceled
+ self.web.add_request(self.web.REQUEST_CANCELED, path, {
+ 'id': download_id
+ })
+
+ fp.close()
+
+ if self.common.platform != 'Darwin':
+ sys.stdout.write("\n")
+
+ # Download is finished
+ if not self.web.stay_open:
+ self.download_in_progress = False
+
+ # Close the server, if necessary
+ if not self.web.stay_open and not canceled:
+ print(strings._("closing_automatically"))
+ self.web.running = False
+ try:
+ if shutdown_func is None:
+ raise RuntimeError('Not running with the Werkzeug Server')
+ shutdown_func()
+ except:
+ pass
+
+ r = Response(generate())
+ if use_gzip:
+ r.headers.set('Content-Encoding', 'gzip')
+ r.headers.set('Content-Length', self.filesize)
+ r.headers.set('Content-Disposition', 'attachment', filename=basename)
+ r = self.web.add_security_headers(r)
+ # guess content type
+ (content_type, _) = mimetypes.guess_type(basename, strict=False)
+ if content_type is not None:
+ r.headers.set('Content-Type', content_type)
+ return r
+
+ def set_file_info(self, filenames, processed_size_callback=None):
+ """
+ Using the list of filenames being shared, fill in details that the web
+ page will need to display. This includes zipping up the file in order to
+ get the zip file's name and size.
+ """
+ self.common.log("ShareModeWeb", "set_file_info")
+ self.web.cancel_compression = False
+
+ self.cleanup_filenames = []
+
+ # build file info list
+ self.file_info = {'files': [], 'dirs': []}
+ for filename in filenames:
+ info = {
+ 'filename': filename,
+ 'basename': os.path.basename(filename.rstrip('/'))
+ }
+ if os.path.isfile(filename):
+ info['size'] = os.path.getsize(filename)
+ info['size_human'] = self.common.human_readable_filesize(info['size'])
+ self.file_info['files'].append(info)
+ if os.path.isdir(filename):
+ info['size'] = self.common.dir_size(filename)
+ info['size_human'] = self.common.human_readable_filesize(info['size'])
+ self.file_info['dirs'].append(info)
+ 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'])
+
+ # Check if there's only 1 file and no folders
+ if len(self.file_info['files']) == 1 and len(self.file_info['dirs']) == 0:
+ self.download_filename = self.file_info['files'][0]['filename']
+ self.download_filesize = self.file_info['files'][0]['size']
+
+ # Compress the file with gzip now, so we don't have to do it on each request
+ self.gzip_filename = tempfile.mkstemp('wb+')[1]
+ self._gzip_compress(self.download_filename, self.gzip_filename, 6, processed_size_callback)
+ self.gzip_filesize = os.path.getsize(self.gzip_filename)
+
+ # Make sure the gzip file gets cleaned up when onionshare stops
+ self.cleanup_filenames.append(self.gzip_filename)
+
+ self.is_zipped = False
+
+ else:
+ # Zip up the files and folders
+ self.zip_writer = ZipWriter(self.common, processed_size_callback=processed_size_callback)
+ self.download_filename = self.zip_writer.zip_filename
+ for info in self.file_info['files']:
+ self.zip_writer.add_file(info['filename'])
+ # Canceling early?
+ if self.web.cancel_compression:
+ self.zip_writer.close()
+ return False
+
+ for info in self.file_info['dirs']:
+ if not self.zip_writer.add_dir(info['filename']):
+ return False
+
+ self.zip_writer.close()
+ self.download_filesize = os.path.getsize(self.download_filename)
+
+ # Make sure the zip file gets cleaned up when onionshare stops
+ self.cleanup_filenames.append(self.zip_writer.zip_filename)
+
+ self.is_zipped = True
+
+ return True
+
+ def should_use_gzip(self):
+ """
+ Should we use gzip for this browser?
+ """
+ return (not self.is_zipped) and ('gzip' in request.headers.get('Accept-Encoding', '').lower())
+
+ def _gzip_compress(self, input_filename, output_filename, level, processed_size_callback=None):
+ """
+ Compress a file with gzip, without loading the whole thing into memory
+ Thanks: https://stackoverflow.com/questions/27035296/python-how-to-gzip-a-large-text-file-without-memoryerror
+ """
+ bytes_processed = 0
+ blocksize = 1 << 16 # 64kB
+ with open(input_filename, 'rb') as input_file:
+ output_file = gzip.open(output_filename, 'wb', level)
+ while True:
+ if processed_size_callback is not None:
+ processed_size_callback(bytes_processed)
+
+ block = input_file.read(blocksize)
+ if len(block) == 0:
+ break
+ output_file.write(block)
+ bytes_processed += blocksize
+
+ output_file.close()
+
+
+class ZipWriter(object):
+ """
+ ZipWriter accepts files and directories and compresses them into a zip file
+ with. If a zip_filename is not passed in, it will use the default onionshare
+ filename.
+ """
+ def __init__(self, common, zip_filename=None, processed_size_callback=None):
+ self.common = common
+ self.cancel_compression = False
+
+ if zip_filename:
+ self.zip_filename = zip_filename
+ else:
+ self.zip_filename = '{0:s}/onionshare_{1:s}.zip'.format(tempfile.mkdtemp(), self.common.random_string(4, 6))
+
+ self.z = zipfile.ZipFile(self.zip_filename, 'w', allowZip64=True)
+ self.processed_size_callback = processed_size_callback
+ if self.processed_size_callback is None:
+ self.processed_size_callback = lambda _: None
+ self._size = 0
+ self.processed_size_callback(self._size)
+
+ def add_file(self, filename):
+ """
+ Add a file to the zip archive.
+ """
+ self.z.write(filename, os.path.basename(filename), zipfile.ZIP_DEFLATED)
+ self._size += os.path.getsize(filename)
+ self.processed_size_callback(self._size)
+
+ def add_dir(self, filename):
+ """
+ Add a directory, and all of its children, to the zip archive.
+ """
+ dir_to_strip = os.path.dirname(filename.rstrip('/'))+'/'
+ for dirpath, dirnames, filenames in os.walk(filename):
+ for f in filenames:
+ # Canceling early?
+ if self.cancel_compression:
+ return False
+
+ full_filename = os.path.join(dirpath, f)
+ if not os.path.islink(full_filename):
+ arc_filename = full_filename[len(dir_to_strip):]
+ self.z.write(full_filename, arc_filename, zipfile.ZIP_DEFLATED)
+ self._size += os.path.getsize(full_filename)
+ self.processed_size_callback(self._size)
+
+ return True
+
+ def close(self):
+ """
+ Close the zip archive.
+ """
+ self.z.close()
diff --git a/onionshare/web/web.py b/onionshare/web/web.py
new file mode 100644
index 00000000..21e9cd8f
--- /dev/null
+++ b/onionshare/web/web.py
@@ -0,0 +1,269 @@
+import hmac
+import logging
+import os
+import queue
+import socket
+import sys
+import tempfile
+from distutils.version import LooseVersion as Version
+from urllib.request import urlopen
+
+import flask
+from flask import Flask, request, render_template, abort, make_response, __version__ as flask_version
+
+from .. import strings
+
+from .share_mode import ShareModeWeb
+from .receive_mode import ReceiveModeWeb, ReceiveModeWSGIMiddleware, ReceiveModeTemporaryFile, ReceiveModeRequest
+
+
+# Stub out flask's show_server_banner function, to avoiding showing warnings that
+# are not applicable to OnionShare
+def stubbed_show_server_banner(env, debug, app_import_path, eager_loading):
+ pass
+
+flask.cli.show_server_banner = stubbed_show_server_banner
+
+
+class Web(object):
+ """
+ The Web object is the OnionShare web server, powered by flask
+ """
+ REQUEST_LOAD = 0
+ REQUEST_STARTED = 1
+ REQUEST_PROGRESS = 2
+ REQUEST_OTHER = 3
+ REQUEST_CANCELED = 4
+ REQUEST_RATE_LIMIT = 5
+ REQUEST_CLOSE_SERVER = 6
+ REQUEST_UPLOAD_FILE_RENAMED = 7
+ REQUEST_UPLOAD_SET_DIR = 8
+ REQUEST_UPLOAD_FINISHED = 9
+ REQUEST_ERROR_DOWNLOADS_DIR_CANNOT_CREATE = 10
+
+ def __init__(self, common, is_gui, mode='share'):
+ self.common = common
+ self.common.log('Web', '__init__', 'is_gui={}, mode={}'.format(is_gui, mode))
+
+ # The flask app
+ self.app = Flask(__name__,
+ static_folder=self.common.get_resource_path('static'),
+ template_folder=self.common.get_resource_path('templates'))
+ self.app.secret_key = self.common.random_string(8)
+
+ # Debug mode?
+ if self.common.debug:
+ self.debug_mode()
+
+ # Are we running in GUI mode?
+ self.is_gui = is_gui
+
+ # Are we using receive mode?
+ self.mode = mode
+ if self.mode == 'receive':
+ # Use custom WSGI middleware, to modify environ
+ self.app.wsgi_app = ReceiveModeWSGIMiddleware(self.app.wsgi_app, self)
+ # Use a custom Request class to track upload progess
+ self.app.request_class = ReceiveModeRequest
+
+ # Starting in Flask 0.11, render_template_string autoescapes template variables
+ # by default. To prevent content injection through template variables in
+ # earlier versions of Flask, we force autoescaping in the Jinja2 template
+ # engine if we detect a Flask version with insecure default behavior.
+ if Version(flask_version) < Version('0.11'):
+ # Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc
+ Flask.select_jinja_autoescape = self._safe_select_jinja_autoescape
+
+ self.security_headers = [
+ ('Content-Security-Policy', 'default-src \'self\'; style-src \'self\'; script-src \'self\'; img-src \'self\' data:;'),
+ ('X-Frame-Options', 'DENY'),
+ ('X-Xss-Protection', '1; mode=block'),
+ ('X-Content-Type-Options', 'nosniff'),
+ ('Referrer-Policy', 'no-referrer'),
+ ('Server', 'OnionShare')
+ ]
+
+ self.q = queue.Queue()
+ self.slug = None
+ self.error404_count = 0
+
+ self.done = False
+
+ # shutting down the server only works within the context of flask, so the easiest way to do it is over http
+ self.shutdown_slug = self.common.random_string(16)
+
+ # Keep track if the server is running
+ self.running = False
+
+ # Define the web app routes
+ self.define_common_routes()
+
+ # Create the mode web object, which defines its own routes
+ self.share_mode = None
+ self.receive_mode = None
+ if self.mode == 'receive':
+ self.receive_mode = ReceiveModeWeb(self.common, self)
+ elif self.mode == 'share':
+ self.share_mode = ShareModeWeb(self.common, self)
+
+
+ def define_common_routes(self):
+ """
+ Common web app routes between sending and receiving
+ """
+ @self.app.errorhandler(404)
+ def page_not_found(e):
+ """
+ 404 error page.
+ """
+ return self.error404()
+
+ @self.app.route("/<slug_candidate>/shutdown")
+ def shutdown(slug_candidate):
+ """
+ Stop the flask web server, from the context of an http request.
+ """
+ self.check_shutdown_slug_candidate(slug_candidate)
+ self.force_shutdown()
+ return ""
+
+ def error404(self):
+ self.add_request(Web.REQUEST_OTHER, request.path)
+ if request.path != '/favicon.ico':
+ self.error404_count += 1
+
+ # In receive mode, with public mode enabled, skip rate limiting 404s
+ if not self.common.settings.get('public_mode'):
+ if self.error404_count == 20:
+ self.add_request(Web.REQUEST_RATE_LIMIT, request.path)
+ self.force_shutdown()
+ print(strings._('error_rate_limit'))
+
+ r = make_response(render_template('404.html'), 404)
+ return self.add_security_headers(r)
+
+ def error403(self):
+ self.add_request(Web.REQUEST_OTHER, request.path)
+
+ r = make_response(render_template('403.html'), 403)
+ return self.add_security_headers(r)
+
+ def add_security_headers(self, r):
+ """
+ Add security headers to a request
+ """
+ for header, value in self.security_headers:
+ r.headers.set(header, value)
+ return r
+
+ def _safe_select_jinja_autoescape(self, filename):
+ if filename is None:
+ return True
+ return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))
+
+ def add_request(self, request_type, path, data=None):
+ """
+ Add a request to the queue, to communicate with the GUI.
+ """
+ self.q.put({
+ 'type': request_type,
+ 'path': path,
+ 'data': data
+ })
+
+ def generate_slug(self, persistent_slug=None):
+ self.common.log('Web', 'generate_slug', 'persistent_slug={}'.format(persistent_slug))
+ if persistent_slug != None and persistent_slug != '':
+ self.slug = persistent_slug
+ self.common.log('Web', 'generate_slug', 'persistent_slug sent, so slug is: "{}"'.format(self.slug))
+ else:
+ self.slug = self.common.build_slug()
+ self.common.log('Web', 'generate_slug', 'built random slug: "{}"'.format(self.slug))
+
+ def debug_mode(self):
+ """
+ Turn on debugging mode, which will log flask errors to a debug file.
+ """
+ if self.common.platform == 'Windows':
+ try:
+ appdata = os.environ['APPDATA']
+ flask_debug_filename = '{}\\OnionShare\\flask_debug.log'.format(appdata)
+ except:
+ # If for some reason we don't have the 'APPDATA' environment variable
+ # (like running tests in Linux while pretending to be in Windows)
+ flask_debug_filename = os.path.expanduser('~/.config/onionshare/flask_debug.log')
+ elif self.common.platform == 'Darwin':
+ flask_debug_filename = os.path.expanduser('~/Library/Application Support/OnionShare/flask_debug.log')
+ else:
+ flask_debug_filename = os.path.expanduser('~/.config/onionshare/flask_debug.log')
+
+ log_handler = logging.FileHandler(flask_debug_filename)
+ log_handler.setLevel(logging.WARNING)
+ self.app.logger.addHandler(log_handler)
+
+ def check_slug_candidate(self, slug_candidate):
+ self.common.log('Web', 'check_slug_candidate: slug_candidate={}'.format(slug_candidate))
+ if self.common.settings.get('public_mode'):
+ abort(404)
+ if not hmac.compare_digest(self.slug, slug_candidate):
+ abort(404)
+
+ def check_shutdown_slug_candidate(self, slug_candidate):
+ self.common.log('Web', 'check_shutdown_slug_candidate: slug_candidate={}'.format(slug_candidate))
+ if not hmac.compare_digest(self.shutdown_slug, slug_candidate):
+ abort(404)
+
+ def force_shutdown(self):
+ """
+ Stop the flask web server, from the context of the flask app.
+ """
+ # Shutdown the flask service
+ try:
+ func = request.environ.get('werkzeug.server.shutdown')
+ if func is None:
+ raise RuntimeError('Not running with the Werkzeug Server')
+ func()
+ except:
+ pass
+ self.running = False
+
+ def start(self, port, stay_open=False, public_mode=False, persistent_slug=None):
+ """
+ Start the flask web server.
+ """
+ self.common.log('Web', 'start', 'port={}, stay_open={}, public_mode={}, persistent_slug={}'.format(port, stay_open, public_mode, persistent_slug))
+ if not public_mode:
+ self.generate_slug(persistent_slug)
+
+ self.stay_open = stay_open
+
+ # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220)
+ if os.path.exists('/usr/share/anon-ws-base-files/workstation'):
+ host = '0.0.0.0'
+ else:
+ host = '127.0.0.1'
+
+ self.running = True
+ self.app.run(host=host, port=port, threaded=True)
+
+ def stop(self, port):
+ """
+ Stop the flask web server by loading /shutdown.
+ """
+
+ if self.mode == 'share':
+ # If the user cancels the download, let the download function know to stop
+ # serving the file
+ self.share_mode.client_cancel = True
+
+ # To stop flask, load http://127.0.0.1:<port>/<shutdown_slug>/shutdown
+ if self.running:
+ try:
+ s = socket.socket()
+ s.connect(('127.0.0.1', port))
+ s.sendall('GET /{0:s}/shutdown HTTP/1.1\r\n\r\n'.format(self.shutdown_slug))
+ except:
+ try:
+ urlopen('http://127.0.0.1:{0:d}/{1:s}/shutdown'.format(port, self.shutdown_slug)).read()
+ except:
+ pass
diff --git a/onionshare_gui/__init__.py b/onionshare_gui/__init__.py
index 5350fe29..675bb52d 100644
--- a/onionshare_gui/__init__.py
+++ b/onionshare_gui/__init__.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -18,14 +18,18 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import division
-import os, sys, platform, argparse
-from .alert import Alert
+import os
+import sys
+import platform
+import argparse
+import signal
+from .widgets import Alert
from PyQt5 import QtCore, QtWidgets
-from onionshare import strings, common, web
+from onionshare import strings
+from onionshare.common import Common
from onionshare.onion import Onion
from onionshare.onionshare import OnionShare
-from onionshare.settings import Settings
from .onionshare_gui import OnionShareGui
@@ -34,9 +38,8 @@ class Application(QtWidgets.QApplication):
This is Qt's QApplication class. It has been overridden to support threads
and the quick keyboard shortcut.
"""
- def __init__(self):
- system = common.get_platform()
- if system == 'Linux' or system == 'BSD':
+ def __init__(self, common):
+ if common.platform == 'Linux' or common.platform == 'BSD':
self.setAttribute(QtCore.Qt.AA_X11InitThreads, True)
QtWidgets.QApplication.__init__(self, sys.argv)
self.installEventFilter(self)
@@ -53,18 +56,31 @@ def main():
"""
The main() function implements all of the logic that the GUI version of onionshare uses.
"""
+ common = Common()
+ common.define_css()
+
+ # Load the default settings and strings early, for the sake of being able to parse options.
+ # These won't be in the user's chosen locale necessarily, but we need to parse them
+ # early in order to even display the option to pass alternate settings (which might
+ # contain a preferred locale).
+ # If an alternate --config is passed, we'll reload strings later.
+ common.load_settings()
strings.load_strings(common)
- print(strings._('version_string').format(common.get_version()))
+
+ # Display OnionShare banner
+ print(strings._('version_string').format(common.version))
+
+ # Allow Ctrl-C to smoothly quit the program instead of throwing an exception
+ # https://stackoverflow.com/questions/42814093/how-to-handle-ctrlc-in-python-app-with-pyqt
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
# Start the Qt app
global qtapp
- qtapp = Application()
+ qtapp = Application(common)
# Parse arguments
parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=48))
parser.add_argument('--local-only', action='store_true', dest='local_only', help=strings._("help_local_only"))
- parser.add_argument('--stay-open', action='store_true', dest='stay_open', help=strings._("help_stay_open"))
- parser.add_argument('--shutdown-timeout', metavar='<int>', dest='shutdown_timeout', default=0, help=strings._("help_shutdown_timeout"))
parser.add_argument('--debug', action='store_true', dest='debug', help=strings._("help_debug"))
parser.add_argument('--filenames', metavar='filenames', nargs='+', help=strings._('help_filename'))
parser.add_argument('--config', metavar='config', default=False, help=strings._('help_config'))
@@ -76,39 +92,38 @@ def main():
filenames[i] = os.path.abspath(filenames[i])
config = args.config
+ if config:
+ # Re-load the strings, in case the provided config has changed locale
+ common.load_settings(config)
+ strings.load_strings(common)
local_only = bool(args.local_only)
- stay_open = bool(args.stay_open)
- shutdown_timeout = int(args.shutdown_timeout)
debug = bool(args.debug)
# Debug mode?
- if debug:
- common.set_debug(debug)
- web.debug_mode()
+ common.debug = debug
# Validation
if filenames:
valid = True
for filename in filenames:
if not os.path.isfile(filename) and not os.path.isdir(filename):
- Alert(strings._("not_a_file", True).format(filename))
+ Alert(common, strings._("not_a_file").format(filename))
valid = False
if not os.access(filename, os.R_OK):
- Alert(strings._("not_a_readable_file", True).format(filename))
+ Alert(common, strings._("not_a_readable_file").format(filename))
valid = False
if not valid:
sys.exit()
# Start the Onion
- onion = Onion()
+ onion = Onion(common)
# Start the OnionShare app
- web.set_stay_open(stay_open)
- app = OnionShare(onion, local_only, stay_open, shutdown_timeout)
+ app = OnionShare(common, onion, local_only)
# Launch the gui
- gui = OnionShareGui(onion, qtapp, app, filenames, config)
+ gui = OnionShareGui(common, onion, qtapp, app, filenames, config, local_only)
# Clean up when app quits
def shutdown():
diff --git a/onionshare_gui/downloads.py b/onionshare_gui/downloads.py
deleted file mode 100644
index bf891b55..00000000
--- a/onionshare_gui/downloads.py
+++ /dev/null
@@ -1,134 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-OnionShare | https://onionshare.org/
-
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
-
-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 <http://www.gnu.org/licenses/>.
-"""
-import time
-
-from PyQt5 import QtCore, QtWidgets
-
-from onionshare import strings, common
-
-class Download(object):
-
- def __init__(self, download_id, total_bytes):
- self.download_id = download_id
- self.started = time.time()
- self.total_bytes = total_bytes
- self.downloaded_bytes = 0
-
- # make a new progress bar
- cssStyleData ="""
- QProgressBar {
- border: 1px solid #4e064f;
- background-color: #ffffff !important;
- text-align: center;
- color: #9b9b9b;
- font-size: 12px;
- }
-
- QProgressBar::chunk {
- background-color: #4e064f;
- width: 10px;
- }"""
- self.progress_bar = QtWidgets.QProgressBar()
- self.progress_bar.setTextVisible(True)
- self.progress_bar.setAttribute(QtCore.Qt.WA_DeleteOnClose)
- self.progress_bar.setAlignment(QtCore.Qt.AlignHCenter)
- self.progress_bar.setMinimum(0)
- self.progress_bar.setMaximum(total_bytes)
- self.progress_bar.setValue(0)
- self.progress_bar.setStyleSheet(cssStyleData)
- self.progress_bar.total_bytes = total_bytes
-
- # start at 0
- self.update(0)
-
- def update(self, downloaded_bytes):
- self.downloaded_bytes = downloaded_bytes
-
- self.progress_bar.setValue(downloaded_bytes)
- if downloaded_bytes == self.progress_bar.total_bytes:
- pb_fmt = strings._('gui_download_progress_complete').format(
- common.format_seconds(time.time() - self.started))
- else:
- elapsed = time.time() - self.started
- if elapsed < 10:
- # Wait a couple of seconds for the download rate to stabilize.
- # This prevents a "Windows copy dialog"-esque experience at
- # the beginning of the download.
- pb_fmt = strings._('gui_download_progress_starting').format(
- common.human_readable_filesize(downloaded_bytes))
- else:
- pb_fmt = strings._('gui_download_progress_eta').format(
- common.human_readable_filesize(downloaded_bytes),
- self.estimated_time_remaining)
-
- self.progress_bar.setFormat(pb_fmt)
-
- def cancel(self):
- self.progress_bar.setFormat(strings._('gui_canceled'))
-
- @property
- def estimated_time_remaining(self):
- return common.estimated_time_remaining(self.downloaded_bytes,
- self.total_bytes,
- self.started)
-
-
-class Downloads(QtWidgets.QWidget):
- """
- The downloads chunk of the GUI. This lists all of the active download
- progress bars.
- """
- def __init__(self):
- super(Downloads, self).__init__()
- self.downloads = {}
- self.layout = QtWidgets.QVBoxLayout()
- self.setLayout(self.layout)
-
- def add_download(self, download_id, total_bytes):
- """
- Add a new download progress bar.
- """
- self.parent().show()
-
- # add it to the list
- download = Download(download_id, total_bytes)
- self.downloads[download_id] = download
- self.layout.insertWidget(-1, download.progress_bar)
-
- def update_download(self, download_id, downloaded_bytes):
- """
- Update the progress of a download progress bar.
- """
- self.downloads[download_id].update(downloaded_bytes)
-
- def cancel_download(self, download_id):
- """
- Update a download progress bar to show that it has been canceled.
- """
- self.downloads[download_id].cancel()
-
- def reset_downloads(self):
- """
- Reset the downloads back to zero
- """
- for download in self.downloads.values():
- self.layout.removeWidget(download.progress_bar)
- download.progress_bar.close()
- self.downloads = {}
diff --git a/onionshare_gui/mode/__init__.py b/onionshare_gui/mode/__init__.py
new file mode 100644
index 00000000..5110289f
--- /dev/null
+++ b/onionshare_gui/mode/__init__.py
@@ -0,0 +1,337 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+from PyQt5 import QtCore, QtWidgets, QtGui
+
+from onionshare import strings
+from onionshare.common import ShutdownTimer
+
+from ..server_status import ServerStatus
+from ..threads import OnionThread
+from ..widgets import Alert
+
+class Mode(QtWidgets.QWidget):
+ """
+ The class that ShareMode and ReceiveMode inherit from.
+ """
+ start_server_finished = QtCore.pyqtSignal()
+ stop_server_finished = QtCore.pyqtSignal()
+ starting_server_step2 = QtCore.pyqtSignal()
+ starting_server_step3 = QtCore.pyqtSignal()
+ starting_server_error = QtCore.pyqtSignal(str)
+ set_server_active = QtCore.pyqtSignal(bool)
+
+ def __init__(self, common, qtapp, app, status_bar, server_status_label, system_tray, filenames=None, local_only=False):
+ super(Mode, self).__init__()
+ self.common = common
+ self.qtapp = qtapp
+ self.app = app
+
+ self.status_bar = status_bar
+ self.server_status_label = server_status_label
+ self.system_tray = system_tray
+
+ self.filenames = filenames
+
+ # The web object gets created in init()
+ self.web = None
+
+ # Local mode is passed from OnionShareGui
+ self.local_only = local_only
+
+ # Threads start out as None
+ self.onion_thread = None
+ self.web_thread = None
+
+ # Server status
+ self.server_status = ServerStatus(self.common, self.qtapp, self.app, None, self.local_only)
+ self.server_status.server_started.connect(self.start_server)
+ self.server_status.server_stopped.connect(self.stop_server)
+ self.server_status.server_canceled.connect(self.cancel_server)
+ self.start_server_finished.connect(self.server_status.start_server_finished)
+ self.stop_server_finished.connect(self.server_status.stop_server_finished)
+ self.starting_server_step2.connect(self.start_server_step2)
+ self.starting_server_step3.connect(self.start_server_step3)
+ self.starting_server_error.connect(self.start_server_error)
+
+ # Primary action
+ # Note: It's up to the downstream Mode to add this to its layout
+ self.primary_action_layout = QtWidgets.QVBoxLayout()
+ self.primary_action_layout.addWidget(self.server_status)
+ self.primary_action = QtWidgets.QWidget()
+ self.primary_action.setLayout(self.primary_action_layout)
+
+ # Hack to allow a minimum width on the main layout
+ # Note: It's up to the downstream Mode to add this to its layout
+ self.min_width_widget = QtWidgets.QWidget()
+ self.min_width_widget.setMinimumWidth(600)
+
+ def init(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def timer_callback(self):
+ """
+ This method is called regularly on a timer.
+ """
+ # If the auto-shutdown timer has stopped, stop the server
+ if self.server_status.status == ServerStatus.STATUS_STARTED:
+ if self.app.shutdown_timer and self.common.settings.get('shutdown_timeout'):
+ if self.timeout > 0:
+ now = QtCore.QDateTime.currentDateTime()
+ seconds_remaining = now.secsTo(self.server_status.timeout)
+
+ # Update the server button
+ server_button_text = self.get_stop_server_shutdown_timeout_text()
+ self.server_status.server_button.setText(server_button_text.format(seconds_remaining))
+
+ self.status_bar.clearMessage()
+ if not self.app.shutdown_timer.is_alive():
+ if self.timeout_finished_should_stop_server():
+ self.server_status.stop_server()
+
+ def timer_callback_custom(self):
+ """
+ Add custom timer code.
+ """
+ pass
+
+ def get_stop_server_shutdown_timeout_text(self):
+ """
+ Return the string to put on the stop server button, if there's a shutdown timeout
+ """
+ pass
+
+ def timeout_finished_should_stop_server(self):
+ """
+ The shutdown timer expired, should we stop the server? Returns a bool
+ """
+ pass
+
+ def start_server(self):
+ """
+ Start the onionshare server. This uses multiple threads to start the Tor onion
+ server and the web app.
+ """
+ self.common.log('Mode', 'start_server')
+
+ self.start_server_custom()
+
+ self.set_server_active.emit(True)
+ self.app.set_stealth(self.common.settings.get('use_stealth'))
+
+ # Clear the status bar
+ self.status_bar.clearMessage()
+ self.server_status_label.setText('')
+
+ self.common.log('Mode', 'start_server', 'Starting an onion thread')
+ self.onion_thread = OnionThread(self)
+ self.onion_thread.success.connect(self.starting_server_step2.emit)
+ self.onion_thread.error.connect(self.starting_server_error.emit)
+ self.onion_thread.start()
+
+ def start_server_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def start_server_step2(self):
+ """
+ Step 2 in starting the onionshare server.
+ """
+ self.common.log('Mode', 'start_server_step2')
+
+ self.start_server_step2_custom()
+
+ # Nothing to do here.
+
+ # start_server_step2_custom has call these to move on:
+ # self.starting_server_step3.emit()
+ # self.start_server_finished.emit()
+
+ def start_server_step2_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def start_server_step3(self):
+ """
+ Step 3 in starting the onionshare server.
+ """
+ self.common.log('Mode', 'start_server_step3')
+
+ self.start_server_step3_custom()
+
+ if self.common.settings.get('shutdown_timeout'):
+ # Convert the date value to seconds between now and then
+ now = QtCore.QDateTime.currentDateTime()
+ self.timeout = now.secsTo(self.server_status.timeout)
+ # Set the shutdown timeout value
+ if self.timeout > 0:
+ self.app.shutdown_timer = ShutdownTimer(self.common, self.timeout)
+ self.app.shutdown_timer.start()
+ # The timeout has actually already passed since the user clicked Start. Probably the Onion service took too long to start.
+ else:
+ self.stop_server()
+ self.start_server_error(strings._('gui_server_started_after_timeout'))
+
+ def start_server_step3_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def start_server_error(self, error):
+ """
+ If there's an error when trying to start the onion service
+ """
+ self.common.log('Mode', 'start_server_error')
+
+ Alert(self.common, error, QtWidgets.QMessageBox.Warning)
+ self.set_server_active.emit(False)
+ self.server_status.stop_server()
+ self.status_bar.clearMessage()
+
+ self.start_server_error_custom()
+
+ def start_server_error_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def cancel_server(self):
+ """
+ Cancel the server while it is preparing to start
+ """
+ self.cancel_server_custom()
+
+ if self.onion_thread:
+ self.common.log('Mode', 'cancel_server: quitting onion thread')
+ self.onion_thread.quit()
+ if self.web_thread:
+ self.common.log('Mode', 'cancel_server: quitting web thread')
+ self.web_thread.quit()
+ self.stop_server()
+
+ def cancel_server_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def stop_server(self):
+ """
+ Stop the onionshare server.
+ """
+ self.common.log('Mode', 'stop_server')
+
+ if self.server_status.status != ServerStatus.STATUS_STOPPED:
+ try:
+ self.web.stop(self.app.port)
+ except:
+ # Probably we had no port to begin with (Onion service didn't start)
+ pass
+ self.app.cleanup()
+
+ self.stop_server_custom()
+
+ self.set_server_active.emit(False)
+ self.stop_server_finished.emit()
+
+ def stop_server_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ def handle_tor_broke(self):
+ """
+ Handle connection from Tor breaking.
+ """
+ if self.server_status.status != ServerStatus.STATUS_STOPPED:
+ self.server_status.stop_server()
+ self.handle_tor_broke_custom()
+
+ def handle_tor_broke_custom(self):
+ """
+ Add custom initialization here.
+ """
+ pass
+
+ # Handle web server events
+
+ def handle_request_load(self, event):
+ """
+ Handle REQUEST_LOAD event.
+ """
+ pass
+
+ def handle_request_started(self, event):
+ """
+ Handle REQUEST_STARTED event.
+ """
+ pass
+
+ def handle_request_rate_limit(self, event):
+ """
+ Handle REQUEST_RATE_LIMIT event.
+ """
+ self.stop_server()
+ Alert(self.common, strings._('error_rate_limit'), QtWidgets.QMessageBox.Critical)
+
+ def handle_request_progress(self, event):
+ """
+ Handle REQUEST_PROGRESS event.
+ """
+ pass
+
+ def handle_request_canceled(self, event):
+ """
+ Handle REQUEST_CANCELED event.
+ """
+ pass
+
+ def handle_request_close_server(self, event):
+ """
+ Handle REQUEST_CLOSE_SERVER event.
+ """
+ pass
+
+ def handle_request_upload_file_renamed(self, event):
+ """
+ Handle REQUEST_UPLOAD_FILE_RENAMED event.
+ """
+ pass
+
+ def handle_request_upload_set_dir(self, event):
+ """
+ Handle REQUEST_UPLOAD_SET_DIR event.
+ """
+ pass
+
+ def handle_request_upload_finished(self, event):
+ """
+ Handle REQUEST_UPLOAD_FINISHED event.
+ """
+ pass
diff --git a/onionshare_gui/mode/history.py b/onionshare_gui/mode/history.py
new file mode 100644
index 00000000..e72a3838
--- /dev/null
+++ b/onionshare_gui/mode/history.py
@@ -0,0 +1,559 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+import time
+import subprocess
+import os
+from datetime import datetime
+from PyQt5 import QtCore, QtWidgets, QtGui
+
+from onionshare import strings
+from ..widgets import Alert
+
+
+class HistoryItem(QtWidgets.QWidget):
+ """
+ The base history item
+ """
+ def __init__(self):
+ super(HistoryItem, self).__init__()
+
+ def update(self):
+ pass
+
+ def cancel(self):
+ pass
+
+
+class DownloadHistoryItem(HistoryItem):
+ """
+ Download history item, for share mode
+ """
+ def __init__(self, common, id, total_bytes):
+ super(DownloadHistoryItem, self).__init__()
+ self.common = common
+
+ self.id = id
+ self.total_bytes = total_bytes
+ self.downloaded_bytes = 0
+ self.started = time.time()
+ self.started_dt = datetime.fromtimestamp(self.started)
+
+ # Label
+ self.label = QtWidgets.QLabel(strings._('gui_download_in_progress').format(self.started_dt.strftime("%b %d, %I:%M%p")))
+
+ # Progress bar
+ self.progress_bar = QtWidgets.QProgressBar()
+ self.progress_bar.setTextVisible(True)
+ self.progress_bar.setAttribute(QtCore.Qt.WA_DeleteOnClose)
+ self.progress_bar.setAlignment(QtCore.Qt.AlignHCenter)
+ self.progress_bar.setMinimum(0)
+ self.progress_bar.setMaximum(total_bytes)
+ self.progress_bar.setValue(0)
+ self.progress_bar.setStyleSheet(self.common.css['downloads_uploads_progress_bar'])
+ self.progress_bar.total_bytes = total_bytes
+
+ # Layout
+ layout = QtWidgets.QVBoxLayout()
+ layout.addWidget(self.label)
+ layout.addWidget(self.progress_bar)
+ self.setLayout(layout)
+
+ # Start at 0
+ self.update(0)
+
+ def update(self, downloaded_bytes):
+ self.downloaded_bytes = downloaded_bytes
+
+ self.progress_bar.setValue(downloaded_bytes)
+ if downloaded_bytes == self.progress_bar.total_bytes:
+ pb_fmt = strings._('gui_download_upload_progress_complete').format(
+ self.common.format_seconds(time.time() - self.started))
+ else:
+ elapsed = time.time() - self.started
+ if elapsed < 10:
+ # Wait a couple of seconds for the download rate to stabilize.
+ # This prevents a "Windows copy dialog"-esque experience at
+ # the beginning of the download.
+ pb_fmt = strings._('gui_download_upload_progress_starting').format(
+ self.common.human_readable_filesize(downloaded_bytes))
+ else:
+ pb_fmt = strings._('gui_download_upload_progress_eta').format(
+ self.common.human_readable_filesize(downloaded_bytes),
+ self.estimated_time_remaining)
+
+ self.progress_bar.setFormat(pb_fmt)
+
+ def cancel(self):
+ self.progress_bar.setFormat(strings._('gui_canceled'))
+
+ @property
+ def estimated_time_remaining(self):
+ return self.common.estimated_time_remaining(self.downloaded_bytes,
+ self.total_bytes,
+ self.started)
+
+
+class UploadHistoryItemFile(QtWidgets.QWidget):
+ def __init__(self, common, filename):
+ super(UploadHistoryItemFile, self).__init__()
+ self.common = common
+
+ self.common.log('UploadHistoryItemFile', '__init__', 'filename: {}'.format(filename))
+
+ self.filename = filename
+ self.dir = None
+ self.started = datetime.now()
+
+ # Filename label
+ self.filename_label = QtWidgets.QLabel(self.filename)
+ self.filename_label_width = self.filename_label.width()
+
+ # File size label
+ self.filesize_label = QtWidgets.QLabel()
+ self.filesize_label.setStyleSheet(self.common.css['receive_file_size'])
+ self.filesize_label.hide()
+
+ # Folder button
+ folder_pixmap = QtGui.QPixmap.fromImage(QtGui.QImage(self.common.get_resource_path('images/open_folder.png')))
+ folder_icon = QtGui.QIcon(folder_pixmap)
+ self.folder_button = QtWidgets.QPushButton()
+ self.folder_button.clicked.connect(self.open_folder)
+ self.folder_button.setIcon(folder_icon)
+ self.folder_button.setIconSize(folder_pixmap.rect().size())
+ self.folder_button.setFlat(True)
+ self.folder_button.hide()
+
+ # Layouts
+ layout = QtWidgets.QHBoxLayout()
+ layout.addWidget(self.filename_label)
+ layout.addWidget(self.filesize_label)
+ layout.addStretch()
+ layout.addWidget(self.folder_button)
+ self.setLayout(layout)
+
+ def update(self, uploaded_bytes, complete):
+ self.filesize_label.setText(self.common.human_readable_filesize(uploaded_bytes))
+ self.filesize_label.show()
+
+ if complete:
+ self.folder_button.show()
+
+ def rename(self, new_filename):
+ self.filename = new_filename
+ self.filename_label.setText(self.filename)
+
+ def set_dir(self, dir):
+ self.dir = dir
+
+ def open_folder(self):
+ """
+ Open the downloads folder, with the file selected, in a cross-platform manner
+ """
+ self.common.log('UploadHistoryItemFile', 'open_folder')
+
+ if not self.dir:
+ self.common.log('UploadHistoryItemFile', 'open_folder', "dir has not been set yet, can't open folder")
+ return
+
+ abs_filename = os.path.join(self.dir, self.filename)
+
+ # Linux
+ if self.common.platform == 'Linux' or self.common.platform == 'BSD':
+ try:
+ # If nautilus is available, open it
+ subprocess.Popen(['nautilus', abs_filename])
+ except:
+ Alert(self.common, strings._('gui_open_folder_error_nautilus').format(abs_filename))
+
+ # macOS
+ elif self.common.platform == 'Darwin':
+ subprocess.call(['open', '-R', abs_filename])
+
+ # Windows
+ elif self.common.platform == 'Windows':
+ subprocess.Popen(['explorer', '/select,{}'.format(abs_filename)])
+
+class UploadHistoryItem(HistoryItem):
+ def __init__(self, common, id, content_length):
+ super(UploadHistoryItem, self).__init__()
+ self.common = common
+ self.id = id
+ self.content_length = content_length
+ self.started = datetime.now()
+
+ # Label
+ self.label = QtWidgets.QLabel(strings._('gui_upload_in_progress').format(self.started.strftime("%b %d, %I:%M%p")))
+
+ # Progress bar
+ self.progress_bar = QtWidgets.QProgressBar()
+ self.progress_bar.setTextVisible(True)
+ self.progress_bar.setAttribute(QtCore.Qt.WA_DeleteOnClose)
+ self.progress_bar.setAlignment(QtCore.Qt.AlignHCenter)
+ self.progress_bar.setMinimum(0)
+ self.progress_bar.setValue(0)
+ self.progress_bar.setStyleSheet(self.common.css['downloads_uploads_progress_bar'])
+
+ # This layout contains file widgets
+ self.files_layout = QtWidgets.QVBoxLayout()
+ self.files_layout.setContentsMargins(0, 0, 0, 0)
+ files_widget = QtWidgets.QWidget()
+ files_widget.setStyleSheet(self.common.css['receive_file'])
+ files_widget.setLayout(self.files_layout)
+
+ # Layout
+ layout = QtWidgets.QVBoxLayout()
+ layout.addWidget(self.label)
+ layout.addWidget(self.progress_bar)
+ layout.addWidget(files_widget)
+ layout.addStretch()
+ self.setLayout(layout)
+
+ # We're also making a dictionary of file widgets, to make them easier to access
+ self.files = {}
+
+ def update(self, data):
+ """
+ Using the progress from Web, update the progress bar and file size labels
+ for each file
+ """
+ if data['action'] == 'progress':
+ total_uploaded_bytes = 0
+ for filename in data['progress']:
+ total_uploaded_bytes += data['progress'][filename]['uploaded_bytes']
+
+ # Update the progress bar
+ self.progress_bar.setMaximum(self.content_length)
+ self.progress_bar.setValue(total_uploaded_bytes)
+
+ elapsed = datetime.now() - self.started
+ if elapsed.seconds < 10:
+ pb_fmt = strings._('gui_download_upload_progress_starting').format(
+ self.common.human_readable_filesize(total_uploaded_bytes))
+ else:
+ estimated_time_remaining = self.common.estimated_time_remaining(
+ total_uploaded_bytes,
+ self.content_length,
+ self.started.timestamp())
+ pb_fmt = strings._('gui_download_upload_progress_eta').format(
+ self.common.human_readable_filesize(total_uploaded_bytes),
+ estimated_time_remaining)
+
+ # Using list(progress) to avoid "RuntimeError: dictionary changed size during iteration"
+ for filename in list(data['progress']):
+ # Add a new file if needed
+ if filename not in self.files:
+ self.files[filename] = UploadHistoryItemFile(self.common, filename)
+ self.files_layout.addWidget(self.files[filename])
+
+ # Update the file
+ self.files[filename].update(data['progress'][filename]['uploaded_bytes'], data['progress'][filename]['complete'])
+
+ elif data['action'] == 'rename':
+ self.files[data['old_filename']].rename(data['new_filename'])
+ self.files[data['new_filename']] = self.files.pop(data['old_filename'])
+
+ elif data['action'] == 'set_dir':
+ self.files[data['filename']].set_dir(data['dir'])
+
+ elif data['action'] == 'finished':
+ # Hide the progress bar
+ self.progress_bar.hide()
+
+ # Change the label
+ self.ended = self.started = datetime.now()
+ if self.started.year == self.ended.year and self.started.month == self.ended.month and self.started.day == self.ended.day:
+ if self.started.hour == self.ended.hour and self.started.minute == self.ended.minute:
+ text = strings._('gui_upload_finished').format(
+ self.started.strftime("%b %d, %I:%M%p")
+ )
+ else:
+ text = strings._('gui_upload_finished_range').format(
+ self.started.strftime("%b %d, %I:%M%p"),
+ self.ended.strftime("%I:%M%p")
+ )
+ else:
+ text = strings._('gui_upload_finished_range').format(
+ self.started.strftime("%b %d, %I:%M%p"),
+ self.ended.strftime("%b %d, %I:%M%p")
+ )
+ self.label.setText(text)
+
+
+class HistoryItemList(QtWidgets.QScrollArea):
+ """
+ List of items
+ """
+ def __init__(self, common):
+ super(HistoryItemList, self).__init__()
+ self.common = common
+
+ self.items = {}
+
+ # The layout that holds all of the items
+ self.items_layout = QtWidgets.QVBoxLayout()
+ self.items_layout.setContentsMargins(0, 0, 0, 0)
+ self.items_layout.setSizeConstraint(QtWidgets.QLayout.SetMinAndMaxSize)
+
+ # Wrapper layout that also contains a stretch
+ wrapper_layout = QtWidgets.QVBoxLayout()
+ wrapper_layout.setSizeConstraint(QtWidgets.QLayout.SetMinAndMaxSize)
+ wrapper_layout.addLayout(self.items_layout)
+ wrapper_layout.addStretch()
+
+ # The internal widget of the scroll area
+ widget = QtWidgets.QWidget()
+ widget.setLayout(wrapper_layout)
+ self.setWidget(widget)
+ self.setWidgetResizable(True)
+
+ # Other scroll area settings
+ self.setBackgroundRole(QtGui.QPalette.Light)
+ self.verticalScrollBar().rangeChanged.connect(self.resizeScroll)
+
+ def resizeScroll(self, minimum, maximum):
+ """
+ Scroll to the bottom of the window when the range changes.
+ """
+ self.verticalScrollBar().setValue(maximum)
+
+ def add(self, id, item):
+ """
+ Add a new item. Override this method.
+ """
+ self.items[id] = item
+ self.items_layout.addWidget(item)
+
+ def update(self, id, data):
+ """
+ Update an item. Override this method.
+ """
+ self.items[id].update(data)
+
+ def cancel(self, id):
+ """
+ Cancel an item. Override this method.
+ """
+ self.items[id].cancel()
+
+ def reset(self):
+ """
+ Reset all items, emptying the list. Override this method.
+ """
+ for item in self.items.values():
+ self.items_layout.removeWidget(item)
+ item.close()
+ self.items = {}
+
+
+class History(QtWidgets.QWidget):
+ """
+ A history of what's happened so far in this mode. This contains an internal
+ object full of a scrollable list of items.
+ """
+ def __init__(self, common, empty_image, empty_text, header_text):
+ super(History, self).__init__()
+ self.common = common
+
+ self.setMinimumWidth(350)
+
+ # In progress and completed counters
+ self.in_progress_count = 0
+ self.completed_count = 0
+
+ # In progress and completed labels
+ self.in_progress_label = QtWidgets.QLabel()
+ self.in_progress_label.setStyleSheet(self.common.css['mode_info_label'])
+ self.completed_label = QtWidgets.QLabel()
+ self.completed_label.setStyleSheet(self.common.css['mode_info_label'])
+
+ # Header
+ self.header_label = QtWidgets.QLabel(header_text)
+ self.header_label.setStyleSheet(self.common.css['downloads_uploads_label'])
+ clear_button = QtWidgets.QPushButton(strings._('gui_clear_history'))
+ clear_button.setStyleSheet(self.common.css['downloads_uploads_clear'])
+ clear_button.setFlat(True)
+ clear_button.clicked.connect(self.reset)
+ header_layout = QtWidgets.QHBoxLayout()
+ header_layout.addWidget(self.header_label)
+ header_layout.addStretch()
+ header_layout.addWidget(self.in_progress_label)
+ header_layout.addWidget(self.completed_label)
+ header_layout.addWidget(clear_button)
+
+ # When there are no items
+ self.empty_image = QtWidgets.QLabel()
+ self.empty_image.setAlignment(QtCore.Qt.AlignCenter)
+ self.empty_image.setPixmap(empty_image)
+ self.empty_text = QtWidgets.QLabel(empty_text)
+ self.empty_text.setAlignment(QtCore.Qt.AlignCenter)
+ self.empty_text.setStyleSheet(self.common.css['downloads_uploads_empty_text'])
+ empty_layout = QtWidgets.QVBoxLayout()
+ empty_layout.addStretch()
+ empty_layout.addWidget(self.empty_image)
+ empty_layout.addWidget(self.empty_text)
+ empty_layout.addStretch()
+ self.empty = QtWidgets.QWidget()
+ self.empty.setStyleSheet(self.common.css['downloads_uploads_empty'])
+ self.empty.setLayout(empty_layout)
+
+ # When there are items
+ self.item_list = HistoryItemList(self.common)
+ self.not_empty_layout = QtWidgets.QVBoxLayout()
+ self.not_empty_layout.addLayout(header_layout)
+ self.not_empty_layout.addWidget(self.item_list)
+ self.not_empty = QtWidgets.QWidget()
+ self.not_empty.setLayout(self.not_empty_layout)
+
+ # Layout
+ layout = QtWidgets.QVBoxLayout()
+ layout.setContentsMargins(0, 0, 0, 0)
+ layout.addWidget(self.empty)
+ layout.addWidget(self.not_empty)
+ self.setLayout(layout)
+
+ # Reset once at the beginning
+ self.reset()
+
+ def add(self, id, item):
+ """
+ Add a new item.
+ """
+ self.common.log('History', 'add', 'id: {}, item: {}'.format(id, item))
+
+ # Hide empty, show not empty
+ self.empty.hide()
+ self.not_empty.show()
+
+ # Add it to the list
+ self.item_list.add(id, item)
+
+ def update(self, id, data):
+ """
+ Update an item.
+ """
+ self.item_list.update(id, data)
+
+ def cancel(self, id):
+ """
+ Cancel an item.
+ """
+ self.item_list.cancel(id)
+
+ def reset(self):
+ """
+ Reset all items.
+ """
+ self.item_list.reset()
+
+ # Hide not empty, show empty
+ self.not_empty.hide()
+ self.empty.show()
+
+ # Reset counters
+ self.completed_count = 0
+ self.in_progress_count = 0
+ self.update_completed()
+ self.update_in_progress()
+
+ def update_completed(self):
+ """
+ Update the 'completed' widget.
+ """
+ if self.completed_count == 0:
+ image = self.common.get_resource_path('images/share_completed_none.png')
+ else:
+ image = self.common.get_resource_path('images/share_completed.png')
+ self.completed_label.setText('<img src="{0:s}" /> {1:d}'.format(image, self.completed_count))
+ self.completed_label.setToolTip(strings._('history_completed_tooltip').format(self.completed_count))
+
+ def update_in_progress(self):
+ """
+ Update the 'in progress' widget.
+ """
+ if self.in_progress_count == 0:
+ image = self.common.get_resource_path('images/share_in_progress_none.png')
+ else:
+ image = self.common.get_resource_path('images/share_in_progress.png')
+ self.in_progress_label.setText('<img src="{0:s}" /> {1:d}'.format(image, self.in_progress_count))
+ self.in_progress_label.setToolTip(strings._('history_in_progress_tooltip').format(self.in_progress_count))
+
+
+class ToggleHistory(QtWidgets.QPushButton):
+ """
+ Widget for toggling showing or hiding the history, as well as keeping track
+ of the indicator counter if it's hidden
+ """
+ def __init__(self, common, current_mode, history_widget, icon, selected_icon):
+ super(ToggleHistory, self).__init__()
+ self.common = common
+ self.current_mode = current_mode
+ self.history_widget = history_widget
+ self.icon = icon
+ self.selected_icon = selected_icon
+
+ # Toggle button
+ self.setDefault(False)
+ self.setFixedWidth(35)
+ self.setFixedHeight(30)
+ self.setFlat(True)
+ self.setIcon(icon)
+ self.clicked.connect(self.toggle_clicked)
+
+ # Keep track of indicator
+ self.indicator_count = 0
+ self.indicator_label = QtWidgets.QLabel(parent=self)
+ self.indicator_label.setStyleSheet(self.common.css['download_uploads_indicator'])
+ self.update_indicator()
+
+ def update_indicator(self, increment=False):
+ """
+ Update the display of the indicator count. If increment is True, then
+ only increment the counter if Downloads is hidden.
+ """
+ if increment and not self.history_widget.isVisible():
+ self.indicator_count += 1
+
+ self.indicator_label.setText("{}".format(self.indicator_count))
+
+ if self.indicator_count == 0:
+ self.indicator_label.hide()
+ else:
+ size = self.indicator_label.sizeHint()
+ self.indicator_label.setGeometry(35-size.width(), 0, size.width(), size.height())
+ self.indicator_label.show()
+
+ def toggle_clicked(self):
+ """
+ Toggle showing and hiding the history widget
+ """
+ self.common.log('ToggleHistory', 'toggle_clicked')
+
+ if self.history_widget.isVisible():
+ self.history_widget.hide()
+ self.setIcon(self.icon)
+ self.setFlat(True)
+ else:
+ self.history_widget.show()
+ self.setIcon(self.selected_icon)
+ self.setFlat(False)
+
+ # Reset the indicator count
+ self.indicator_count = 0
+ self.update_indicator()
diff --git a/onionshare_gui/mode/receive_mode/__init__.py b/onionshare_gui/mode/receive_mode/__init__.py
new file mode 100644
index 00000000..c53f1ea1
--- /dev/null
+++ b/onionshare_gui/mode/receive_mode/__init__.py
@@ -0,0 +1,214 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+from PyQt5 import QtCore, QtWidgets, QtGui
+
+from onionshare import strings
+from onionshare.web import Web
+
+from ..history import History, ToggleHistory, UploadHistoryItem
+from .. import Mode
+
+class ReceiveMode(Mode):
+ """
+ Parts of the main window UI for receiving files.
+ """
+ def init(self):
+ """
+ Custom initialization for ReceiveMode.
+ """
+ # Create the Web object
+ self.web = Web(self.common, True, 'receive')
+
+ # Server status
+ self.server_status.set_mode('receive')
+ self.server_status.server_started_finished.connect(self.update_primary_action)
+ self.server_status.server_stopped.connect(self.update_primary_action)
+ self.server_status.server_canceled.connect(self.update_primary_action)
+
+ # Tell server_status about web, then update
+ self.server_status.web = self.web
+ self.server_status.update()
+
+ # Upload history
+ self.history = History(
+ self.common,
+ QtGui.QPixmap.fromImage(QtGui.QImage(self.common.get_resource_path('images/uploads_transparent.png'))),
+ strings._('gui_no_uploads'),
+ strings._('gui_uploads')
+ )
+ self.history.hide()
+
+ # Toggle history
+ self.toggle_history = ToggleHistory(
+ self.common, self, self.history,
+ QtGui.QIcon(self.common.get_resource_path('images/uploads_toggle.png')),
+ QtGui.QIcon(self.common.get_resource_path('images/uploads_toggle_selected.png'))
+ )
+
+ # Receive mode warning
+ receive_warning = QtWidgets.QLabel(strings._('gui_receive_mode_warning'))
+ receive_warning.setMinimumHeight(80)
+ receive_warning.setWordWrap(True)
+
+ # Top bar
+ top_bar_layout = QtWidgets.QHBoxLayout()
+ top_bar_layout.addStretch()
+ top_bar_layout.addWidget(self.toggle_history)
+
+ # Main layout
+ self.main_layout = QtWidgets.QVBoxLayout()
+ self.main_layout.addLayout(top_bar_layout)
+ self.main_layout.addWidget(receive_warning)
+ self.main_layout.addWidget(self.primary_action)
+ self.main_layout.addStretch()
+ self.main_layout.addWidget(self.min_width_widget)
+
+ # Wrapper layout
+ self.wrapper_layout = QtWidgets.QHBoxLayout()
+ self.wrapper_layout.addLayout(self.main_layout)
+ self.wrapper_layout.addWidget(self.history)
+ self.setLayout(self.wrapper_layout)
+
+ def get_stop_server_shutdown_timeout_text(self):
+ """
+ Return the string to put on the stop server button, if there's a shutdown timeout
+ """
+ return strings._('gui_receive_stop_server_shutdown_timeout')
+
+ def timeout_finished_should_stop_server(self):
+ """
+ The shutdown timer expired, should we stop the server? Returns a bool
+ """
+ # If there were no attempts to upload files, or all uploads are done, we can stop
+ if self.web.receive_mode.upload_count == 0 or not self.web.receive_mode.uploads_in_progress:
+ self.server_status.stop_server()
+ self.server_status_label.setText(strings._('close_on_timeout'))
+ return True
+ # An upload is probably still running - hold off on stopping the share, but block new shares.
+ else:
+ self.server_status_label.setText(strings._('timeout_upload_still_running'))
+ self.web.receive_mode.can_upload = False
+ return False
+
+ def start_server_custom(self):
+ """
+ Starting the server.
+ """
+ # Reset web counters
+ self.web.receive_mode.upload_count = 0
+ self.web.error404_count = 0
+
+ # Hide and reset the uploads if we have previously shared
+ self.reset_info_counters()
+
+ def start_server_step2_custom(self):
+ """
+ Step 2 in starting the server.
+ """
+ # Continue
+ self.starting_server_step3.emit()
+ self.start_server_finished.emit()
+
+ def handle_tor_broke_custom(self):
+ """
+ Connection to Tor broke.
+ """
+ self.primary_action.hide()
+
+ def handle_request_load(self, event):
+ """
+ Handle REQUEST_LOAD event.
+ """
+ self.system_tray.showMessage(strings._('systray_page_loaded_title'), strings._('systray_upload_page_loaded_message'))
+
+ def handle_request_started(self, event):
+ """
+ Handle REQUEST_STARTED event.
+ """
+ item = UploadHistoryItem(self.common, event["data"]["id"], event["data"]["content_length"])
+ self.history.add(event["data"]["id"], item)
+ self.toggle_history.update_indicator(True)
+ self.history.in_progress_count += 1
+ self.history.update_in_progress()
+
+ self.system_tray.showMessage(strings._('systray_upload_started_title'), strings._('systray_upload_started_message'))
+
+ def handle_request_progress(self, event):
+ """
+ Handle REQUEST_PROGRESS event.
+ """
+ self.history.update(event["data"]["id"], {
+ 'action': 'progress',
+ 'progress': event["data"]["progress"]
+ })
+
+ def handle_request_close_server(self, event):
+ """
+ Handle REQUEST_CLOSE_SERVER event.
+ """
+ self.stop_server()
+ self.system_tray.showMessage(strings._('systray_close_server_title'), strings._('systray_close_server_message'))
+
+ def handle_request_upload_file_renamed(self, event):
+ """
+ Handle REQUEST_UPLOAD_FILE_RENAMED event.
+ """
+ self.history.update(event["data"]["id"], {
+ 'action': 'rename',
+ 'old_filename': event["data"]["old_filename"],
+ 'new_filename': event["data"]["new_filename"]
+ })
+
+ def handle_request_upload_set_dir(self, event):
+ """
+ Handle REQUEST_UPLOAD_SET_DIR event.
+ """
+ self.history.update(event["data"]["id"], {
+ 'action': 'set_dir',
+ 'filename': event["data"]["filename"],
+ 'dir': event["data"]["dir"]
+ })
+
+ def handle_request_upload_finished(self, event):
+ """
+ Handle REQUEST_UPLOAD_FINISHED event.
+ """
+ self.history.update(event["data"]["id"], {
+ 'action': 'finished'
+ })
+ self.history.completed_count += 1
+ self.history.in_progress_count -= 1
+ self.history.update_completed()
+ self.history.update_in_progress()
+
+ def on_reload_settings(self):
+ """
+ We should be ok to re-enable the 'Start Receive Mode' button now.
+ """
+ self.primary_action.show()
+
+ def reset_info_counters(self):
+ """
+ Set the info counters back to zero.
+ """
+ self.history.reset()
+
+ def update_primary_action(self):
+ self.common.log('ReceiveMode', 'update_primary_action')
diff --git a/onionshare_gui/mode/share_mode/__init__.py b/onionshare_gui/mode/share_mode/__init__.py
new file mode 100644
index 00000000..436d42f7
--- /dev/null
+++ b/onionshare_gui/mode/share_mode/__init__.py
@@ -0,0 +1,382 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+import os
+from PyQt5 import QtCore, QtWidgets, QtGui
+
+from onionshare import strings
+from onionshare.onion import *
+from onionshare.common import Common
+from onionshare.web import Web
+
+from .file_selection import FileSelection
+from .threads import CompressThread
+from .. import Mode
+from ..history import History, ToggleHistory, DownloadHistoryItem
+from ...widgets import Alert
+
+
+class ShareMode(Mode):
+ """
+ Parts of the main window UI for sharing files.
+ """
+ def init(self):
+ """
+ Custom initialization for ReceiveMode.
+ """
+ # Threads start out as None
+ self.compress_thread = None
+
+ # Create the Web object
+ self.web = Web(self.common, True, 'share')
+
+ # File selection
+ self.file_selection = FileSelection(self.common)
+ if self.filenames:
+ for filename in self.filenames:
+ self.file_selection.file_list.add_file(filename)
+
+ # Server status
+ self.server_status.set_mode('share', self.file_selection)
+ self.server_status.server_started.connect(self.file_selection.server_started)
+ self.server_status.server_stopped.connect(self.file_selection.server_stopped)
+ self.server_status.server_stopped.connect(self.update_primary_action)
+ self.server_status.server_canceled.connect(self.file_selection.server_stopped)
+ self.server_status.server_canceled.connect(self.update_primary_action)
+ self.file_selection.file_list.files_updated.connect(self.server_status.update)
+ self.file_selection.file_list.files_updated.connect(self.update_primary_action)
+ # Tell server_status about web, then update
+ self.server_status.web = self.web
+ self.server_status.update()
+
+ # Filesize warning
+ self.filesize_warning = QtWidgets.QLabel()
+ self.filesize_warning.setWordWrap(True)
+ self.filesize_warning.setStyleSheet(self.common.css['share_filesize_warning'])
+ self.filesize_warning.hide()
+
+ # Download history
+ self.history = History(
+ self.common,
+ QtGui.QPixmap.fromImage(QtGui.QImage(self.common.get_resource_path('images/downloads_transparent.png'))),
+ strings._('gui_no_downloads'),
+ strings._('gui_downloads')
+ )
+ self.history.hide()
+
+ # Info label
+ self.info_label = QtWidgets.QLabel()
+ self.info_label.hide()
+
+ # Toggle history
+ self.toggle_history = ToggleHistory(
+ self.common, self, self.history,
+ QtGui.QIcon(self.common.get_resource_path('images/downloads_toggle.png')),
+ QtGui.QIcon(self.common.get_resource_path('images/downloads_toggle_selected.png'))
+ )
+
+ # Top bar
+ top_bar_layout = QtWidgets.QHBoxLayout()
+ top_bar_layout.addWidget(self.info_label)
+ top_bar_layout.addStretch()
+ top_bar_layout.addWidget(self.toggle_history)
+
+ # Primary action layout
+ self.primary_action_layout.addWidget(self.filesize_warning)
+ self.primary_action.hide()
+ self.update_primary_action()
+
+ # Status bar, zip progress bar
+ self._zip_progress_bar = None
+
+ # Main layout
+ self.main_layout = QtWidgets.QVBoxLayout()
+ self.main_layout.addLayout(top_bar_layout)
+ self.main_layout.addLayout(self.file_selection)
+ self.main_layout.addWidget(self.primary_action)
+ self.main_layout.addWidget(self.min_width_widget)
+
+ # Wrapper layout
+ self.wrapper_layout = QtWidgets.QHBoxLayout()
+ self.wrapper_layout.addLayout(self.main_layout)
+ self.wrapper_layout.addWidget(self.history)
+ self.setLayout(self.wrapper_layout)
+
+ # Always start with focus on file selection
+ self.file_selection.setFocus()
+
+ def get_stop_server_shutdown_timeout_text(self):
+ """
+ Return the string to put on the stop server button, if there's a shutdown timeout
+ """
+ return strings._('gui_share_stop_server_shutdown_timeout')
+
+ def timeout_finished_should_stop_server(self):
+ """
+ The shutdown timer expired, should we stop the server? Returns a bool
+ """
+ # If there were no attempts to download the share, or all downloads are done, we can stop
+ if self.web.share_mode.download_count == 0 or self.web.done:
+ self.server_status.stop_server()
+ self.server_status_label.setText(strings._('close_on_timeout'))
+ return True
+ # A download is probably still running - hold off on stopping the share
+ else:
+ self.server_status_label.setText(strings._('timeout_download_still_running'))
+ return False
+
+ def start_server_custom(self):
+ """
+ Starting the server.
+ """
+ # Reset web counters
+ self.web.share_mode.download_count = 0
+ self.web.error404_count = 0
+
+ # Hide and reset the downloads if we have previously shared
+ self.reset_info_counters()
+
+ def start_server_step2_custom(self):
+ """
+ Step 2 in starting the server. Zipping up files.
+ """
+ # Add progress bar to the status bar, indicating the compressing of files.
+ self._zip_progress_bar = ZipProgressBar(self.common, 0)
+ self.filenames = []
+ for index in range(self.file_selection.file_list.count()):
+ self.filenames.append(self.file_selection.file_list.item(index).filename)
+
+ self._zip_progress_bar.total_files_size = ShareMode._compute_total_size(self.filenames)
+ self.status_bar.insertWidget(0, self._zip_progress_bar)
+
+ # prepare the files for sending in a new thread
+ self.compress_thread = CompressThread(self)
+ self.compress_thread.success.connect(self.starting_server_step3.emit)
+ self.compress_thread.success.connect(self.start_server_finished.emit)
+ self.compress_thread.error.connect(self.starting_server_error.emit)
+ self.server_status.server_canceled.connect(self.compress_thread.cancel)
+ self.compress_thread.start()
+
+ def start_server_step3_custom(self):
+ """
+ Step 3 in starting the server. Remove zip progess bar, and display large filesize
+ warning, if applicable.
+ """
+ # Remove zip progress bar
+ if self._zip_progress_bar is not None:
+ self.status_bar.removeWidget(self._zip_progress_bar)
+ self._zip_progress_bar = None
+
+ # Warn about sending large files over Tor
+ if self.web.share_mode.download_filesize >= 157286400: # 150mb
+ self.filesize_warning.setText(strings._("large_filesize"))
+ self.filesize_warning.show()
+
+ def start_server_error_custom(self):
+ """
+ Start server error.
+ """
+ if self._zip_progress_bar is not None:
+ self.status_bar.removeWidget(self._zip_progress_bar)
+ self._zip_progress_bar = None
+
+ def stop_server_custom(self):
+ """
+ Stop server.
+ """
+ # Remove the progress bar
+ if self._zip_progress_bar is not None:
+ self.status_bar.removeWidget(self._zip_progress_bar)
+ self._zip_progress_bar = None
+
+ self.filesize_warning.hide()
+ self.history.in_progress_count = 0
+ self.history.completed_count = 0
+ self.history.update_in_progress()
+ self.file_selection.file_list.adjustSize()
+
+ def cancel_server_custom(self):
+ """
+ Stop the compression thread on cancel
+ """
+ if self.compress_thread:
+ self.common.log('ShareMode', 'cancel_server: quitting compress thread')
+ self.compress_thread.quit()
+
+ def handle_tor_broke_custom(self):
+ """
+ Connection to Tor broke.
+ """
+ self.primary_action.hide()
+
+ def handle_request_load(self, event):
+ """
+ Handle REQUEST_LOAD event.
+ """
+ self.system_tray.showMessage(strings._('systray_page_loaded_title'), strings._('systray_download_page_loaded_message'))
+
+ def handle_request_started(self, event):
+ """
+ Handle REQUEST_STARTED event.
+ """
+ if event["data"]["use_gzip"]:
+ filesize = self.web.share_mode.gzip_filesize
+ else:
+ filesize = self.web.share_mode.download_filesize
+
+ item = DownloadHistoryItem(self.common, event["data"]["id"], filesize)
+ self.history.add(event["data"]["id"], item)
+ self.toggle_history.update_indicator(True)
+ self.history.in_progress_count += 1
+ self.history.update_in_progress()
+
+ self.system_tray.showMessage(strings._('systray_download_started_title'), strings._('systray_download_started_message'))
+
+ def handle_request_progress(self, event):
+ """
+ Handle REQUEST_PROGRESS event.
+ """
+ self.history.update(event["data"]["id"], event["data"]["bytes"])
+
+ # Is the download complete?
+ if event["data"]["bytes"] == self.web.share_mode.filesize:
+ self.system_tray.showMessage(strings._('systray_download_completed_title'), strings._('systray_download_completed_message'))
+
+ # Update completed and in progress labels
+ self.history.completed_count += 1
+ self.history.in_progress_count -= 1
+ self.history.update_completed()
+ self.history.update_in_progress()
+
+ # Close on finish?
+ if self.common.settings.get('close_after_first_download'):
+ self.server_status.stop_server()
+ self.status_bar.clearMessage()
+ self.server_status_label.setText(strings._('closing_automatically'))
+ else:
+ if self.server_status.status == self.server_status.STATUS_STOPPED:
+ self.history.cancel(event["data"]["id"])
+ self.history.in_progress_count = 0
+ self.history.update_in_progress()
+
+ def handle_request_canceled(self, event):
+ """
+ Handle REQUEST_CANCELED event.
+ """
+ self.history.cancel(event["data"]["id"])
+
+ # Update in progress count
+ self.history.in_progress_count -= 1
+ self.history.update_in_progress()
+ self.system_tray.showMessage(strings._('systray_download_canceled_title'), strings._('systray_download_canceled_message'))
+
+ def on_reload_settings(self):
+ """
+ If there were some files listed for sharing, we should be ok to re-enable
+ the 'Start Sharing' button now.
+ """
+ if self.server_status.file_selection.get_num_files() > 0:
+ self.primary_action.show()
+ self.info_label.show()
+
+ def update_primary_action(self):
+ self.common.log('ShareMode', 'update_primary_action')
+
+ # Show or hide primary action layout
+ file_count = self.file_selection.file_list.count()
+ if file_count > 0:
+ self.primary_action.show()
+ self.info_label.show()
+
+ # Update the file count in the info label
+ total_size_bytes = 0
+ for index in range(self.file_selection.file_list.count()):
+ item = self.file_selection.file_list.item(index)
+ total_size_bytes += item.size_bytes
+ total_size_readable = self.common.human_readable_filesize(total_size_bytes)
+
+ if file_count > 1:
+ self.info_label.setText(strings._('gui_file_info').format(file_count, total_size_readable))
+ else:
+ self.info_label.setText(strings._('gui_file_info_single').format(file_count, total_size_readable))
+
+ else:
+ self.primary_action.hide()
+ self.info_label.hide()
+
+ def reset_info_counters(self):
+ """
+ Set the info counters back to zero.
+ """
+ self.history.reset()
+
+ @staticmethod
+ def _compute_total_size(filenames):
+ total_size = 0
+ for filename in filenames:
+ if os.path.isfile(filename):
+ total_size += os.path.getsize(filename)
+ if os.path.isdir(filename):
+ total_size += Common.dir_size(filename)
+ return total_size
+
+
+class ZipProgressBar(QtWidgets.QProgressBar):
+ update_processed_size_signal = QtCore.pyqtSignal(int)
+
+ def __init__(self, common, total_files_size):
+ super(ZipProgressBar, self).__init__()
+ self.common = common
+
+ self.setMaximumHeight(20)
+ self.setMinimumWidth(200)
+ self.setValue(0)
+ self.setFormat(strings._('zip_progress_bar_format'))
+ self.setStyleSheet(self.common.css['share_zip_progess_bar'])
+
+ self._total_files_size = total_files_size
+ self._processed_size = 0
+
+ self.update_processed_size_signal.connect(self.update_processed_size)
+
+ @property
+ def total_files_size(self):
+ return self._total_files_size
+
+ @total_files_size.setter
+ def total_files_size(self, val):
+ self._total_files_size = val
+
+ @property
+ def processed_size(self):
+ return self._processed_size
+
+ @processed_size.setter
+ def processed_size(self, val):
+ self.update_processed_size(val)
+
+ def update_processed_size(self, val):
+ self._processed_size = val
+
+ if self.processed_size < self.total_files_size:
+ self.setValue(int((self.processed_size * 100) / self.total_files_size))
+ elif self.total_files_size != 0:
+ self.setValue(100)
+ else:
+ self.setValue(0)
diff --git a/onionshare_gui/file_selection.py b/onionshare_gui/mode/share_mode/file_selection.py
index 3f52a96d..ec3b5ea5 100644
--- a/onionshare_gui/file_selection.py
+++ b/onionshare_gui/mode/share_mode/file_selection.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -19,26 +19,30 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
from PyQt5 import QtCore, QtWidgets, QtGui
-from .alert import Alert
-from onionshare import strings, common
+from onionshare import strings
+
+from ...widgets import Alert, AddFileDialog
class DropHereLabel(QtWidgets.QLabel):
"""
When there are no files or folders in the FileList yet, display the
'drop files here' message and graphic.
"""
- def __init__(self, parent, image=False):
+ def __init__(self, common, parent, image=False):
self.parent = parent
super(DropHereLabel, self).__init__(parent=parent)
+
+ self.common = common
+
self.setAcceptDrops(True)
self.setAlignment(QtCore.Qt.AlignCenter)
if image:
- self.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(common.get_resource_path('images/logo_transparent.png'))))
+ self.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(self.common.get_resource_path('images/logo_transparent.png'))))
else:
- self.setText(strings._('gui_drag_and_drop', True))
- self.setStyleSheet('color: #999999;')
+ self.setText(strings._('gui_drag_and_drop'))
+ self.setStyleSheet(self.common.css['share_file_selection_drop_here_label'])
self.hide()
@@ -53,13 +57,16 @@ class DropCountLabel(QtWidgets.QLabel):
While dragging files over the FileList, this counter displays the
number of files you're dragging.
"""
- def __init__(self, parent):
+ def __init__(self, common, parent):
self.parent = parent
super(DropCountLabel, self).__init__(parent=parent)
+
+ self.common = common
+
self.setAcceptDrops(True)
self.setAlignment(QtCore.Qt.AlignCenter)
- self.setText(strings._('gui_drag_and_drop', True))
- self.setStyleSheet('color: #ffffff; background-color: #f44449; font-weight: bold; padding: 5px 10px; border-radius: 10px;')
+ self.setText(strings._('gui_drag_and_drop'))
+ self.setStyleSheet(self.common.css['share_file_selection_drop_count_label'])
self.hide()
def dragEnterEvent(self, event):
@@ -74,16 +81,19 @@ class FileList(QtWidgets.QListWidget):
files_dropped = QtCore.pyqtSignal()
files_updated = QtCore.pyqtSignal()
- def __init__(self, parent=None):
+ def __init__(self, common, parent=None):
super(FileList, self).__init__(parent)
+
+ self.common = common
+
self.setAcceptDrops(True)
self.setIconSize(QtCore.QSize(32, 32))
self.setSortingEnabled(True)
- self.setMinimumHeight(205)
+ self.setMinimumHeight(160)
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
- self.drop_here_image = DropHereLabel(self, True)
- self.drop_here_text = DropHereLabel(self, False)
- self.drop_count = DropCountLabel(self)
+ self.drop_here_image = DropHereLabel(self.common, self, True)
+ self.drop_here_text = DropHereLabel(self.common, self, False)
+ self.drop_count = DropCountLabel(self.common, self)
self.resizeEvent(None)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
@@ -148,7 +158,7 @@ class FileList(QtWidgets.QListWidget):
dragEnterEvent for dragging files and directories into the widget.
"""
if event.mimeData().hasUrls:
- self.setStyleSheet('FileList { border: 3px solid #538ad0; }')
+ self.setStyleSheet(self.common.css['share_file_list_drag_enter'])
count = len(event.mimeData().urls())
self.drop_count.setText('+{}'.format(count))
@@ -163,7 +173,7 @@ class FileList(QtWidgets.QListWidget):
"""
dragLeaveEvent for dragging files and directories into the widget.
"""
- self.setStyleSheet('FileList { border: none; }')
+ self.setStyleSheet(self.common.css['share_file_list_drag_leave'])
self.drop_count.hide()
event.accept()
self.update()
@@ -191,7 +201,7 @@ class FileList(QtWidgets.QListWidget):
else:
event.ignore()
- self.setStyleSheet('border: none;')
+ self.setStyleSheet(self.common.css['share_file_list_drag_leave'])
self.drop_count.hide()
self.files_dropped.emit()
@@ -206,7 +216,7 @@ class FileList(QtWidgets.QListWidget):
if filename not in filenames:
if not os.access(filename, os.R_OK):
- Alert(strings._("not_a_readable_file", True).format(filename))
+ Alert(self.common, strings._("not_a_readable_file").format(filename))
return
fileinfo = QtCore.QFileInfo(filename)
@@ -215,10 +225,10 @@ class FileList(QtWidgets.QListWidget):
if os.path.isfile(filename):
size_bytes = fileinfo.size()
- size_readable = common.human_readable_filesize(size_bytes)
+ size_readable = self.common.human_readable_filesize(size_bytes)
else:
- size_bytes = common.dir_size(filename)
- size_readable = common.human_readable_filesize(size_bytes)
+ size_bytes = self.common.dir_size(filename)
+ size_readable = self.common.human_readable_filesize(size_bytes)
# Create a new item
item = QtWidgets.QListWidgetItem()
@@ -228,7 +238,7 @@ class FileList(QtWidgets.QListWidget):
# Item's filename attribute and size labels
item.filename = filename
item_size = QtWidgets.QLabel(size_readable)
- item_size.setStyleSheet('QLabel { color: #666666; font-size: 11px; }')
+ item_size.setStyleSheet(self.common.css['share_file_list_item_size'])
item.basename = os.path.basename(filename.rstrip('/'))
# Use the basename as the method with which to sort the list
@@ -245,12 +255,13 @@ class FileList(QtWidgets.QListWidget):
item.item_button = QtWidgets.QPushButton()
item.item_button.setDefault(False)
item.item_button.setFlat(True)
- item.item_button.setIcon( QtGui.QIcon(common.get_resource_path('images/file_delete.png')) )
+ item.item_button.setIcon( QtGui.QIcon(self.common.get_resource_path('images/file_delete.png')) )
item.item_button.clicked.connect(delete_item)
item.item_button.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
# Item info widget, with a white background
item_info_layout = QtWidgets.QHBoxLayout()
+ item_info_layout.setContentsMargins(0, 0, 0, 0)
item_info_layout.addWidget(item_size)
item_info_layout.addWidget(item.item_button)
item_info = QtWidgets.QWidget()
@@ -277,20 +288,23 @@ class FileSelection(QtWidgets.QVBoxLayout):
The list of files and folders in the GUI, as well as buttons to add and
delete the files and folders.
"""
- def __init__(self):
+ def __init__(self, common):
super(FileSelection, self).__init__()
+
+ self.common = common
+
self.server_on = False
# File list
- self.file_list = FileList()
+ self.file_list = FileList(self.common)
self.file_list.itemSelectionChanged.connect(self.update)
self.file_list.files_dropped.connect(self.update)
self.file_list.files_updated.connect(self.update)
# Buttons
- self.add_button = QtWidgets.QPushButton(strings._('gui_add', True))
+ self.add_button = QtWidgets.QPushButton(strings._('gui_add'))
self.add_button.clicked.connect(self.add)
- self.delete_button = QtWidgets.QPushButton(strings._('gui_delete', True))
+ self.delete_button = QtWidgets.QPushButton(strings._('gui_delete'))
self.delete_button.clicked.connect(self.delete)
button_layout = QtWidgets.QHBoxLayout()
button_layout.addStretch()
@@ -327,7 +341,7 @@ class FileSelection(QtWidgets.QVBoxLayout):
"""
Add button clicked.
"""
- file_dialog = FileDialog(caption=strings._('gui_choose_items', True))
+ file_dialog = AddFileDialog(self.common, caption=strings._('gui_choose_items'))
if file_dialog.exec_() == QtWidgets.QDialog.Accepted:
for filename in file_dialog.selectedFiles():
self.file_list.add_file(filename)
@@ -375,22 +389,3 @@ class FileSelection(QtWidgets.QVBoxLayout):
Set the Qt app focus on the file selection box.
"""
self.file_list.setFocus()
-
-class FileDialog(QtWidgets.QFileDialog):
- """
- Overridden version of QFileDialog which allows us to select
- folders as well as, or instead of, files.
- """
- def __init__(self, *args, **kwargs):
- QtWidgets.QFileDialog.__init__(self, *args, **kwargs)
- self.setOption(self.DontUseNativeDialog, True)
- self.setOption(self.ReadOnly, True)
- self.setOption(self.ShowDirsOnly, False)
- self.setFileMode(self.ExistingFiles)
- tree_view = self.findChild(QtWidgets.QTreeView)
- tree_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
- list_view = self.findChild(QtWidgets.QListView, "listView")
- list_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
-
- def accept(self):
- QtWidgets.QDialog.accept(self)
diff --git a/onionshare_gui/mode/share_mode/threads.py b/onionshare_gui/mode/share_mode/threads.py
new file mode 100644
index 00000000..24e2c242
--- /dev/null
+++ b/onionshare_gui/mode/share_mode/threads.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+from PyQt5 import QtCore
+
+
+class CompressThread(QtCore.QThread):
+ """
+ Compresses files to be shared
+ """
+ success = QtCore.pyqtSignal()
+ error = QtCore.pyqtSignal(str)
+
+ def __init__(self, mode):
+ super(CompressThread, self).__init__()
+ self.mode = mode
+ self.mode.common.log('CompressThread', '__init__')
+
+ # prepare files to share
+ def set_processed_size(self, x):
+ if self.mode._zip_progress_bar != None:
+ self.mode._zip_progress_bar.update_processed_size_signal.emit(x)
+
+ def run(self):
+ self.mode.common.log('CompressThread', 'run')
+
+ try:
+ if self.mode.web.share_mode.set_file_info(self.mode.filenames, processed_size_callback=self.set_processed_size):
+ self.success.emit()
+ else:
+ # Cancelled
+ pass
+
+ self.mode.app.cleanup_filenames += self.mode.web.share_mode.cleanup_filenames
+ except OSError as e:
+ self.error.emit(e.strerror)
+
+ def cancel(self):
+ self.mode.common.log('CompressThread', 'cancel')
+
+ # Let the Web and ZipWriter objects know that we're canceling compression early
+ self.mode.web.cancel_compression = True
+ try:
+ self.mode.web.zip_writer.cancel_compression = True
+ except AttributeError:
+ # we never made it as far as creating a ZipWriter object
+ pass
diff --git a/onionshare_gui/onionshare_gui.py b/onionshare_gui/onionshare_gui.py
index c05e3323..eab3261e 100644
--- a/onionshare_gui/onionshare_gui.py
+++ b/onionshare_gui/onionshare_gui.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -17,209 +17,171 @@ 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 <http://www.gnu.org/licenses/>.
"""
-import os, threading, time
+import queue
from PyQt5 import QtCore, QtWidgets, QtGui
-from onionshare import strings, common, web
-from onionshare.settings import Settings
-from onionshare.onion import *
+from onionshare import strings
+from onionshare.web import Web
+
+from .mode.share_mode import ShareMode
+from .mode.receive_mode import ReceiveMode
from .tor_connection_dialog import TorConnectionDialog
from .settings_dialog import SettingsDialog
-from .file_selection import FileSelection
-from .server_status import ServerStatus
-from .downloads import Downloads
-from .alert import Alert
+from .widgets import Alert
from .update_checker import UpdateThread
+from .server_status import ServerStatus
class OnionShareGui(QtWidgets.QMainWindow):
"""
OnionShareGui is the main window for the GUI that contains all of the
GUI elements.
"""
- start_server_finished = QtCore.pyqtSignal()
- stop_server_finished = QtCore.pyqtSignal()
- starting_server_step2 = QtCore.pyqtSignal()
- starting_server_step3 = QtCore.pyqtSignal()
- starting_server_error = QtCore.pyqtSignal(str)
+ MODE_SHARE = 'share'
+ MODE_RECEIVE = 'receive'
- def __init__(self, onion, qtapp, app, filenames, config=False):
+ def __init__(self, common, onion, qtapp, app, filenames, config=False, local_only=False):
super(OnionShareGui, self).__init__()
- self._initSystemTray()
-
- common.log('OnionShareGui', '__init__')
+ self.common = common
+ self.common.log('OnionShareGui', '__init__')
+ self.setMinimumWidth(820)
+ self.setMinimumHeight(660)
self.onion = onion
self.qtapp = qtapp
self.app = app
+ self.local_only = local_only
+
+ self.mode = self.MODE_SHARE
self.setWindowTitle('OnionShare')
- self.setWindowIcon(QtGui.QIcon(common.get_resource_path('images/logo.png')))
- self.setMinimumWidth(430)
+ self.setWindowIcon(QtGui.QIcon(self.common.get_resource_path('images/logo.png')))
- # Load settings
+ # Load settings, if a custom config was passed in
self.config = config
- self.settings = Settings(self.config)
- self.settings.load()
-
- # File selection
- self.file_selection = FileSelection()
- if filenames:
- for filename in filenames:
- self.file_selection.file_list.add_file(filename)
-
- # Server status
- self.server_status = ServerStatus(self.qtapp, self.app, web, self.file_selection, self.settings)
- self.server_status.server_started.connect(self.file_selection.server_started)
- self.server_status.server_started.connect(self.start_server)
- self.server_status.server_started.connect(self.update_server_status_indicator)
- self.server_status.server_stopped.connect(self.file_selection.server_stopped)
- self.server_status.server_stopped.connect(self.stop_server)
- self.server_status.server_stopped.connect(self.update_server_status_indicator)
- self.server_status.server_stopped.connect(self.update_primary_action)
- self.server_status.server_canceled.connect(self.cancel_server)
- self.server_status.server_canceled.connect(self.file_selection.server_stopped)
- self.server_status.server_canceled.connect(self.update_primary_action)
- self.start_server_finished.connect(self.clear_message)
- self.start_server_finished.connect(self.server_status.start_server_finished)
- self.start_server_finished.connect(self.update_server_status_indicator)
- self.stop_server_finished.connect(self.server_status.stop_server_finished)
- self.stop_server_finished.connect(self.update_server_status_indicator)
- self.file_selection.file_list.files_updated.connect(self.server_status.update)
- self.file_selection.file_list.files_updated.connect(self.update_primary_action)
- self.server_status.url_copied.connect(self.copy_url)
- self.server_status.hidservauth_copied.connect(self.copy_hidservauth)
- self.starting_server_step2.connect(self.start_server_step2)
- self.starting_server_step3.connect(self.start_server_step3)
- self.starting_server_error.connect(self.start_server_error)
- self.server_status.button_clicked.connect(self.clear_message)
-
- # Filesize warning
- self.filesize_warning = QtWidgets.QLabel()
- self.filesize_warning.setWordWrap(True)
- self.filesize_warning.setStyleSheet('padding: 10px 0; font-weight: bold; color: #333333;')
- self.filesize_warning.hide()
-
- # Downloads
- self.downloads = Downloads()
- self.downloads_container = QtWidgets.QScrollArea()
- self.downloads_container.setWidget(self.downloads)
- self.downloads_container.setWidgetResizable(True)
- self.downloads_container.setMaximumHeight(200)
- self.downloads_container.setMinimumHeight(75)
- self.vbar = self.downloads_container.verticalScrollBar()
- self.downloads_container.hide() # downloads start out hidden
- self.new_download = False
- self.downloads_in_progress = 0
- self.downloads_completed = 0
-
- # Info label along top of screen
- self.info_layout = QtWidgets.QHBoxLayout()
- self.info_label = QtWidgets.QLabel()
- self.info_label.setStyleSheet('QLabel { font-size: 12px; color: #666666; }')
-
- self.info_in_progress_downloads_count = QtWidgets.QLabel()
- self.info_in_progress_downloads_count.setStyleSheet('QLabel { font-size: 12px; color: #666666; }')
-
- self.info_completed_downloads_count = QtWidgets.QLabel()
- self.info_completed_downloads_count.setStyleSheet('QLabel { font-size: 12px; color: #666666; }')
-
- self.update_downloads_completed(self.downloads_in_progress)
- self.update_downloads_in_progress(self.downloads_in_progress)
-
- self.info_layout.addWidget(self.info_label)
- self.info_layout.addStretch()
- self.info_layout.addWidget(self.info_in_progress_downloads_count)
- self.info_layout.addWidget(self.info_completed_downloads_count)
-
- self.info_widget = QtWidgets.QWidget()
- self.info_widget.setLayout(self.info_layout)
- self.info_widget.hide()
-
- # Settings button on the status bar
+ if self.config:
+ self.common.load_settings(self.config)
+
+ # System tray
+ menu = QtWidgets.QMenu()
+ self.settings_action = menu.addAction(strings._('gui_settings_window_title'))
+ self.settings_action.triggered.connect(self.open_settings)
+ help_action = menu.addAction(strings._('gui_settings_button_help'))
+ help_action.triggered.connect(SettingsDialog.help_clicked)
+ exit_action = menu.addAction(strings._('systray_menu_exit'))
+ exit_action.triggered.connect(self.close)
+
+ self.system_tray = QtWidgets.QSystemTrayIcon(self)
+ # The convention is Mac systray icons are always grayscale
+ if self.common.platform == 'Darwin':
+ self.system_tray.setIcon(QtGui.QIcon(self.common.get_resource_path('images/logo_grayscale.png')))
+ else:
+ self.system_tray.setIcon(QtGui.QIcon(self.common.get_resource_path('images/logo.png')))
+ self.system_tray.setContextMenu(menu)
+ self.system_tray.show()
+
+ # Mode switcher, to switch between share files and receive files
+ self.share_mode_button = QtWidgets.QPushButton(strings._('gui_mode_share_button'));
+ self.share_mode_button.setFixedHeight(50)
+ self.share_mode_button.clicked.connect(self.share_mode_clicked)
+ self.receive_mode_button = QtWidgets.QPushButton(strings._('gui_mode_receive_button'));
+ self.receive_mode_button.setFixedHeight(50)
+ self.receive_mode_button.clicked.connect(self.receive_mode_clicked)
self.settings_button = QtWidgets.QPushButton()
self.settings_button.setDefault(False)
- self.settings_button.setFlat(True)
self.settings_button.setFixedWidth(40)
- self.settings_button.setIcon( QtGui.QIcon(common.get_resource_path('images/settings.png')) )
+ self.settings_button.setFixedHeight(50)
+ self.settings_button.setIcon( QtGui.QIcon(self.common.get_resource_path('images/settings.png')) )
self.settings_button.clicked.connect(self.open_settings)
+ self.settings_button.setStyleSheet(self.common.css['settings_button'])
+ mode_switcher_layout = QtWidgets.QHBoxLayout();
+ mode_switcher_layout.setSpacing(0)
+ mode_switcher_layout.addWidget(self.share_mode_button)
+ mode_switcher_layout.addWidget(self.receive_mode_button)
+ mode_switcher_layout.addWidget(self.settings_button)
# Server status indicator on the status bar
- self.server_status_image_stopped = QtGui.QImage(common.get_resource_path('images/server_stopped.png'))
- self.server_status_image_working = QtGui.QImage(common.get_resource_path('images/server_working.png'))
- self.server_status_image_started = QtGui.QImage(common.get_resource_path('images/server_started.png'))
+ self.server_status_image_stopped = QtGui.QImage(self.common.get_resource_path('images/server_stopped.png'))
+ self.server_status_image_working = QtGui.QImage(self.common.get_resource_path('images/server_working.png'))
+ self.server_status_image_started = QtGui.QImage(self.common.get_resource_path('images/server_started.png'))
self.server_status_image_label = QtWidgets.QLabel()
self.server_status_image_label.setFixedWidth(20)
- self.server_status_label = QtWidgets.QLabel()
- self.server_status_label.setStyleSheet('QLabel { font-style: italic; color: #666666; }')
+ self.server_status_label = QtWidgets.QLabel('')
+ self.server_status_label.setStyleSheet(self.common.css['server_status_indicator_label'])
server_status_indicator_layout = QtWidgets.QHBoxLayout()
server_status_indicator_layout.addWidget(self.server_status_image_label)
server_status_indicator_layout.addWidget(self.server_status_label)
self.server_status_indicator = QtWidgets.QWidget()
self.server_status_indicator.setLayout(server_status_indicator_layout)
- self.update_server_status_indicator()
# Status bar
self.status_bar = QtWidgets.QStatusBar()
self.status_bar.setSizeGripEnabled(False)
- statusBar_cssStyleData ="""
- QStatusBar {
- font-style: italic;
- color: #666666;
- }
-
- QStatusBar::item {
- border: 0px;
- }"""
-
- self.status_bar.setStyleSheet(statusBar_cssStyleData)
+ self.status_bar.setStyleSheet(self.common.css['status_bar'])
self.status_bar.addPermanentWidget(self.server_status_indicator)
- self.status_bar.addPermanentWidget(self.settings_button)
self.setStatusBar(self.status_bar)
- # Status bar, zip progress bar
- self._zip_progress_bar = None
- # Status bar, sharing messages
- self.server_share_status_label = QtWidgets.QLabel('')
- self.server_share_status_label.setStyleSheet('QLabel { font-style: italic; color: #666666; padding: 2px; }')
- self.status_bar.insertWidget(0, self.server_share_status_label)
-
- # Primary action layout
- primary_action_layout = QtWidgets.QVBoxLayout()
- primary_action_layout.addWidget(self.server_status)
- primary_action_layout.addWidget(self.filesize_warning)
- primary_action_layout.addWidget(self.downloads_container)
- self.primary_action = QtWidgets.QWidget()
- self.primary_action.setLayout(primary_action_layout)
- self.primary_action.hide()
- self.update_primary_action()
-
- # Main layout
- self.layout = QtWidgets.QVBoxLayout()
- self.layout.addWidget(self.info_widget)
- self.layout.addLayout(self.file_selection)
- self.layout.addWidget(self.primary_action)
+ # Share mode
+ self.share_mode = ShareMode(self.common, qtapp, app, self.status_bar, self.server_status_label, self.system_tray, filenames, self.local_only)
+ self.share_mode.init()
+ self.share_mode.server_status.server_started.connect(self.update_server_status_indicator)
+ self.share_mode.server_status.server_stopped.connect(self.update_server_status_indicator)
+ self.share_mode.start_server_finished.connect(self.update_server_status_indicator)
+ self.share_mode.stop_server_finished.connect(self.update_server_status_indicator)
+ self.share_mode.stop_server_finished.connect(self.stop_server_finished)
+ self.share_mode.start_server_finished.connect(self.clear_message)
+ self.share_mode.server_status.button_clicked.connect(self.clear_message)
+ self.share_mode.server_status.url_copied.connect(self.copy_url)
+ self.share_mode.server_status.hidservauth_copied.connect(self.copy_hidservauth)
+ self.share_mode.set_server_active.connect(self.set_server_active)
+
+ # Receive mode
+ self.receive_mode = ReceiveMode(self.common, qtapp, app, self.status_bar, self.server_status_label, self.system_tray, None, self.local_only)
+ self.receive_mode.init()
+ self.receive_mode.server_status.server_started.connect(self.update_server_status_indicator)
+ self.receive_mode.server_status.server_stopped.connect(self.update_server_status_indicator)
+ self.receive_mode.start_server_finished.connect(self.update_server_status_indicator)
+ self.receive_mode.stop_server_finished.connect(self.update_server_status_indicator)
+ self.receive_mode.stop_server_finished.connect(self.stop_server_finished)
+ self.receive_mode.start_server_finished.connect(self.clear_message)
+ self.receive_mode.server_status.button_clicked.connect(self.clear_message)
+ self.receive_mode.server_status.url_copied.connect(self.copy_url)
+ self.receive_mode.server_status.hidservauth_copied.connect(self.copy_hidservauth)
+ self.receive_mode.set_server_active.connect(self.set_server_active)
+
+ self.update_mode_switcher()
+ self.update_server_status_indicator()
+
+ # Layouts
+ contents_layout = QtWidgets.QVBoxLayout()
+ contents_layout.setContentsMargins(10, 0, 10, 0)
+ contents_layout.addWidget(self.receive_mode)
+ contents_layout.addWidget(self.share_mode)
+
+ layout = QtWidgets.QVBoxLayout()
+ layout.setContentsMargins(0, 0, 0, 0)
+ layout.addLayout(mode_switcher_layout)
+ layout.addLayout(contents_layout)
+
central_widget = QtWidgets.QWidget()
- central_widget.setLayout(self.layout)
+ central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.show()
- # Always start with focus on file selection
- self.file_selection.setFocus()
-
# The server isn't active yet
self.set_server_active(False)
# Create the timer
self.timer = QtCore.QTimer()
- self.timer.timeout.connect(self.check_for_requests)
+ self.timer.timeout.connect(self.timer_callback)
# Start the "Connecting to Tor" dialog, which calls onion.connect()
- tor_con = TorConnectionDialog(self.qtapp, self.settings, self.onion)
+ tor_con = TorConnectionDialog(self.common, self.qtapp, self.onion)
tor_con.canceled.connect(self._tor_connection_canceled)
tor_con.open_settings.connect(self._tor_connection_open_settings)
- tor_con.start()
+ if not self.local_only:
+ tor_con.start()
# Start the timer
self.timer.start(500)
@@ -227,77 +189,76 @@ class OnionShareGui(QtWidgets.QMainWindow):
# After connecting to Tor, check for updates
self.check_for_updates()
- def update_primary_action(self):
- # Show or hide primary action layout
- file_count = self.file_selection.file_list.count()
- if file_count > 0:
- self.primary_action.show()
- self.info_widget.show()
-
- # Update the file count in the info label
- total_size_bytes = 0
- for index in range(self.file_selection.file_list.count()):
- item = self.file_selection.file_list.item(index)
- total_size_bytes += item.size_bytes
- total_size_readable = common.human_readable_filesize(total_size_bytes)
-
- if file_count > 1:
- self.info_label.setText(strings._('gui_file_info', True).format(file_count, total_size_readable))
- else:
- self.info_label.setText(strings._('gui_file_info_single', True).format(file_count, total_size_readable))
+ def update_mode_switcher(self):
+ # Based on the current mode, switch the mode switcher button styles,
+ # and show and hide widgets to switch modes
+ if self.mode == self.MODE_SHARE:
+ self.share_mode_button.setStyleSheet(self.common.css['mode_switcher_selected_style'])
+ self.receive_mode_button.setStyleSheet(self.common.css['mode_switcher_unselected_style'])
+ self.receive_mode.hide()
+ self.share_mode.show()
else:
- self.primary_action.hide()
- self.info_widget.hide()
+ self.share_mode_button.setStyleSheet(self.common.css['mode_switcher_unselected_style'])
+ self.receive_mode_button.setStyleSheet(self.common.css['mode_switcher_selected_style'])
- # Resize window
- self.adjustSize()
+ self.share_mode.hide()
+ self.receive_mode.show()
- def update_server_status_indicator(self):
- common.log('OnionShareGui', 'update_server_status_indicator')
+ self.update_server_status_indicator()
- # Set the status image
- if self.server_status.status == self.server_status.STATUS_STOPPED:
- self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_stopped))
- self.server_status_label.setText(strings._('gui_status_indicator_stopped', True))
- elif self.server_status.status == self.server_status.STATUS_WORKING:
- self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_working))
- self.server_status_label.setText(strings._('gui_status_indicator_working', True))
- elif self.server_status.status == self.server_status.STATUS_STARTED:
- self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_started))
- self.server_status_label.setText(strings._('gui_status_indicator_started', True))
-
- def _initSystemTray(self):
- system = common.get_platform()
+ def share_mode_clicked(self):
+ if self.mode != self.MODE_SHARE:
+ self.common.log('OnionShareGui', 'share_mode_clicked')
+ self.mode = self.MODE_SHARE
+ self.update_mode_switcher()
- menu = QtWidgets.QMenu()
- self.settingsAction = menu.addAction(strings._('gui_settings_window_title', True))
- self.settingsAction.triggered.connect(self.open_settings)
- self.helpAction = menu.addAction(strings._('gui_settings_button_help', True))
- self.helpAction.triggered.connect(SettingsDialog.help_clicked)
- self.exitAction = menu.addAction(strings._('systray_menu_exit', True))
- self.exitAction.triggered.connect(self.close)
-
- self.systemTray = QtWidgets.QSystemTrayIcon(self)
- # The convention is Mac systray icons are always grayscale
- if system == 'Darwin':
- self.systemTray.setIcon(QtGui.QIcon(common.get_resource_path('images/logo_grayscale.png')))
+ def receive_mode_clicked(self):
+ if self.mode != self.MODE_RECEIVE:
+ self.common.log('OnionShareGui', 'receive_mode_clicked')
+ self.mode = self.MODE_RECEIVE
+ self.update_mode_switcher()
+
+ def update_server_status_indicator(self):
+ # Set the status image
+ if self.mode == self.MODE_SHARE:
+ # Share mode
+ if self.share_mode.server_status.status == ServerStatus.STATUS_STOPPED:
+ self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_stopped))
+ self.server_status_label.setText(strings._('gui_status_indicator_share_stopped'))
+ elif self.share_mode.server_status.status == ServerStatus.STATUS_WORKING:
+ self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_working))
+ self.server_status_label.setText(strings._('gui_status_indicator_share_working'))
+ elif self.share_mode.server_status.status == ServerStatus.STATUS_STARTED:
+ self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_started))
+ self.server_status_label.setText(strings._('gui_status_indicator_share_started'))
else:
- self.systemTray.setIcon(QtGui.QIcon(common.get_resource_path('images/logo.png')))
- self.systemTray.setContextMenu(menu)
- self.systemTray.show()
+ # Receive mode
+ if self.receive_mode.server_status.status == ServerStatus.STATUS_STOPPED:
+ self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_stopped))
+ self.server_status_label.setText(strings._('gui_status_indicator_receive_stopped'))
+ elif self.receive_mode.server_status.status == ServerStatus.STATUS_WORKING:
+ self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_working))
+ self.server_status_label.setText(strings._('gui_status_indicator_receive_working'))
+ elif self.receive_mode.server_status.status == ServerStatus.STATUS_STARTED:
+ self.server_status_image_label.setPixmap(QtGui.QPixmap.fromImage(self.server_status_image_started))
+ self.server_status_label.setText(strings._('gui_status_indicator_receive_started'))
+
+ def stop_server_finished(self):
+ # When the server stopped, cleanup the ephemeral onion service
+ self.onion.cleanup(stop_tor=False)
def _tor_connection_canceled(self):
"""
If the user cancels before Tor finishes connecting, ask if they want to
quit, or open settings.
"""
- common.log('OnionShareGui', '_tor_connection_canceled')
+ self.common.log('OnionShareGui', '_tor_connection_canceled')
def ask():
- a = Alert(strings._('gui_tor_connection_ask', True), QtWidgets.QMessageBox.Question, buttons=QtWidgets.QMessageBox.NoButton, autostart=False)
- settings_button = QtWidgets.QPushButton(strings._('gui_tor_connection_ask_open_settings', True))
- quit_button = QtWidgets.QPushButton(strings._('gui_tor_connection_ask_quit', True))
+ a = Alert(self.common, strings._('gui_tor_connection_ask'), QtWidgets.QMessageBox.Question, buttons=QtWidgets.QMessageBox.NoButton, autostart=False)
+ settings_button = QtWidgets.QPushButton(strings._('gui_tor_connection_ask_open_settings'))
+ quit_button = QtWidgets.QPushButton(strings._('gui_tor_connection_ask_quit'))
a.addButton(settings_button, QtWidgets.QMessageBox.AcceptRole)
a.addButton(quit_button, QtWidgets.QMessageBox.RejectRole)
a.setDefaultButton(settings_button)
@@ -305,12 +266,12 @@ class OnionShareGui(QtWidgets.QMainWindow):
if a.clickedButton() == settings_button:
# Open settings
- common.log('OnionShareGui', '_tor_connection_canceled', 'Settings button clicked')
+ self.common.log('OnionShareGui', '_tor_connection_canceled', 'Settings button clicked')
self.open_settings()
if a.clickedButton() == quit_button:
# Quit
- common.log('OnionShareGui', '_tor_connection_canceled', 'Quit button clicked')
+ self.common.log('OnionShareGui', '_tor_connection_canceled', 'Quit button clicked')
# Wait 1ms for the event loop to finish, then quit
QtCore.QTimer.singleShot(1, self.qtapp.quit)
@@ -322,7 +283,7 @@ class OnionShareGui(QtWidgets.QMainWindow):
"""
The TorConnectionDialog wants to open the Settings dialog
"""
- common.log('OnionShareGui', '_tor_connection_open_settings')
+ self.common.log('OnionShareGui', '_tor_connection_open_settings')
# Wait 1ms for the event loop to finish closing the TorConnectionDialog
QtCore.QTimer.singleShot(1, self.open_settings)
@@ -331,337 +292,132 @@ class OnionShareGui(QtWidgets.QMainWindow):
"""
Open the SettingsDialog.
"""
- common.log('OnionShareGui', 'open_settings')
+ self.common.log('OnionShareGui', 'open_settings')
def reload_settings():
- common.log('OnionShareGui', 'open_settings', 'settings have changed, reloading')
- self.settings.load()
+ self.common.log('OnionShareGui', 'open_settings', 'settings have changed, reloading')
+ self.common.settings.load()
+
# We might've stopped the main requests timer if a Tor connection failed.
# If we've reloaded settings, we probably succeeded in obtaining a new
# connection. If so, restart the timer.
- if self.onion.is_authenticated():
- if not self.timer.isActive():
- self.timer.start(500)
- # If there were some files listed for sharing, we should be ok to
- # re-enable the 'Start Sharing' button now.
- if self.server_status.file_selection.get_num_files() > 0:
- self.server_status.server_button.setEnabled(True)
- self.status_bar.clearMessage()
+ if not self.local_only:
+ if self.onion.is_authenticated():
+ if not self.timer.isActive():
+ self.timer.start(500)
+ self.share_mode.on_reload_settings()
+ self.receive_mode.on_reload_settings()
+ self.status_bar.clearMessage()
+
# If we switched off the shutdown timeout setting, ensure the widget is hidden.
- if not self.settings.get('shutdown_timeout'):
- self.server_status.shutdown_timeout_container.hide()
+ if not self.common.settings.get('shutdown_timeout'):
+ self.share_mode.server_status.shutdown_timeout_container.hide()
+ self.receive_mode.server_status.shutdown_timeout_container.hide()
- d = SettingsDialog(self.onion, self.qtapp, self.config)
+ d = SettingsDialog(self.common, self.onion, self.qtapp, self.config, self.local_only)
d.settings_saved.connect(reload_settings)
d.exec_()
# When settings close, refresh the server status UI
- self.server_status.update()
-
- def start_server(self):
- """
- Start the onionshare server. This uses multiple threads to start the Tor onion
- server and the web app.
- """
- common.log('OnionShareGui', 'start_server')
-
- self.set_server_active(True)
-
- self.app.set_stealth(self.settings.get('use_stealth'))
-
- # Hide and reset the downloads if we have previously shared
- self.downloads_container.hide()
- self.downloads.reset_downloads()
- self.reset_info_counters()
- self.status_bar.clearMessage()
- self.server_share_status_label.setText('')
-
- # Reset web counters
- web.download_count = 0
- web.error404_count = 0
- web.set_gui_mode()
-
- # start the onion service in a new thread
- def start_onion_service(self):
- try:
- self.app.start_onion_service()
- self.starting_server_step2.emit()
-
- except (TorTooOld, TorErrorInvalidSetting, TorErrorAutomatic, TorErrorSocketPort, TorErrorSocketFile, TorErrorMissingPassword, TorErrorUnreadableCookieFile, TorErrorAuthError, TorErrorProtocolError, BundledTorTimeout, OSError) as e:
- self.starting_server_error.emit(e.args[0])
- return
-
-
- self.app.stay_open = not self.settings.get('close_after_first_download')
-
- # start onionshare http service in new thread
- t = threading.Thread(target=web.start, args=(self.app.port, self.app.stay_open, self.settings.get('slug')))
- t.daemon = True
- t.start()
- # wait for modules in thread to load, preventing a thread-related cx_Freeze crash
- time.sleep(0.2)
-
- common.log('OnionshareGui', 'start_server', 'Starting an onion thread')
- self.t = OnionThread(function=start_onion_service, kwargs={'self': self})
- self.t.daemon = True
- self.t.start()
-
- def start_server_step2(self):
- """
- Step 2 in starting the onionshare server. Zipping up files.
- """
- common.log('OnionShareGui', 'start_server_step2')
-
- # add progress bar to the status bar, indicating the crunching of files.
- self._zip_progress_bar = ZipProgressBar(0)
- self.filenames = []
- for index in range(self.file_selection.file_list.count()):
- self.filenames.append(self.file_selection.file_list.item(index).filename)
-
- self._zip_progress_bar.total_files_size = OnionShareGui._compute_total_size(self.filenames)
- self.status_bar.insertWidget(0, self._zip_progress_bar)
-
- # prepare the files for sending in a new thread
- def finish_starting_server(self):
- # prepare files to share
- def _set_processed_size(x):
- if self._zip_progress_bar != None:
- self._zip_progress_bar.update_processed_size_signal.emit(x)
- try:
- web.set_file_info(self.filenames, processed_size_callback=_set_processed_size)
- self.app.cleanup_filenames.append(web.zip_filename)
- self.starting_server_step3.emit()
-
- # done
- self.start_server_finished.emit()
- except OSError as e:
- self.starting_server_error.emit(e.strerror)
- return
-
- t = threading.Thread(target=finish_starting_server, kwargs={'self': self})
- t.daemon = True
- t.start()
-
- def start_server_step3(self):
- """
- Step 3 in starting the onionshare server. This displays the large filesize
- warning, if applicable.
- """
- common.log('OnionShareGui', 'start_server_step3')
-
- # Remove zip progress bar
- if self._zip_progress_bar is not None:
- self.status_bar.removeWidget(self._zip_progress_bar)
- self._zip_progress_bar = None
-
- # warn about sending large files over Tor
- if web.zip_filesize >= 157286400: # 150mb
- self.filesize_warning.setText(strings._("large_filesize", True))
- self.filesize_warning.show()
-
- if self.settings.get('shutdown_timeout'):
- # Convert the date value to seconds between now and then
- now = QtCore.QDateTime.currentDateTime()
- self.timeout = now.secsTo(self.server_status.timeout)
- # Set the shutdown timeout value
- if self.timeout > 0:
- self.app.shutdown_timer = common.close_after_seconds(self.timeout)
- self.app.shutdown_timer.start()
- # The timeout has actually already passed since the user clicked Start. Probably the Onion service took too long to start.
- else:
- self.stop_server()
- self.start_server_error(strings._('gui_server_started_after_timeout'))
-
- def start_server_error(self, error):
- """
- If there's an error when trying to start the onion service
- """
- common.log('OnionShareGui', 'start_server_error')
-
- self.set_server_active(False)
-
- Alert(error, QtWidgets.QMessageBox.Warning)
- self.server_status.stop_server()
- if self._zip_progress_bar is not None:
- self.status_bar.removeWidget(self._zip_progress_bar)
- self._zip_progress_bar = None
- self.status_bar.clearMessage()
-
- def cancel_server(self):
- """
- Cancel the server while it is preparing to start
- """
- if self.t:
- self.t.quit()
- self.stop_server()
-
- def stop_server(self):
- """
- Stop the onionshare server.
- """
- common.log('OnionShareGui', 'stop_server')
-
- if self.server_status.status != self.server_status.STATUS_STOPPED:
- try:
- web.stop(self.app.port)
- except:
- # Probably we had no port to begin with (Onion service didn't start)
- pass
- self.app.cleanup()
- # Remove ephemeral service, but don't disconnect from Tor
- self.onion.cleanup(stop_tor=False)
- self.filesize_warning.hide()
- self.downloads_in_progress = 0
- self.downloads_completed = 0
- self.update_downloads_in_progress(0)
- self.file_selection.file_list.adjustSize()
-
- self.set_server_active(False)
- self.stop_server_finished.emit()
+ self.share_mode.server_status.update()
+ self.receive_mode.server_status.update()
def check_for_updates(self):
"""
Check for updates in a new thread, if enabled.
"""
- system = common.get_platform()
- if system == 'Windows' or system == 'Darwin':
- if self.settings.get('use_autoupdate'):
+ if self.common.platform == 'Windows' or self.common.platform == 'Darwin':
+ if self.common.settings.get('use_autoupdate'):
def update_available(update_url, installed_version, latest_version):
- Alert(strings._("update_available", True).format(update_url, installed_version, latest_version))
+ Alert(self.common, strings._("update_available").format(update_url, installed_version, latest_version))
- self.update_thread = UpdateThread(self.onion, self.config)
+ self.update_thread = UpdateThread(self.common, self.onion, self.config)
self.update_thread.update_available.connect(update_available)
self.update_thread.start()
- @staticmethod
- def _compute_total_size(filenames):
- total_size = 0
- for filename in filenames:
- if os.path.isfile(filename):
- total_size += os.path.getsize(filename)
- if os.path.isdir(filename):
- total_size += common.dir_size(filename)
- return total_size
-
- def check_for_requests(self):
+ def timer_callback(self):
"""
- Check for messages communicated from the web app, and update the GUI accordingly.
+ Check for messages communicated from the web app, and update the GUI accordingly. Also,
+ call ShareMode and ReceiveMode's timer_callbacks.
"""
self.update()
- # Have we lost connection to Tor somehow?
- if not self.onion.is_authenticated():
- self.timer.stop()
- if self.server_status.status != self.server_status.STATUS_STOPPED:
- self.server_status.stop_server()
- self.server_status.server_button.setEnabled(False)
- self.status_bar.showMessage(strings._('gui_tor_connection_lost', True))
- if self.systemTray.supportsMessages() and self.settings.get('systray_notifications'):
- self.systemTray.showMessage(strings._('gui_tor_connection_lost', True), strings._('gui_tor_connection_error_settings', True))
-
- # scroll to the bottom of the dl progress bar log pane
- # if a new download has been added
- if self.new_download:
- self.vbar.setValue(self.vbar.maximum())
- self.new_download = False
+ if not self.local_only:
+ # Have we lost connection to Tor somehow?
+ if not self.onion.is_authenticated():
+ self.timer.stop()
+ self.status_bar.showMessage(strings._('gui_tor_connection_lost'))
+ self.system_tray.showMessage(strings._('gui_tor_connection_lost'), strings._('gui_tor_connection_error_settings'))
+
+ self.share_mode.handle_tor_broke()
+ self.receive_mode.handle_tor_broke()
+
+ # Process events from the web object
+ if self.mode == self.MODE_SHARE:
+ mode = self.share_mode
+ else:
+ mode = self.receive_mode
events = []
done = False
while not done:
try:
- r = web.q.get(False)
+ r = mode.web.q.get(False)
events.append(r)
- except web.queue.Empty:
+ except queue.Empty:
done = True
for event in events:
- if event["type"] == web.REQUEST_LOAD:
- self.status_bar.showMessage(strings._('download_page_loaded', True))
-
- elif event["type"] == web.REQUEST_DOWNLOAD:
- self.downloads_container.show() # show the downloads layout
- self.downloads.add_download(event["data"]["id"], web.zip_filesize)
- self.new_download = True
- self.downloads_in_progress += 1
- self.update_downloads_in_progress(self.downloads_in_progress)
- if self.systemTray.supportsMessages() and self.settings.get('systray_notifications'):
- self.systemTray.showMessage(strings._('systray_download_started_title', True), strings._('systray_download_started_message', True))
-
- elif event["type"] == web.REQUEST_RATE_LIMIT:
- self.stop_server()
- Alert(strings._('error_rate_limit'), QtWidgets.QMessageBox.Critical)
-
- elif event["type"] == web.REQUEST_PROGRESS:
- self.downloads.update_download(event["data"]["id"], event["data"]["bytes"])
-
- # is the download complete?
- if event["data"]["bytes"] == web.zip_filesize:
- if self.systemTray.supportsMessages() and self.settings.get('systray_notifications'):
- self.systemTray.showMessage(strings._('systray_download_completed_title', True), strings._('systray_download_completed_message', True))
- # Update the total 'completed downloads' info
- self.downloads_completed += 1
- self.update_downloads_completed(self.downloads_completed)
- # Update the 'in progress downloads' info
- self.downloads_in_progress -= 1
- self.update_downloads_in_progress(self.downloads_in_progress)
-
- # close on finish?
- if not web.get_stay_open():
- self.server_status.stop_server()
- self.status_bar.clearMessage()
- self.server_share_status_label.setText(strings._('closing_automatically', True))
- else:
- if self.server_status.status == self.server_status.STATUS_STOPPED:
- self.downloads.cancel_download(event["data"]["id"])
- self.downloads_in_progress = 0
- self.update_downloads_in_progress(self.downloads_in_progress)
-
-
- elif event["type"] == web.REQUEST_CANCELED:
- self.downloads.cancel_download(event["data"]["id"])
- # Update the 'in progress downloads' info
- self.downloads_in_progress -= 1
- self.update_downloads_in_progress(self.downloads_in_progress)
- if self.systemTray.supportsMessages() and self.settings.get('systray_notifications'):
- self.systemTray.showMessage(strings._('systray_download_canceled_title', True), strings._('systray_download_canceled_message', True))
-
- elif event["path"] != '/favicon.ico':
- self.status_bar.showMessage('[#{0:d}] {1:s}: {2:s}'.format(web.error404_count, strings._('other_page_loaded', True), event["path"]))
-
- # If the auto-shutdown timer has stopped, stop the server
- if self.server_status.status == self.server_status.STATUS_STARTED:
- if self.app.shutdown_timer and self.settings.get('shutdown_timeout'):
- if self.timeout > 0:
- now = QtCore.QDateTime.currentDateTime()
- seconds_remaining = now.secsTo(self.server_status.timeout)
- self.server_status.server_button.setText(strings._('gui_stop_server_shutdown_timeout', True).format(seconds_remaining))
- if not self.app.shutdown_timer.is_alive():
- # If there were no attempts to download the share, or all downloads are done, we can stop
- if web.download_count == 0 or web.done:
- self.server_status.stop_server()
- self.status_bar.clearMessage()
- self.server_share_status_label.setText(strings._('close_on_timeout', True))
- # A download is probably still running - hold off on stopping the share
- else:
- self.status_bar.clearMessage()
- self.server_share_status_label.setText(strings._('timeout_download_still_running', True))
+ if event["type"] == Web.REQUEST_LOAD:
+ mode.handle_request_load(event)
+
+ elif event["type"] == Web.REQUEST_STARTED:
+ mode.handle_request_started(event)
+
+ elif event["type"] == Web.REQUEST_RATE_LIMIT:
+ mode.handle_request_rate_limit(event)
+
+ elif event["type"] == Web.REQUEST_PROGRESS:
+ mode.handle_request_progress(event)
+
+ elif event["type"] == Web.REQUEST_CANCELED:
+ mode.handle_request_canceled(event)
+
+ elif event["type"] == Web.REQUEST_CLOSE_SERVER:
+ mode.handle_request_close_server(event)
+
+ elif event["type"] == Web.REQUEST_UPLOAD_FILE_RENAMED:
+ mode.handle_request_upload_file_renamed(event)
+
+ elif event["type"] == Web.REQUEST_UPLOAD_SET_DIR:
+ mode.handle_request_upload_set_dir(event)
+
+ elif event["type"] == Web.REQUEST_UPLOAD_FINISHED:
+ mode.handle_request_upload_finished(event)
+
+ if event["type"] == Web.REQUEST_ERROR_DOWNLOADS_DIR_CANNOT_CREATE:
+ Alert(self.common, strings._('error_cannot_create_downloads_dir').format(event["data"]["receive_mode_dir"]))
+
+ if event["type"] == Web.REQUEST_OTHER:
+ if event["path"] != '/favicon.ico' and event["path"] != "/{}/shutdown".format(mode.web.shutdown_slug):
+ self.status_bar.showMessage('[#{0:d}] {1:s}: {2:s}'.format(mode.web.error404_count, strings._('other_page_loaded'), event["path"]))
+
+ mode.timer_callback()
def copy_url(self):
"""
When the URL gets copied to the clipboard, display this in the status bar.
"""
- common.log('OnionShareGui', 'copy_url')
- if self.systemTray.supportsMessages() and self.settings.get('systray_notifications'):
- self.systemTray.showMessage(strings._('gui_copied_url_title', True), strings._('gui_copied_url', True))
+ self.common.log('OnionShareGui', 'copy_url')
+ self.system_tray.showMessage(strings._('gui_copied_url_title'), strings._('gui_copied_url'))
def copy_hidservauth(self):
"""
When the stealth onion service HidServAuth gets copied to the clipboard, display this in the status bar.
"""
- common.log('OnionShareGui', 'copy_hidservauth')
- if self.systemTray.supportsMessages() and self.settings.get('systray_notifications'):
- self.systemTray.showMessage(strings._('gui_copied_hidservauth_title', True), strings._('gui_copied_hidservauth', True))
+ self.common.log('OnionShareGui', 'copy_hidservauth')
+ self.system_tray.showMessage(strings._('gui_copied_hidservauth_title'), strings._('gui_copied_hidservauth'))
def clear_message(self):
"""
@@ -671,56 +427,42 @@ class OnionShareGui(QtWidgets.QMainWindow):
def set_server_active(self, active):
"""
- Disable the Settings button while an OnionShare server is active.
+ Disable the Settings and Receive Files buttons while an Share Files server is active.
"""
if active:
self.settings_button.hide()
+ if self.mode == self.MODE_SHARE:
+ self.share_mode_button.show()
+ self.receive_mode_button.hide()
+ else:
+ self.share_mode_button.hide()
+ self.receive_mode_button.show()
else:
self.settings_button.show()
+ self.share_mode_button.show()
+ self.receive_mode_button.show()
# Disable settings menu action when server is active
- self.settingsAction.setEnabled(not active)
-
- def reset_info_counters(self):
- """
- Set the info counters back to zero.
- """
- self.update_downloads_completed(0)
- self.update_downloads_in_progress(0)
-
- def update_downloads_completed(self, count):
- """
- Update the 'Downloads completed' info widget.
- """
- if count == 0:
- self.info_completed_downloads_image = common.get_resource_path('images/download_completed_none.png')
- else:
- self.info_completed_downloads_image = common.get_resource_path('images/download_completed.png')
- self.info_completed_downloads_count.setText('<img src="{0:s}" /> {1:d}'.format(self.info_completed_downloads_image, count))
- self.info_completed_downloads_count.setToolTip(strings._('info_completed_downloads_tooltip', True).format(count))
-
- def update_downloads_in_progress(self, count):
- """
- Update the 'Downloads in progress' info widget.
- """
- if count == 0:
- self.info_in_progress_downloads_image = common.get_resource_path('images/download_in_progress_none.png')
- else:
- self.info_in_progress_downloads_image = common.get_resource_path('images/download_in_progress.png')
- self.info_in_progress_downloads_count.setText('<img src="{0:s}" /> {1:d}'.format(self.info_in_progress_downloads_image, count))
- self.info_in_progress_downloads_count.setToolTip(strings._('info_in_progress_downloads_tooltip', True).format(count))
+ self.settings_action.setEnabled(not active)
def closeEvent(self, e):
- common.log('OnionShareGui', 'closeEvent')
+ self.common.log('OnionShareGui', 'closeEvent')
try:
- if self.server_status.status != self.server_status.STATUS_STOPPED:
- common.log('OnionShareGui', 'closeEvent, opening warning dialog')
+ if self.mode == OnionShareGui.MODE_SHARE:
+ server_status = self.share_mode.server_status
+ else:
+ server_status = self.receive_mode.server_status
+ if server_status.status != server_status.STATUS_STOPPED:
+ self.common.log('OnionShareGui', 'closeEvent, opening warning dialog')
dialog = QtWidgets.QMessageBox()
- dialog.setWindowTitle(strings._('gui_quit_title', True))
- dialog.setText(strings._('gui_quit_warning', True))
+ dialog.setWindowTitle(strings._('gui_quit_title'))
+ if self.mode == OnionShareGui.MODE_SHARE:
+ dialog.setText(strings._('gui_share_quit_warning'))
+ else:
+ dialog.setText(strings._('gui_receive_quit_warning'))
dialog.setIcon(QtWidgets.QMessageBox.Critical)
- quit_button = dialog.addButton(strings._('gui_quit_warning_quit', True), QtWidgets.QMessageBox.YesRole)
- dont_quit_button = dialog.addButton(strings._('gui_quit_warning_dont_quit', True), QtWidgets.QMessageBox.NoRole)
+ quit_button = dialog.addButton(strings._('gui_quit_warning_quit'), QtWidgets.QMessageBox.YesRole)
+ dont_quit_button = dialog.addButton(strings._('gui_quit_warning_dont_quit'), QtWidgets.QMessageBox.NoRole)
dialog.setDefaultButton(dont_quit_button)
reply = dialog.exec_()
@@ -734,81 +476,3 @@ class OnionShareGui(QtWidgets.QMainWindow):
except:
e.accept()
-
-
-class ZipProgressBar(QtWidgets.QProgressBar):
- update_processed_size_signal = QtCore.pyqtSignal(int)
-
- def __init__(self, total_files_size):
- super(ZipProgressBar, self).__init__()
- self.setMaximumHeight(20)
- self.setMinimumWidth(200)
- self.setValue(0)
- self.setFormat(strings._('zip_progress_bar_format'))
- cssStyleData ="""
- QProgressBar {
- border: 1px solid #4e064f;
- background-color: #ffffff !important;
- text-align: center;
- color: #9b9b9b;
- }
-
- QProgressBar::chunk {
- border: 0px;
- background-color: #4e064f;
- width: 10px;
- }"""
- self.setStyleSheet(cssStyleData)
-
- self._total_files_size = total_files_size
- self._processed_size = 0
-
- self.update_processed_size_signal.connect(self.update_processed_size)
-
- @property
- def total_files_size(self):
- return self._total_files_size
-
- @total_files_size.setter
- def total_files_size(self, val):
- self._total_files_size = val
-
- @property
- def processed_size(self):
- return self._processed_size
-
- @processed_size.setter
- def processed_size(self, val):
- self.update_processed_size(val)
-
- def update_processed_size(self, val):
- self._processed_size = val
- if self.processed_size < self.total_files_size:
- self.setValue(int((self.processed_size * 100) / self.total_files_size))
- elif self.total_files_size != 0:
- self.setValue(100)
- else:
- self.setValue(0)
-
-
-class OnionThread(QtCore.QThread):
- """
- A QThread for starting our Onion Service.
- By using QThread rather than threading.Thread, we are able
- to call quit() or terminate() on the startup if the user
- decided to cancel (in which case do not proceed with obtaining
- the Onion address and starting the web server).
- """
- def __init__(self, function, kwargs=None):
- super(OnionThread, self).__init__()
- common.log('OnionThread', '__init__')
- self.function = function
- if not kwargs:
- self.kwargs = {}
- else:
- self.kwargs = kwargs
-
- def run(self):
- common.log('OnionThread', 'run')
-
- self.function(**self.kwargs)
diff --git a/onionshare_gui/server_status.py b/onionshare_gui/server_status.py
index f3156fed..e34a3d16 100644
--- a/onionshare_gui/server_status.py
+++ b/onionshare_gui/server_status.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -18,45 +18,61 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import platform
-from .alert import Alert
+import textwrap
from PyQt5 import QtCore, QtWidgets, QtGui
-from onionshare import strings, common, settings
+from onionshare import strings
+
+from .widgets import Alert
class ServerStatus(QtWidgets.QWidget):
"""
The server status chunk of the GUI.
"""
server_started = QtCore.pyqtSignal()
+ server_started_finished = QtCore.pyqtSignal()
server_stopped = QtCore.pyqtSignal()
server_canceled = QtCore.pyqtSignal()
button_clicked = QtCore.pyqtSignal()
url_copied = QtCore.pyqtSignal()
hidservauth_copied = QtCore.pyqtSignal()
+ MODE_SHARE = 'share'
+ MODE_RECEIVE = 'receive'
+
STATUS_STOPPED = 0
STATUS_WORKING = 1
STATUS_STARTED = 2
- def __init__(self, qtapp, app, web, file_selection, settings):
+ def __init__(self, common, qtapp, app, file_selection=None, local_only=False):
super(ServerStatus, self).__init__()
+
+ self.common = common
+
self.status = self.STATUS_STOPPED
+ self.mode = None # Gets set in self.set_mode
self.qtapp = qtapp
self.app = app
- self.web = web
- self.file_selection = file_selection
- self.settings = settings
+ self.web = None
+ self.local_only = local_only
+
+ self.resizeEvent(None)
# Shutdown timeout layout
- self.shutdown_timeout_label = QtWidgets.QLabel(strings._('gui_settings_shutdown_timeout', True))
+ self.shutdown_timeout_label = QtWidgets.QLabel(strings._('gui_settings_shutdown_timeout'))
self.shutdown_timeout = QtWidgets.QDateTimeEdit()
- # Set proposed timeout to be 5 minutes into the future
self.shutdown_timeout.setDisplayFormat("hh:mm A MMM d, yy")
- self.shutdown_timeout.setDateTime(QtCore.QDateTime.currentDateTime().addSecs(300))
- # Onion services can take a little while to start, so reduce the risk of it expiring too soon by setting the minimum to 2 min from now
- self.shutdown_timeout.setMinimumDateTime(QtCore.QDateTime.currentDateTime().addSecs(120))
+ if self.local_only:
+ # For testing
+ self.shutdown_timeout.setDateTime(QtCore.QDateTime.currentDateTime().addSecs(15))
+ self.shutdown_timeout.setMinimumDateTime(QtCore.QDateTime.currentDateTime())
+ else:
+ # Set proposed timeout to be 5 minutes into the future
+ self.shutdown_timeout.setDateTime(QtCore.QDateTime.currentDateTime().addSecs(300))
+ # Onion services can take a little while to start, so reduce the risk of it expiring too soon by setting the minimum to 60s from now
+ self.shutdown_timeout.setMinimumDateTime(QtCore.QDateTime.currentDateTime().addSecs(60))
self.shutdown_timeout.setCurrentSection(QtWidgets.QDateTimeEdit.MinuteSection)
shutdown_timeout_layout = QtWidgets.QHBoxLayout()
shutdown_timeout_layout.addWidget(self.shutdown_timeout_label)
@@ -69,31 +85,29 @@ class ServerStatus(QtWidgets.QWidget):
self.shutdown_timeout_container.setLayout(shutdown_timeout_container_layout)
self.shutdown_timeout_container.hide()
-
# Server layout
self.server_button = QtWidgets.QPushButton()
self.server_button.clicked.connect(self.server_button_clicked)
# URL layout
- url_font = QtGui.QFont()
- self.url_description = QtWidgets.QLabel(strings._('gui_url_description', True))
+ url_font = QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont)
+ self.url_description = QtWidgets.QLabel()
self.url_description.setWordWrap(True)
self.url_description.setMinimumHeight(50)
self.url = QtWidgets.QLabel()
self.url.setFont(url_font)
self.url.setWordWrap(True)
- self.url.setMinimumHeight(60)
self.url.setMinimumSize(self.url.sizeHint())
- self.url.setStyleSheet('QLabel { background-color: #ffffff; color: #000000; padding: 10px; border: 1px solid #666666; }')
+ self.url.setStyleSheet(self.common.css['server_status_url'])
- url_buttons_style = 'QPushButton { color: #3f7fcf; }'
- self.copy_url_button = QtWidgets.QPushButton(strings._('gui_copy_url', True))
+ self.copy_url_button = QtWidgets.QPushButton(strings._('gui_copy_url'))
self.copy_url_button.setFlat(True)
- self.copy_url_button.setStyleSheet(url_buttons_style)
+ self.copy_url_button.setStyleSheet(self.common.css['server_status_url_buttons'])
+ self.copy_url_button.setMinimumHeight(65)
self.copy_url_button.clicked.connect(self.copy_url)
- self.copy_hidservauth_button = QtWidgets.QPushButton(strings._('gui_copy_hidservauth', True))
+ self.copy_hidservauth_button = QtWidgets.QPushButton(strings._('gui_copy_hidservauth'))
self.copy_hidservauth_button.setFlat(True)
- self.copy_hidservauth_button.setStyleSheet(url_buttons_style)
+ self.copy_hidservauth_button.setStyleSheet(self.common.css['server_status_url_buttons'])
self.copy_hidservauth_button.clicked.connect(self.copy_hidservauth)
url_buttons_layout = QtWidgets.QHBoxLayout()
url_buttons_layout.addWidget(self.copy_url_button)
@@ -112,14 +126,42 @@ class ServerStatus(QtWidgets.QWidget):
layout.addWidget(self.shutdown_timeout_container)
self.setLayout(layout)
+ def set_mode(self, share_mode, file_selection=None):
+ """
+ The server status is in share mode.
+ """
+ self.mode = share_mode
+
+ if self.mode == ServerStatus.MODE_SHARE:
+ self.file_selection = file_selection
+
self.update()
+ def resizeEvent(self, event):
+ """
+ When the widget is resized, try and adjust the display of a v3 onion URL.
+ """
+ try:
+ # Wrap the URL label
+ url_length=len(self.get_url())
+ if url_length > 60:
+ width = self.frameGeometry().width()
+ if width < 530:
+ wrapped_onion_url = textwrap.fill(self.get_url(), 46)
+ self.url.setText(wrapped_onion_url)
+ else:
+ self.url.setText(self.get_url())
+ except:
+ pass
+
+
def shutdown_timeout_reset(self):
"""
Reset the timeout in the UI after stopping a share
"""
self.shutdown_timeout.setDateTime(QtCore.QDateTime.currentDateTime().addSecs(300))
- self.shutdown_timeout.setMinimumDateTime(QtCore.QDateTime.currentDateTime().addSecs(120))
+ if not self.local_only:
+ self.shutdown_timeout.setMinimumDateTime(QtCore.QDateTime.currentDateTime().addSecs(60))
def update(self):
"""
@@ -129,31 +171,36 @@ class ServerStatus(QtWidgets.QWidget):
if self.status == self.STATUS_STARTED:
self.url_description.show()
- info_image = common.get_resource_path('images/info.png')
- self.url_description.setText(strings._('gui_url_description', True).format(info_image))
+ info_image = self.common.get_resource_path('images/info.png')
+
+ if self.mode == ServerStatus.MODE_SHARE:
+ self.url_description.setText(strings._('gui_share_url_description').format(info_image))
+ else:
+ self.url_description.setText(strings._('gui_receive_url_description').format(info_image))
+
# Show a Tool Tip explaining the lifecycle of this URL
- if self.settings.get('save_private_key'):
- if self.settings.get('close_after_first_download'):
- self.url_description.setToolTip(strings._('gui_url_label_onetime_and_persistent', True))
+ if self.common.settings.get('save_private_key'):
+ if self.mode == ServerStatus.MODE_SHARE and self.common.settings.get('close_after_first_download'):
+ self.url_description.setToolTip(strings._('gui_url_label_onetime_and_persistent'))
else:
- self.url_description.setToolTip(strings._('gui_url_label_persistent', True))
+ self.url_description.setToolTip(strings._('gui_url_label_persistent'))
else:
- if self.settings.get('close_after_first_download'):
- self.url_description.setToolTip(strings._('gui_url_label_onetime', True))
+ if self.mode == ServerStatus.MODE_SHARE and self.common.settings.get('close_after_first_download'):
+ self.url_description.setToolTip(strings._('gui_url_label_onetime'))
else:
- self.url_description.setToolTip(strings._('gui_url_label_stay_open', True))
+ self.url_description.setToolTip(strings._('gui_url_label_stay_open'))
- self.url.setText('http://{0:s}/{1:s}'.format(self.app.onion_host, self.web.slug))
+ self.url.setText(self.get_url())
self.url.show()
self.copy_url_button.show()
- if self.settings.get('save_private_key'):
- if not self.settings.get('slug'):
- self.settings.set('slug', self.web.slug)
- self.settings.save()
+ if self.common.settings.get('save_private_key'):
+ if not self.common.settings.get('slug'):
+ self.common.settings.set('slug', self.web.slug)
+ self.common.settings.save()
- if self.settings.get('shutdown_timeout'):
+ if self.common.settings.get('shutdown_timeout'):
self.shutdown_timeout_container.hide()
if self.app.stealth:
@@ -167,39 +214,46 @@ class ServerStatus(QtWidgets.QWidget):
self.copy_hidservauth_button.hide()
# Button
- button_stopped_style = 'QPushButton { background-color: #5fa416; color: #ffffff; padding: 10px; border: 0; border-radius: 5px; }'
- button_working_style = 'QPushButton { background-color: #4c8211; color: #ffffff; padding: 10px; border: 0; border-radius: 5px; font-style: italic; }'
- button_started_style = 'QPushButton { background-color: #d0011b; color: #ffffff; padding: 10px; border: 0; border-radius: 5px; }'
- if self.file_selection.get_num_files() == 0:
+ if self.mode == ServerStatus.MODE_SHARE and self.file_selection.get_num_files() == 0:
self.server_button.hide()
else:
self.server_button.show()
if self.status == self.STATUS_STOPPED:
- self.server_button.setStyleSheet(button_stopped_style)
+ self.server_button.setStyleSheet(self.common.css['server_status_button_stopped'])
self.server_button.setEnabled(True)
- self.server_button.setText(strings._('gui_start_server', True))
+ if self.mode == ServerStatus.MODE_SHARE:
+ self.server_button.setText(strings._('gui_share_start_server'))
+ else:
+ self.server_button.setText(strings._('gui_receive_start_server'))
self.server_button.setToolTip('')
- if self.settings.get('shutdown_timeout'):
+ if self.common.settings.get('shutdown_timeout'):
self.shutdown_timeout_container.show()
elif self.status == self.STATUS_STARTED:
- self.server_button.setStyleSheet(button_started_style)
+ self.server_button.setStyleSheet(self.common.css['server_status_button_started'])
self.server_button.setEnabled(True)
- self.server_button.setText(strings._('gui_stop_server', True))
- if self.settings.get('shutdown_timeout'):
+ if self.mode == ServerStatus.MODE_SHARE:
+ self.server_button.setText(strings._('gui_share_stop_server'))
+ else:
+ self.server_button.setText(strings._('gui_receive_stop_server'))
+ if self.common.settings.get('shutdown_timeout'):
self.shutdown_timeout_container.hide()
- self.server_button.setToolTip(strings._('gui_stop_server_shutdown_timeout_tooltip', True).format(self.timeout))
+ if self.mode == ServerStatus.MODE_SHARE:
+ self.server_button.setToolTip(strings._('gui_share_stop_server_shutdown_timeout_tooltip').format(self.timeout))
+ else:
+ self.server_button.setToolTip(strings._('gui_receive_stop_server_shutdown_timeout_tooltip').format(self.timeout))
+
elif self.status == self.STATUS_WORKING:
- self.server_button.setStyleSheet(button_working_style)
+ self.server_button.setStyleSheet(self.common.css['server_status_button_working'])
self.server_button.setEnabled(True)
self.server_button.setText(strings._('gui_please_wait'))
- if self.settings.get('shutdown_timeout'):
+ if self.common.settings.get('shutdown_timeout'):
self.shutdown_timeout_container.hide()
else:
- self.server_button.setStyleSheet(button_working_style)
+ self.server_button.setStyleSheet(self.common.css['server_status_button_working'])
self.server_button.setEnabled(False)
self.server_button.setText(strings._('gui_please_wait'))
- if self.settings.get('shutdown_timeout'):
+ if self.common.settings.get('shutdown_timeout'):
self.shutdown_timeout_container.hide()
def server_button_clicked(self):
@@ -207,12 +261,15 @@ class ServerStatus(QtWidgets.QWidget):
Toggle starting or stopping the server.
"""
if self.status == self.STATUS_STOPPED:
- if self.settings.get('shutdown_timeout'):
- # Get the timeout chosen, stripped of its seconds. This prevents confusion if the share stops at (say) 37 seconds past the minute chosen
- self.timeout = self.shutdown_timeout.dateTime().toPyDateTime().replace(second=0, microsecond=0)
+ if self.common.settings.get('shutdown_timeout'):
+ if self.local_only:
+ self.timeout = self.shutdown_timeout.dateTime().toPyDateTime()
+ else:
+ # Get the timeout chosen, stripped of its seconds. This prevents confusion if the share stops at (say) 37 seconds past the minute chosen
+ self.timeout = self.shutdown_timeout.dateTime().toPyDateTime().replace(second=0, microsecond=0)
# If the timeout has actually passed already before the user hit Start, refuse to start the server.
if QtCore.QDateTime.currentDateTime().toPyDateTime() > self.timeout:
- Alert(strings._('gui_server_timeout_expired', QtWidgets.QMessageBox.Warning))
+ Alert(self.common, strings._('gui_server_timeout_expired'), QtWidgets.QMessageBox.Warning)
else:
self.start_server()
else:
@@ -238,6 +295,7 @@ class ServerStatus(QtWidgets.QWidget):
self.status = self.STATUS_STARTED
self.copy_url()
self.update()
+ self.server_started_finished.emit()
def stop_server(self):
"""
@@ -252,7 +310,7 @@ class ServerStatus(QtWidgets.QWidget):
"""
Cancel the server.
"""
- common.log('ServerStatus', 'cancel_server', 'Canceling the server mid-startup')
+ self.common.log('ServerStatus', 'cancel_server', 'Canceling the server mid-startup')
self.status = self.STATUS_WORKING
self.shutdown_timeout_reset()
self.update()
@@ -269,10 +327,8 @@ class ServerStatus(QtWidgets.QWidget):
"""
Copy the onionshare URL to the clipboard.
"""
- url = 'http://{0:s}/{1:s}'.format(self.app.onion_host, self.web.slug)
-
clipboard = self.qtapp.clipboard()
- clipboard.setText(url)
+ clipboard.setText(self.get_url())
self.url_copied.emit()
@@ -284,3 +340,13 @@ class ServerStatus(QtWidgets.QWidget):
clipboard.setText(self.app.auth_string)
self.hidservauth_copied.emit()
+
+ def get_url(self):
+ """
+ Returns the OnionShare URL.
+ """
+ if self.common.settings.get('public_mode'):
+ url = 'http://{0:s}'.format(self.app.onion_host)
+ else:
+ url = 'http://{0:s}/{1:s}'.format(self.app.onion_host, self.web.slug)
+ return url
diff --git a/onionshare_gui/settings_dialog.py b/onionshare_gui/settings_dialog.py
index c2dca97c..958d49fd 100644
--- a/onionshare_gui/settings_dialog.py
+++ b/onionshare_gui/settings_dialog.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -24,7 +24,7 @@ from onionshare import strings, common
from onionshare.settings import Settings
from onionshare.onion import *
-from .alert import Alert
+from .widgets import Alert
from .update_checker import *
from .tor_connection_dialog import TorConnectionDialog
@@ -34,93 +34,176 @@ class SettingsDialog(QtWidgets.QDialog):
"""
settings_saved = QtCore.pyqtSignal()
- def __init__(self, onion, qtapp, config=False):
+ def __init__(self, common, onion, qtapp, config=False, local_only=False):
super(SettingsDialog, self).__init__()
- common.log('SettingsDialog', '__init__')
+
+ self.common = common
+
+ self.common.log('SettingsDialog', '__init__')
self.onion = onion
self.qtapp = qtapp
self.config = config
+ self.local_only = local_only
self.setModal(True)
- self.setWindowTitle(strings._('gui_settings_window_title', True))
- self.setWindowIcon(QtGui.QIcon(common.get_resource_path('images/logo.png')))
+ self.setWindowTitle(strings._('gui_settings_window_title'))
+ self.setWindowIcon(QtGui.QIcon(self.common.get_resource_path('images/logo.png')))
self.system = platform.system()
- # Sharing options
-
- # Close after first download
- self.close_after_first_download_checkbox = QtWidgets.QCheckBox()
- self.close_after_first_download_checkbox.setCheckState(QtCore.Qt.Checked)
- self.close_after_first_download_checkbox.setText(strings._("gui_settings_close_after_first_download_option", True))
-
- # Whether or not to show systray notifications
- self.systray_notifications_checkbox = QtWidgets.QCheckBox()
- self.systray_notifications_checkbox.setCheckState(QtCore.Qt.Checked)
- self.systray_notifications_checkbox.setText(strings._("gui_settings_systray_notifications", True))
-
- # Whether or not to use a shutdown timer
+ # General options
+
+ # Use a slug or not ('public mode')
+ self.public_mode_checkbox = QtWidgets.QCheckBox()
+ self.public_mode_checkbox.setCheckState(QtCore.Qt.Unchecked)
+ self.public_mode_checkbox.setText(strings._("gui_settings_public_mode_checkbox"))
+ public_mode_label = QtWidgets.QLabel(strings._("gui_settings_whats_this").format("https://github.com/micahflee/onionshare/wiki/Public-Mode"))
+ public_mode_label.setStyleSheet(self.common.css['settings_whats_this'])
+ public_mode_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
+ public_mode_label.setOpenExternalLinks(True)
+ public_mode_label.setMinimumSize(public_mode_label.sizeHint())
+ public_mode_layout = QtWidgets.QHBoxLayout()
+ public_mode_layout.addWidget(self.public_mode_checkbox)
+ public_mode_layout.addWidget(public_mode_label)
+ public_mode_layout.addStretch()
+ public_mode_layout.setContentsMargins(0,0,0,0)
+ self.public_mode_widget = QtWidgets.QWidget()
+ self.public_mode_widget.setLayout(public_mode_layout)
+
+ # Whether or not to use a shutdown ('auto-stop') timer
self.shutdown_timeout_checkbox = QtWidgets.QCheckBox()
self.shutdown_timeout_checkbox.setCheckState(QtCore.Qt.Checked)
- self.shutdown_timeout_checkbox.setText(strings._("gui_settings_shutdown_timeout_checkbox", True))
-
- # Whether or not to save the Onion private key for reuse
+ self.shutdown_timeout_checkbox.setText(strings._("gui_settings_shutdown_timeout_checkbox"))
+ shutdown_timeout_label = QtWidgets.QLabel(strings._("gui_settings_whats_this").format("https://github.com/micahflee/onionshare/wiki/Using-the-Auto-Stop-Timer"))
+ shutdown_timeout_label.setStyleSheet(self.common.css['settings_whats_this'])
+ shutdown_timeout_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
+ shutdown_timeout_label.setOpenExternalLinks(True)
+ shutdown_timeout_label.setMinimumSize(public_mode_label.sizeHint())
+ shutdown_timeout_layout = QtWidgets.QHBoxLayout()
+ shutdown_timeout_layout.addWidget(self.shutdown_timeout_checkbox)
+ shutdown_timeout_layout.addWidget(shutdown_timeout_label)
+ shutdown_timeout_layout.addStretch()
+ shutdown_timeout_layout.setContentsMargins(0,0,0,0)
+ self.shutdown_timeout_widget = QtWidgets.QWidget()
+ self.shutdown_timeout_widget.setLayout(shutdown_timeout_layout)
+
+ # Whether or not to use legacy v2 onions
+ self.use_legacy_v2_onions_checkbox = QtWidgets.QCheckBox()
+ self.use_legacy_v2_onions_checkbox.setCheckState(QtCore.Qt.Unchecked)
+ self.use_legacy_v2_onions_checkbox.setText(strings._("gui_use_legacy_v2_onions_checkbox"))
+ self.use_legacy_v2_onions_checkbox.clicked.connect(self.use_legacy_v2_onions_checkbox_clicked)
+ use_legacy_v2_onions_label = QtWidgets.QLabel(strings._("gui_settings_whats_this").format("https://github.com/micahflee/onionshare/wiki/Legacy-Addresses"))
+ use_legacy_v2_onions_label.setStyleSheet(self.common.css['settings_whats_this'])
+ use_legacy_v2_onions_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
+ use_legacy_v2_onions_label.setOpenExternalLinks(True)
+ use_legacy_v2_onions_layout = QtWidgets.QHBoxLayout()
+ use_legacy_v2_onions_layout.addWidget(self.use_legacy_v2_onions_checkbox)
+ use_legacy_v2_onions_layout.addWidget(use_legacy_v2_onions_label)
+ use_legacy_v2_onions_layout.addStretch()
+ use_legacy_v2_onions_layout.setContentsMargins(0,0,0,0)
+ self.use_legacy_v2_onions_widget = QtWidgets.QWidget()
+ self.use_legacy_v2_onions_widget.setLayout(use_legacy_v2_onions_layout)
+
+ # Whether or not to save the Onion private key for reuse (persistent URL mode)
self.save_private_key_checkbox = QtWidgets.QCheckBox()
self.save_private_key_checkbox.setCheckState(QtCore.Qt.Unchecked)
- self.save_private_key_checkbox.setText(strings._("gui_save_private_key_checkbox", True))
-
- # Sharing options layout
- sharing_group_layout = QtWidgets.QVBoxLayout()
- sharing_group_layout.addWidget(self.close_after_first_download_checkbox)
- sharing_group_layout.addWidget(self.systray_notifications_checkbox)
- sharing_group_layout.addWidget(self.shutdown_timeout_checkbox)
- sharing_group_layout.addWidget(self.save_private_key_checkbox)
- sharing_group = QtWidgets.QGroupBox(strings._("gui_settings_sharing_label", True))
- sharing_group.setLayout(sharing_group_layout)
-
- # Stealth options
+ self.save_private_key_checkbox.setText(strings._("gui_save_private_key_checkbox"))
+ self.save_private_key_checkbox.clicked.connect(self.save_private_key_checkbox_clicked)
+ save_private_key_label = QtWidgets.QLabel(strings._("gui_settings_whats_this").format("https://github.com/micahflee/onionshare/wiki/Using-a-Persistent-URL"))
+ save_private_key_label.setStyleSheet(self.common.css['settings_whats_this'])
+ save_private_key_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
+ save_private_key_label.setOpenExternalLinks(True)
+ save_private_key_layout = QtWidgets.QHBoxLayout()
+ save_private_key_layout.addWidget(self.save_private_key_checkbox)
+ save_private_key_layout.addWidget(save_private_key_label)
+ save_private_key_layout.addStretch()
+ save_private_key_layout.setContentsMargins(0,0,0,0)
+ self.save_private_key_widget = QtWidgets.QWidget()
+ self.save_private_key_widget.setLayout(save_private_key_layout)
# Stealth
- stealth_details = QtWidgets.QLabel(strings._("gui_settings_stealth_option_details", True))
- stealth_details.setWordWrap(True)
- stealth_details.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
- stealth_details.setOpenExternalLinks(True)
- stealth_details.setMinimumSize(stealth_details.sizeHint())
self.stealth_checkbox = QtWidgets.QCheckBox()
self.stealth_checkbox.setCheckState(QtCore.Qt.Unchecked)
- self.stealth_checkbox.setText(strings._("gui_settings_stealth_option", True))
-
- hidservauth_details = QtWidgets.QLabel(strings._('gui_settings_stealth_hidservauth_string', True))
+ self.stealth_checkbox.setText(strings._("gui_settings_stealth_option"))
+ self.stealth_checkbox.clicked.connect(self.stealth_checkbox_clicked_connect)
+ use_stealth_label = QtWidgets.QLabel(strings._("gui_settings_whats_this").format("https://github.com/micahflee/onionshare/wiki/Stealth-Onion-Services"))
+ use_stealth_label.setStyleSheet(self.common.css['settings_whats_this'])
+ use_stealth_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
+ use_stealth_label.setOpenExternalLinks(True)
+ use_stealth_label.setMinimumSize(use_stealth_label.sizeHint())
+ use_stealth_layout = QtWidgets.QHBoxLayout()
+ use_stealth_layout.addWidget(self.stealth_checkbox)
+ use_stealth_layout.addWidget(use_stealth_label)
+ use_stealth_layout.addStretch()
+ use_stealth_layout.setContentsMargins(0,0,0,0)
+ self.use_stealth_widget = QtWidgets.QWidget()
+ self.use_stealth_widget.setLayout(use_stealth_layout)
+
+ hidservauth_details = QtWidgets.QLabel(strings._('gui_settings_stealth_hidservauth_string'))
hidservauth_details.setWordWrap(True)
hidservauth_details.setMinimumSize(hidservauth_details.sizeHint())
hidservauth_details.hide()
- self.hidservauth_copy_button = QtWidgets.QPushButton(strings._('gui_copy_hidservauth', True))
+ self.hidservauth_copy_button = QtWidgets.QPushButton(strings._('gui_copy_hidservauth'))
self.hidservauth_copy_button.clicked.connect(self.hidservauth_copy_button_clicked)
self.hidservauth_copy_button.hide()
- # Stealth options layout
- stealth_group_layout = QtWidgets.QVBoxLayout()
- stealth_group_layout.addWidget(stealth_details)
- stealth_group_layout.addWidget(self.stealth_checkbox)
- stealth_group_layout.addWidget(hidservauth_details)
- stealth_group_layout.addWidget(self.hidservauth_copy_button)
- stealth_group = QtWidgets.QGroupBox(strings._("gui_settings_stealth_label", True))
- stealth_group.setLayout(stealth_group_layout)
+ # General options layout
+ general_group_layout = QtWidgets.QVBoxLayout()
+ general_group_layout.addWidget(self.public_mode_widget)
+ general_group_layout.addWidget(self.shutdown_timeout_widget)
+ general_group_layout.addWidget(self.use_legacy_v2_onions_widget)
+ general_group_layout.addWidget(self.save_private_key_widget)
+ general_group_layout.addWidget(self.use_stealth_widget)
+ general_group_layout.addWidget(hidservauth_details)
+ general_group_layout.addWidget(self.hidservauth_copy_button)
+
+ general_group = QtWidgets.QGroupBox(strings._("gui_settings_general_label"))
+ general_group.setLayout(general_group_layout)
+
+ # Sharing options
+
+ # Close after first download
+ self.close_after_first_download_checkbox = QtWidgets.QCheckBox()
+ self.close_after_first_download_checkbox.setCheckState(QtCore.Qt.Checked)
+ self.close_after_first_download_checkbox.setText(strings._("gui_settings_close_after_first_download_option"))
+
+ # Sharing options layout
+ sharing_group_layout = QtWidgets.QVBoxLayout()
+ sharing_group_layout.addWidget(self.close_after_first_download_checkbox)
+ sharing_group = QtWidgets.QGroupBox(strings._("gui_settings_sharing_label"))
+ sharing_group.setLayout(sharing_group_layout)
+
+ # Downloads dir
+ downloads_label = QtWidgets.QLabel(strings._('gui_settings_downloads_label'));
+ self.downloads_dir_lineedit = QtWidgets.QLineEdit()
+ self.downloads_dir_lineedit.setReadOnly(True)
+ downloads_button = QtWidgets.QPushButton(strings._('gui_settings_downloads_button'))
+ downloads_button.clicked.connect(self.downloads_button_clicked)
+ downloads_layout = QtWidgets.QHBoxLayout()
+ downloads_layout.addWidget(downloads_label)
+ downloads_layout.addWidget(self.downloads_dir_lineedit)
+ downloads_layout.addWidget(downloads_button)
+
+ # Receiving options layout
+ receiving_group_layout = QtWidgets.QVBoxLayout()
+ receiving_group_layout.addLayout(downloads_layout)
+ receiving_group = QtWidgets.QGroupBox(strings._("gui_settings_receiving_label"))
+ receiving_group.setLayout(receiving_group_layout)
# Automatic updates options
# Autoupdate
self.autoupdate_checkbox = QtWidgets.QCheckBox()
self.autoupdate_checkbox.setCheckState(QtCore.Qt.Unchecked)
- self.autoupdate_checkbox.setText(strings._("gui_settings_autoupdate_option", True))
+ self.autoupdate_checkbox.setText(strings._("gui_settings_autoupdate_option"))
# Last update time
self.autoupdate_timestamp = QtWidgets.QLabel()
# Check for updates button
- self.check_for_updates_button = QtWidgets.QPushButton(strings._('gui_settings_autoupdate_check_button', True))
+ self.check_for_updates_button = QtWidgets.QPushButton(strings._('gui_settings_autoupdate_check_button'))
self.check_for_updates_button.clicked.connect(self.check_for_updates)
# We can't check for updates if not connected to Tor
if not self.onion.connected_to_tor:
@@ -131,17 +214,32 @@ class SettingsDialog(QtWidgets.QDialog):
autoupdate_group_layout.addWidget(self.autoupdate_checkbox)
autoupdate_group_layout.addWidget(self.autoupdate_timestamp)
autoupdate_group_layout.addWidget(self.check_for_updates_button)
- autoupdate_group = QtWidgets.QGroupBox(strings._("gui_settings_autoupdate_label", True))
+ autoupdate_group = QtWidgets.QGroupBox(strings._("gui_settings_autoupdate_label"))
autoupdate_group.setLayout(autoupdate_group_layout)
# Autoupdate is only available for Windows and Mac (Linux updates using package manager)
if self.system != 'Windows' and self.system != 'Darwin':
autoupdate_group.hide()
+ # Language settings
+ language_label = QtWidgets.QLabel(strings._("gui_settings_language_label"))
+ self.language_combobox = QtWidgets.QComboBox()
+ # Populate the dropdown with all of OnionShare's available languages
+ language_names_to_locales = {v: k for k, v in self.common.settings.available_locales.items()}
+ language_names = list(language_names_to_locales)
+ language_names.sort()
+ for language_name in language_names:
+ locale = language_names_to_locales[language_name]
+ self.language_combobox.addItem(language_name, QtCore.QVariant(locale))
+ language_layout = QtWidgets.QHBoxLayout()
+ language_layout.addWidget(language_label)
+ language_layout.addWidget(self.language_combobox)
+ language_layout.addStretch()
+
# Connection type: either automatic, control port, or socket file
# Bundled Tor
- self.connection_type_bundled_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_bundled_option', True))
+ self.connection_type_bundled_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_bundled_option'))
self.connection_type_bundled_radio.toggled.connect(self.connection_type_bundled_toggled)
# Bundled Tor doesn't work on dev mode in Windows or Mac
@@ -151,49 +249,38 @@ class SettingsDialog(QtWidgets.QDialog):
# Bridge options for bundled tor
# No bridges option radio
- self.tor_bridges_no_bridges_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_no_bridges_radio_option', True))
+ self.tor_bridges_no_bridges_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_no_bridges_radio_option'))
self.tor_bridges_no_bridges_radio.toggled.connect(self.tor_bridges_no_bridges_radio_toggled)
# obfs4 option radio
# if the obfs4proxy binary is missing, we can't use obfs4 transports
- (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = common.get_tor_paths()
+ (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = self.common.get_tor_paths()
if not os.path.isfile(self.obfs4proxy_file_path):
- self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_obfs4_radio_option_no_obfs4proxy', True))
+ self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_obfs4_radio_option_no_obfs4proxy'))
self.tor_bridges_use_obfs4_radio.setEnabled(False)
else:
- self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_obfs4_radio_option', True))
+ self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_obfs4_radio_option'))
self.tor_bridges_use_obfs4_radio.toggled.connect(self.tor_bridges_use_obfs4_radio_toggled)
- # meek_lite-amazon option radio
- # if the obfs4proxy binary is missing, we can't use meek_lite-amazon transports
- (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = common.get_tor_paths()
- if not os.path.isfile(self.obfs4proxy_file_path):
- self.tor_bridges_use_meek_lite_amazon_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_meek_lite_amazon_radio_option_no_obfs4proxy', True))
- self.tor_bridges_use_meek_lite_amazon_radio.setEnabled(False)
- else:
- self.tor_bridges_use_meek_lite_amazon_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_meek_lite_amazon_radio_option', True))
- self.tor_bridges_use_meek_lite_amazon_radio.toggled.connect(self.tor_bridges_use_meek_lite_amazon_radio_toggled)
-
# meek_lite-azure option radio
# if the obfs4proxy binary is missing, we can't use meek_lite-azure transports
- (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = common.get_tor_paths()
+ (self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path) = self.common.get_tor_paths()
if not os.path.isfile(self.obfs4proxy_file_path):
- self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_meek_lite_azure_radio_option_no_obfs4proxy', True))
+ self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_meek_lite_azure_radio_option_no_obfs4proxy'))
self.tor_bridges_use_meek_lite_azure_radio.setEnabled(False)
else:
- self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_meek_lite_azure_radio_option', True))
+ self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_meek_lite_azure_radio_option'))
self.tor_bridges_use_meek_lite_azure_radio.toggled.connect(self.tor_bridges_use_meek_lite_azure_radio_toggled)
# meek_lite currently not supported on the version of obfs4proxy bundled with TorBrowser
if self.system == 'Windows' or self.system == 'Darwin':
- self.tor_bridges_use_meek_lite_amazon_radio.hide()
self.tor_bridges_use_meek_lite_azure_radio.hide()
# Custom bridges radio and textbox
- self.tor_bridges_use_custom_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_custom_radio_option', True))
+ self.tor_bridges_use_custom_radio = QtWidgets.QRadioButton(strings._('gui_settings_tor_bridges_custom_radio_option'))
self.tor_bridges_use_custom_radio.toggled.connect(self.tor_bridges_use_custom_radio_toggled)
- self.tor_bridges_use_custom_label = QtWidgets.QLabel(strings._('gui_settings_tor_bridges_custom_label', True))
+ self.tor_bridges_use_custom_label = QtWidgets.QLabel(strings._('gui_settings_tor_bridges_custom_label'))
self.tor_bridges_use_custom_label.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)
self.tor_bridges_use_custom_label.setOpenExternalLinks(True)
self.tor_bridges_use_custom_textbox = QtWidgets.QPlainTextEdit()
@@ -212,7 +299,6 @@ class SettingsDialog(QtWidgets.QDialog):
bridges_layout = QtWidgets.QVBoxLayout()
bridges_layout.addWidget(self.tor_bridges_no_bridges_radio)
bridges_layout.addWidget(self.tor_bridges_use_obfs4_radio)
- bridges_layout.addWidget(self.tor_bridges_use_meek_lite_amazon_radio)
bridges_layout.addWidget(self.tor_bridges_use_meek_lite_azure_radio)
bridges_layout.addWidget(self.tor_bridges_use_custom_radio)
bridges_layout.addWidget(self.tor_bridges_use_custom_textbox_options)
@@ -221,14 +307,14 @@ class SettingsDialog(QtWidgets.QDialog):
self.bridges.setLayout(bridges_layout)
# Automatic
- self.connection_type_automatic_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_automatic_option', True))
+ self.connection_type_automatic_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_automatic_option'))
self.connection_type_automatic_radio.toggled.connect(self.connection_type_automatic_toggled)
# Control port
- self.connection_type_control_port_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_control_port_option', True))
+ self.connection_type_control_port_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_control_port_option'))
self.connection_type_control_port_radio.toggled.connect(self.connection_type_control_port_toggled)
- connection_type_control_port_extras_label = QtWidgets.QLabel(strings._('gui_settings_control_port_label', True))
+ connection_type_control_port_extras_label = QtWidgets.QLabel(strings._('gui_settings_control_port_label'))
self.connection_type_control_port_extras_address = QtWidgets.QLineEdit()
self.connection_type_control_port_extras_port = QtWidgets.QLineEdit()
connection_type_control_port_extras_layout = QtWidgets.QHBoxLayout()
@@ -241,10 +327,10 @@ class SettingsDialog(QtWidgets.QDialog):
self.connection_type_control_port_extras.hide()
# Socket file
- self.connection_type_socket_file_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_socket_file_option', True))
+ self.connection_type_socket_file_radio = QtWidgets.QRadioButton(strings._('gui_settings_connection_type_socket_file_option'))
self.connection_type_socket_file_radio.toggled.connect(self.connection_type_socket_file_toggled)
- connection_type_socket_file_extras_label = QtWidgets.QLabel(strings._('gui_settings_socket_file_label', True))
+ connection_type_socket_file_extras_label = QtWidgets.QLabel(strings._('gui_settings_socket_file_label'))
self.connection_type_socket_file_extras_path = QtWidgets.QLineEdit()
connection_type_socket_file_extras_layout = QtWidgets.QHBoxLayout()
connection_type_socket_file_extras_layout.addWidget(connection_type_socket_file_extras_label)
@@ -255,7 +341,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.connection_type_socket_file_extras.hide()
# Tor SOCKS address and port
- gui_settings_socks_label = QtWidgets.QLabel(strings._('gui_settings_socks_label', True))
+ gui_settings_socks_label = QtWidgets.QLabel(strings._('gui_settings_socks_label'))
self.connection_type_socks_address = QtWidgets.QLineEdit()
self.connection_type_socks_port = QtWidgets.QLineEdit()
connection_type_socks_layout = QtWidgets.QHBoxLayout()
@@ -270,14 +356,14 @@ class SettingsDialog(QtWidgets.QDialog):
# Authentication options
# No authentication
- self.authenticate_no_auth_radio = QtWidgets.QRadioButton(strings._('gui_settings_authenticate_no_auth_option', True))
+ self.authenticate_no_auth_radio = QtWidgets.QRadioButton(strings._('gui_settings_authenticate_no_auth_option'))
self.authenticate_no_auth_radio.toggled.connect(self.authenticate_no_auth_toggled)
# Password
- self.authenticate_password_radio = QtWidgets.QRadioButton(strings._('gui_settings_authenticate_password_option', True))
+ self.authenticate_password_radio = QtWidgets.QRadioButton(strings._('gui_settings_authenticate_password_option'))
self.authenticate_password_radio.toggled.connect(self.authenticate_password_toggled)
- authenticate_password_extras_label = QtWidgets.QLabel(strings._('gui_settings_password_label', True))
+ authenticate_password_extras_label = QtWidgets.QLabel(strings._('gui_settings_password_label'))
self.authenticate_password_extras_password = QtWidgets.QLineEdit('')
authenticate_password_extras_layout = QtWidgets.QHBoxLayout()
authenticate_password_extras_layout.addWidget(authenticate_password_extras_label)
@@ -292,47 +378,49 @@ class SettingsDialog(QtWidgets.QDialog):
authenticate_group_layout.addWidget(self.authenticate_no_auth_radio)
authenticate_group_layout.addWidget(self.authenticate_password_radio)
authenticate_group_layout.addWidget(self.authenticate_password_extras)
- self.authenticate_group = QtWidgets.QGroupBox(strings._("gui_settings_authenticate_label", True))
+ self.authenticate_group = QtWidgets.QGroupBox(strings._("gui_settings_authenticate_label"))
self.authenticate_group.setLayout(authenticate_group_layout)
- # Test tor settings button
- self.connection_type_test_button = QtWidgets.QPushButton(strings._('gui_settings_connection_type_test_button', True))
- self.connection_type_test_button.clicked.connect(self.test_tor_clicked)
-
# Put the radios into their own group so they are exclusive
connection_type_radio_group_layout = QtWidgets.QVBoxLayout()
connection_type_radio_group_layout.addWidget(self.connection_type_bundled_radio)
connection_type_radio_group_layout.addWidget(self.connection_type_automatic_radio)
connection_type_radio_group_layout.addWidget(self.connection_type_control_port_radio)
connection_type_radio_group_layout.addWidget(self.connection_type_socket_file_radio)
- connection_type_radio_group = QtWidgets.QGroupBox(strings._("gui_settings_connection_type_label", True))
+ connection_type_radio_group = QtWidgets.QGroupBox(strings._("gui_settings_connection_type_label"))
connection_type_radio_group.setLayout(connection_type_radio_group_layout)
- # Connection type layout
- connection_type_group_layout = QtWidgets.QVBoxLayout()
- connection_type_group_layout.addWidget(self.connection_type_control_port_extras)
- connection_type_group_layout.addWidget(self.connection_type_socket_file_extras)
- connection_type_group_layout.addWidget(self.connection_type_socks)
- connection_type_group_layout.addWidget(self.authenticate_group)
- connection_type_group_layout.addWidget(self.connection_type_test_button)
- connection_type_group = QtWidgets.QGroupBox()
- connection_type_group.setLayout(connection_type_group_layout)
-
# The Bridges options are not exclusive (enabling Bridges offers obfs4 or custom bridges)
connection_type_bridges_radio_group_layout = QtWidgets.QVBoxLayout()
connection_type_bridges_radio_group_layout.addWidget(self.bridges)
- self.connection_type_bridges_radio_group = QtWidgets.QGroupBox(strings._("gui_settings_tor_bridges", True))
+ self.connection_type_bridges_radio_group = QtWidgets.QGroupBox(strings._("gui_settings_tor_bridges"))
self.connection_type_bridges_radio_group.setLayout(connection_type_bridges_radio_group_layout)
self.connection_type_bridges_radio_group.hide()
+ # Test tor settings button
+ self.connection_type_test_button = QtWidgets.QPushButton(strings._('gui_settings_connection_type_test_button'))
+ self.connection_type_test_button.clicked.connect(self.test_tor_clicked)
+ connection_type_test_button_layout = QtWidgets.QHBoxLayout()
+ connection_type_test_button_layout.addWidget(self.connection_type_test_button)
+ connection_type_test_button_layout.addStretch()
+
+ # Connection type layout
+ connection_type_layout = QtWidgets.QVBoxLayout()
+ connection_type_layout.addWidget(self.connection_type_control_port_extras)
+ connection_type_layout.addWidget(self.connection_type_socket_file_extras)
+ connection_type_layout.addWidget(self.connection_type_socks)
+ connection_type_layout.addWidget(self.authenticate_group)
+ connection_type_layout.addWidget(self.connection_type_bridges_radio_group)
+ connection_type_layout.addLayout(connection_type_test_button_layout)
+
# Buttons
- self.save_button = QtWidgets.QPushButton(strings._('gui_settings_button_save', True))
+ self.save_button = QtWidgets.QPushButton(strings._('gui_settings_button_save'))
self.save_button.clicked.connect(self.save_clicked)
- self.cancel_button = QtWidgets.QPushButton(strings._('gui_settings_button_cancel', True))
+ self.cancel_button = QtWidgets.QPushButton(strings._('gui_settings_button_cancel'))
self.cancel_button.clicked.connect(self.cancel_clicked)
- version_label = QtWidgets.QLabel('OnionShare {0:s}'.format(common.get_version()))
- version_label.setStyleSheet('color: #666666')
- self.help_button = QtWidgets.QPushButton(strings._('gui_settings_button_help', True))
+ version_label = QtWidgets.QLabel('OnionShare {0:s}'.format(self.common.version))
+ version_label.setStyleSheet(self.common.css['settings_version'])
+ self.help_button = QtWidgets.QPushButton(strings._('gui_settings_button_help'))
self.help_button.clicked.connect(self.help_clicked)
buttons_layout = QtWidgets.QHBoxLayout()
buttons_layout.addWidget(version_label)
@@ -343,20 +431,21 @@ class SettingsDialog(QtWidgets.QDialog):
# Tor network connection status
self.tor_status = QtWidgets.QLabel()
- self.tor_status.setStyleSheet('background-color: #ffffff; color: #000000; padding: 10px')
+ self.tor_status.setStyleSheet(self.common.css['settings_tor_status'])
self.tor_status.hide()
# Layout
left_col_layout = QtWidgets.QVBoxLayout()
+ left_col_layout.addWidget(general_group)
left_col_layout.addWidget(sharing_group)
- left_col_layout.addWidget(stealth_group)
+ left_col_layout.addWidget(receiving_group)
left_col_layout.addWidget(autoupdate_group)
+ left_col_layout.addLayout(language_layout)
left_col_layout.addStretch()
right_col_layout = QtWidgets.QVBoxLayout()
right_col_layout.addWidget(connection_type_radio_group)
- right_col_layout.addWidget(connection_type_group)
- right_col_layout.addWidget(self.connection_type_bridges_radio_group)
+ right_col_layout.addLayout(connection_type_layout)
right_col_layout.addWidget(self.tor_status)
right_col_layout.addStretch()
@@ -372,7 +461,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.cancel_button.setFocus()
# Load settings, and fill them in
- self.old_settings = Settings(self.config)
+ self.old_settings = Settings(self.common, self.config)
self.old_settings.load()
close_after_first_download = self.old_settings.get('close_after_first_download')
@@ -381,32 +470,54 @@ class SettingsDialog(QtWidgets.QDialog):
else:
self.close_after_first_download_checkbox.setCheckState(QtCore.Qt.Unchecked)
- systray_notifications = self.old_settings.get('systray_notifications')
- if systray_notifications:
- self.systray_notifications_checkbox.setCheckState(QtCore.Qt.Checked)
- else:
- self.systray_notifications_checkbox.setCheckState(QtCore.Qt.Unchecked)
-
shutdown_timeout = self.old_settings.get('shutdown_timeout')
if shutdown_timeout:
self.shutdown_timeout_checkbox.setCheckState(QtCore.Qt.Checked)
else:
self.shutdown_timeout_checkbox.setCheckState(QtCore.Qt.Unchecked)
+ use_legacy_v2_onions = self.old_settings.get('use_legacy_v2_onions')
+
+ if use_legacy_v2_onions:
+ self.save_private_key_widget.show()
+ self.use_stealth_widget.show()
+ else:
+ self.save_private_key_widget.hide()
+ self.use_stealth_widget.hide()
+
save_private_key = self.old_settings.get('save_private_key')
if save_private_key:
self.save_private_key_checkbox.setCheckState(QtCore.Qt.Checked)
+ # Legacy v2 mode is forced on if persistence is enabled
+ self.use_legacy_v2_onions_checkbox.setEnabled(False)
else:
self.save_private_key_checkbox.setCheckState(QtCore.Qt.Unchecked)
+ self.use_legacy_v2_onions_checkbox.setEnabled(True)
+
+ if use_legacy_v2_onions or save_private_key:
+ self.use_legacy_v2_onions_checkbox.setCheckState(QtCore.Qt.Checked)
+
+ downloads_dir = self.old_settings.get('downloads_dir')
+ self.downloads_dir_lineedit.setText(downloads_dir)
+
+ public_mode = self.old_settings.get('public_mode')
+ if public_mode:
+ self.public_mode_checkbox.setCheckState(QtCore.Qt.Checked)
+ else:
+ self.public_mode_checkbox.setCheckState(QtCore.Qt.Unchecked)
use_stealth = self.old_settings.get('use_stealth')
if use_stealth:
self.stealth_checkbox.setCheckState(QtCore.Qt.Checked)
- if save_private_key:
+ # Legacy v2 mode is forced on if Stealth is enabled
+ self.use_legacy_v2_onions_checkbox.setEnabled(False)
+ if save_private_key and self.old_settings.get('hidservauth_string') != "":
hidservauth_details.show()
self.hidservauth_copy_button.show()
else:
self.stealth_checkbox.setCheckState(QtCore.Qt.Unchecked)
+ if not save_private_key:
+ self.use_legacy_v2_onions_checkbox.setEnabled(True)
use_autoupdate = self.old_settings.get('use_autoupdate')
if use_autoupdate:
@@ -417,6 +528,10 @@ class SettingsDialog(QtWidgets.QDialog):
autoupdate_timestamp = self.old_settings.get('autoupdate_timestamp')
self._update_autoupdate_timestamp(autoupdate_timestamp)
+ locale = self.old_settings.get('locale')
+ locale_index = self.language_combobox.findData(QtCore.QVariant(locale))
+ self.language_combobox.setCurrentIndex(locale_index)
+
connection_type = self.old_settings.get('connection_type')
if connection_type == 'bundled':
if self.connection_type_bundled_radio.isEnabled():
@@ -445,13 +560,11 @@ class SettingsDialog(QtWidgets.QDialog):
if self.old_settings.get('no_bridges'):
self.tor_bridges_no_bridges_radio.setChecked(True)
self.tor_bridges_use_obfs4_radio.setChecked(False)
- self.tor_bridges_use_meek_lite_amazon_radio.setChecked(False)
self.tor_bridges_use_meek_lite_azure_radio.setChecked(False)
self.tor_bridges_use_custom_radio.setChecked(False)
else:
self.tor_bridges_no_bridges_radio.setChecked(False)
self.tor_bridges_use_obfs4_radio.setChecked(self.old_settings.get('tor_bridges_use_obfs4'))
- self.tor_bridges_use_meek_lite_amazon_radio.setChecked(self.old_settings.get('tor_bridges_use_meek_lite_amazon'))
self.tor_bridges_use_meek_lite_azure_radio.setChecked(self.old_settings.get('tor_bridges_use_meek_lite_azure'))
if self.old_settings.get('tor_bridges_use_custom_bridges'):
@@ -470,7 +583,7 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Connection type bundled was toggled. If checked, hide authentication fields.
"""
- common.log('SettingsDialog', 'connection_type_bundled_toggled')
+ self.common.log('SettingsDialog', 'connection_type_bundled_toggled')
if checked:
self.authenticate_group.hide()
self.connection_type_socks.hide()
@@ -490,19 +603,15 @@ class SettingsDialog(QtWidgets.QDialog):
if checked:
self.tor_bridges_use_custom_textbox_options.hide()
- def tor_bridges_use_meek_lite_amazon_radio_toggled(self, checked):
- """
- meek_lite-amazon bridges option was toggled. If checked, disable custom bridge options.
- """
- if checked:
- self.tor_bridges_use_custom_textbox_options.hide()
-
def tor_bridges_use_meek_lite_azure_radio_toggled(self, checked):
"""
meek_lite_azure bridges option was toggled. If checked, disable custom bridge options.
"""
if checked:
self.tor_bridges_use_custom_textbox_options.hide()
+ # Alert the user about meek's costliness if it looks like they're turning it on
+ if not self.old_settings.get('tor_bridges_use_meek_lite_azure'):
+ Alert(self.common, strings._('gui_settings_meek_lite_expensive_warning'), QtWidgets.QMessageBox.Warning)
def tor_bridges_use_custom_radio_toggled(self, checked):
"""
@@ -515,7 +624,7 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Connection type automatic was toggled. If checked, hide authentication fields.
"""
- common.log('SettingsDialog', 'connection_type_automatic_toggled')
+ self.common.log('SettingsDialog', 'connection_type_automatic_toggled')
if checked:
self.authenticate_group.hide()
self.connection_type_socks.hide()
@@ -526,7 +635,7 @@ class SettingsDialog(QtWidgets.QDialog):
Connection type control port was toggled. If checked, show extra fields
for Tor control address and port. If unchecked, hide those extra fields.
"""
- common.log('SettingsDialog', 'connection_type_control_port_toggled')
+ self.common.log('SettingsDialog', 'connection_type_control_port_toggled')
if checked:
self.authenticate_group.show()
self.connection_type_control_port_extras.show()
@@ -541,7 +650,7 @@ class SettingsDialog(QtWidgets.QDialog):
Connection type socket file was toggled. If checked, show extra fields
for socket file. If unchecked, hide those extra fields.
"""
- common.log('SettingsDialog', 'connection_type_socket_file_toggled')
+ self.common.log('SettingsDialog', 'connection_type_socket_file_toggled')
if checked:
self.authenticate_group.show()
self.connection_type_socket_file_extras.show()
@@ -554,14 +663,14 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Authentication option no authentication was toggled.
"""
- common.log('SettingsDialog', 'authenticate_no_auth_toggled')
+ self.common.log('SettingsDialog', 'authenticate_no_auth_toggled')
def authenticate_password_toggled(self, checked):
"""
Authentication option password was toggled. If checked, show extra fields
for password auth. If unchecked, hide those extra fields.
"""
- common.log('SettingsDialog', 'authenticate_password_toggled')
+ self.common.log('SettingsDialog', 'authenticate_password_toggled')
if checked:
self.authenticate_password_extras.show()
else:
@@ -572,16 +681,61 @@ class SettingsDialog(QtWidgets.QDialog):
Toggle the 'Copy HidServAuth' button
to copy the saved HidServAuth to clipboard.
"""
- common.log('SettingsDialog', 'hidservauth_copy_button_clicked', 'HidServAuth was copied to clipboard')
+ self.common.log('SettingsDialog', 'hidservauth_copy_button_clicked', 'HidServAuth was copied to clipboard')
clipboard = self.qtapp.clipboard()
clipboard.setText(self.old_settings.get('hidservauth_string'))
+ def use_legacy_v2_onions_checkbox_clicked(self, checked):
+ """
+ Show the legacy settings if the legacy mode is enabled.
+ """
+ if checked:
+ self.save_private_key_widget.show()
+ self.use_stealth_widget.show()
+ else:
+ self.save_private_key_widget.hide()
+ self.use_stealth_widget.hide()
+
+ def save_private_key_checkbox_clicked(self, checked):
+ """
+ Prevent the v2 legacy mode being switched off if persistence is enabled
+ """
+ if checked:
+ self.use_legacy_v2_onions_checkbox.setCheckState(QtCore.Qt.Checked)
+ self.use_legacy_v2_onions_checkbox.setEnabled(False)
+ else:
+ if not self.stealth_checkbox.isChecked():
+ self.use_legacy_v2_onions_checkbox.setEnabled(True)
+
+ def stealth_checkbox_clicked_connect(self, checked):
+ """
+ Prevent the v2 legacy mode being switched off if stealth is enabled
+ """
+ if checked:
+ self.use_legacy_v2_onions_checkbox.setCheckState(QtCore.Qt.Checked)
+ self.use_legacy_v2_onions_checkbox.setEnabled(False)
+ else:
+ if not self.save_private_key_checkbox.isChecked():
+ self.use_legacy_v2_onions_checkbox.setEnabled(True)
+
+ def downloads_button_clicked(self):
+ """
+ Browse for a new downloads directory
+ """
+ downloads_dir = self.downloads_dir_lineedit.text()
+ selected_dir = QtWidgets.QFileDialog.getExistingDirectory(self,
+ strings._('gui_settings_downloads_label'), downloads_dir)
+
+ if selected_dir:
+ self.common.log('SettingsDialog', 'downloads_button_clicked', 'selected dir: {}'.format(selected_dir))
+ self.downloads_dir_lineedit.setText(selected_dir)
+
def test_tor_clicked(self):
"""
Test Tor Settings button clicked. With the given settings, see if we can
successfully connect and authenticate to Tor.
"""
- common.log('SettingsDialog', 'test_tor_clicked')
+ self.common.log('SettingsDialog', 'test_tor_clicked')
settings = self.settings_from_fields()
try:
@@ -596,17 +750,17 @@ class SettingsDialog(QtWidgets.QDialog):
else:
tor_status_update_func = None
- onion = Onion()
- onion.connect(settings=settings, config=self.config, tor_status_update_func=tor_status_update_func)
+ onion = Onion(self.common)
+ onion.connect(custom_settings=settings, config=self.config, tor_status_update_func=tor_status_update_func)
# If an exception hasn't been raised yet, the Tor settings work
- Alert(strings._('settings_test_success', True).format(onion.tor_version, onion.supports_ephemeral, onion.supports_stealth))
+ Alert(self.common, strings._('settings_test_success').format(onion.tor_version, onion.supports_ephemeral, onion.supports_stealth, onion.supports_next_gen_onions))
# Clean up
onion.cleanup()
except (TorErrorInvalidSetting, TorErrorAutomatic, TorErrorSocketPort, TorErrorSocketFile, TorErrorMissingPassword, TorErrorUnreadableCookieFile, TorErrorAuthError, TorErrorProtocolError, BundledTorNotSupported, BundledTorTimeout) as e:
- Alert(e.args[0], QtWidgets.QMessageBox.Warning)
+ Alert(self.common, e.args[0], QtWidgets.QMessageBox.Warning)
if settings.get('connection_type') == 'bundled':
self.tor_status.hide()
self._enable_buttons()
@@ -615,14 +769,14 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Check for Updates button clicked. Manually force an update check.
"""
- common.log('SettingsDialog', 'check_for_updates')
+ self.common.log('SettingsDialog', 'check_for_updates')
# Disable buttons
self._disable_buttons()
self.qtapp.processEvents()
def update_timestamp():
# Update the last checked label
- settings = Settings(self.config)
+ settings = Settings(self.common, self.config)
settings.load()
autoupdate_timestamp = settings.get('autoupdate_timestamp')
self._update_autoupdate_timestamp(autoupdate_timestamp)
@@ -636,22 +790,22 @@ class SettingsDialog(QtWidgets.QDialog):
# Check for updates
def update_available(update_url, installed_version, latest_version):
- Alert(strings._("update_available", True).format(update_url, installed_version, latest_version))
+ Alert(self.common, strings._("update_available").format(update_url, installed_version, latest_version))
close_forced_update_thread()
def update_not_available():
- Alert(strings._('update_not_available', True))
+ Alert(self.common, strings._('update_not_available'))
close_forced_update_thread()
def update_error():
- Alert(strings._('update_error_check_error', True), QtWidgets.QMessageBox.Warning)
+ Alert(self.common, strings._('update_error_check_error'), QtWidgets.QMessageBox.Warning)
close_forced_update_thread()
- def update_invalid_version():
- Alert(strings._('update_error_invalid_latest_version', True).format(e.latest_version), QtWidgets.QMessageBox.Warning)
+ def update_invalid_version(latest_version):
+ Alert(self.common, strings._('update_error_invalid_latest_version').format(latest_version), QtWidgets.QMessageBox.Warning)
close_forced_update_thread()
- forced_update_thread = UpdateThread(self.onion, self.config, force=True)
+ forced_update_thread = UpdateThread(self.common, self.onion, self.config, force=True)
forced_update_thread.update_available.connect(update_available)
forced_update_thread.update_not_available.connect(update_not_available)
forced_update_thread.update_error.connect(update_error)
@@ -662,57 +816,73 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Save button clicked. Save current settings to disk.
"""
- common.log('SettingsDialog', 'save_clicked')
+ self.common.log('SettingsDialog', 'save_clicked')
+
+ def changed(s1, s2, keys):
+ """
+ Compare the Settings objects s1 and s2 and return true if any values
+ have changed for the given keys.
+ """
+ for key in keys:
+ if s1.get(key) != s2.get(key):
+ return True
+ return False
settings = self.settings_from_fields()
if settings:
+ # If language changed, inform user they need to restart OnionShare
+ if changed(settings, self.old_settings, ['locale']):
+ # Look up error message in different locale
+ new_locale = settings.get('locale')
+ if new_locale in strings.translations and 'gui_settings_language_changed_notice' in strings.translations[new_locale]:
+ notice = strings.translations[new_locale]['gui_settings_language_changed_notice']
+ else:
+ notice = strings._('gui_settings_language_changed_notice')
+ Alert(self.common, notice, QtWidgets.QMessageBox.Information)
+
+ # Save the new settings
settings.save()
# If Tor isn't connected, or if Tor settings have changed, Reinitialize
# the Onion object
reboot_onion = False
- if self.onion.is_authenticated():
- common.log('SettingsDialog', 'save_clicked', 'Connected to Tor')
- def changed(s1, s2, keys):
- """
- Compare the Settings objects s1 and s2 and return true if any values
- have changed for the given keys.
- """
- for key in keys:
- if s1.get(key) != s2.get(key):
- return True
- return False
-
- if changed(settings, self.old_settings, [
- 'connection_type', 'control_port_address',
- 'control_port_port', 'socks_address', 'socks_port',
- 'socket_file_path', 'auth_type', 'auth_password',
- 'no_bridges', 'tor_bridges_use_obfs4',
- 'tor_bridges_use_meek_lite_amazon', 'tor_bridges_use_meek_lite_azure',
- 'tor_bridges_use_custom_bridges']):
-
+ if not self.local_only:
+ if self.onion.is_authenticated():
+ self.common.log('SettingsDialog', 'save_clicked', 'Connected to Tor')
+
+ if changed(settings, self.old_settings, [
+ 'connection_type', 'control_port_address',
+ 'control_port_port', 'socks_address', 'socks_port',
+ 'socket_file_path', 'auth_type', 'auth_password',
+ 'no_bridges', 'tor_bridges_use_obfs4',
+ 'tor_bridges_use_meek_lite_azure',
+ 'tor_bridges_use_custom_bridges']):
+
+ reboot_onion = True
+
+ else:
+ self.common.log('SettingsDialog', 'save_clicked', 'Not connected to Tor')
+ # Tor isn't connected, so try connecting
reboot_onion = True
- else:
- common.log('SettingsDialog', 'save_clicked', 'Not connected to Tor')
- # Tor isn't connected, so try connecting
- reboot_onion = True
+ # Do we need to reinitialize Tor?
+ if reboot_onion:
+ # Reinitialize the Onion object
+ self.common.log('SettingsDialog', 'save_clicked', 'rebooting the Onion')
+ self.onion.cleanup()
- # Do we need to reinitialize Tor?
- if reboot_onion:
- # Reinitialize the Onion object
- common.log('SettingsDialog', 'save_clicked', 'rebooting the Onion')
- self.onion.cleanup()
+ tor_con = TorConnectionDialog(self.common, self.qtapp, self.onion, settings)
+ tor_con.start()
- tor_con = TorConnectionDialog(self.qtapp, settings, self.onion)
- tor_con.start()
+ self.common.log('SettingsDialog', 'save_clicked', 'Onion done rebooting, connected to Tor: {}'.format(self.onion.connected_to_tor))
- common.log('SettingsDialog', 'save_clicked', 'Onion done rebooting, connected to Tor: {}'.format(self.onion.connected_to_tor))
+ if self.onion.is_authenticated() and not tor_con.wasCanceled():
+ self.settings_saved.emit()
+ self.close()
- if self.onion.is_authenticated() and not tor_con.wasCanceled():
+ else:
self.settings_saved.emit()
self.close()
-
else:
self.settings_saved.emit()
self.close()
@@ -721,9 +891,9 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Cancel button clicked.
"""
- common.log('SettingsDialog', 'cancel_clicked')
- if not self.onion.is_authenticated():
- Alert(strings._('gui_tor_connection_canceled', True), QtWidgets.QMessageBox.Warning)
+ self.common.log('SettingsDialog', 'cancel_clicked')
+ if not self.local_only and not self.onion.is_authenticated():
+ Alert(self.common, strings._('gui_tor_connection_canceled'), QtWidgets.QMessageBox.Warning)
sys.exit()
else:
self.close()
@@ -732,22 +902,34 @@ class SettingsDialog(QtWidgets.QDialog):
"""
Help button clicked.
"""
- common.log('SettingsDialog', 'help_clicked')
- help_site = 'https://github.com/micahflee/onionshare/wiki'
- QtGui.QDesktopServices.openUrl(QtCore.QUrl(help_site))
+ self.common.log('SettingsDialog', 'help_clicked')
+ SettingsDialog.open_help()
+
+ @staticmethod
+ def open_help():
+ help_url = 'https://github.com/micahflee/onionshare/wiki'
+ QtGui.QDesktopServices.openUrl(QtCore.QUrl(help_url))
def settings_from_fields(self):
"""
Return a Settings object that's full of values from the settings dialog.
"""
- common.log('SettingsDialog', 'settings_from_fields')
- settings = Settings(self.config)
+ self.common.log('SettingsDialog', 'settings_from_fields')
+ settings = Settings(self.common, self.config)
settings.load() # To get the last update timestamp
settings.set('close_after_first_download', self.close_after_first_download_checkbox.isChecked())
- settings.set('systray_notifications', self.systray_notifications_checkbox.isChecked())
settings.set('shutdown_timeout', self.shutdown_timeout_checkbox.isChecked())
+
+ # Complicated logic here to force v2 onion mode on or off depending on other settings
+ if self.use_legacy_v2_onions_checkbox.isChecked():
+ use_legacy_v2_onions = True
+ else:
+ use_legacy_v2_onions = False
+
if self.save_private_key_checkbox.isChecked():
+ # force the legacy mode on
+ use_legacy_v2_onions = True
settings.set('save_private_key', True)
settings.set('private_key', self.old_settings.get('private_key'))
settings.set('slug', self.old_settings.get('slug'))
@@ -758,11 +940,31 @@ class SettingsDialog(QtWidgets.QDialog):
settings.set('slug', '')
# Also unset the HidServAuth if we are removing our reusable private key
settings.set('hidservauth_string', '')
+
+ if use_legacy_v2_onions:
+ settings.set('use_legacy_v2_onions', True)
+ else:
+ settings.set('use_legacy_v2_onions', False)
+ # If we are not using legacy mode, but we previously had persistence turned on, force it off!
+ settings.set('save_private_key', False)
+ settings.set('private_key', '')
+ settings.set('slug', '')
+ # Also unset the HidServAuth if we are removing our reusable private key
+ settings.set('hidservauth_string', '')
+
+ settings.set('downloads_dir', self.downloads_dir_lineedit.text())
+ settings.set('public_mode', self.public_mode_checkbox.isChecked())
settings.set('use_stealth', self.stealth_checkbox.isChecked())
# Always unset the HidServAuth if Stealth mode is unset
if not self.stealth_checkbox.isChecked():
settings.set('hidservauth_string', '')
+ # Language
+ locale_index = self.language_combobox.currentIndex()
+ locale = self.language_combobox.itemData(locale_index)
+ settings.set('locale', locale)
+
+ # Tor connection
if self.connection_type_bundled_radio.isChecked():
settings.set('connection_type', 'bundled')
if self.connection_type_automatic_radio.isChecked():
@@ -795,31 +997,21 @@ class SettingsDialog(QtWidgets.QDialog):
if self.tor_bridges_no_bridges_radio.isChecked():
settings.set('no_bridges', True)
settings.set('tor_bridges_use_obfs4', False)
- settings.set('tor_bridges_use_meek_lite_amazon', False)
settings.set('tor_bridges_use_meek_lite_azure', False)
settings.set('tor_bridges_use_custom_bridges', '')
if self.tor_bridges_use_obfs4_radio.isChecked():
settings.set('no_bridges', False)
settings.set('tor_bridges_use_obfs4', True)
- settings.set('tor_bridges_use_meek_lite_amazon', False)
- settings.set('tor_bridges_use_meek_lite_azure', False)
- settings.set('tor_bridges_use_custom_bridges', '')
- if self.tor_bridges_use_meek_lite_amazon_radio.isChecked():
- settings.set('no_bridges', False)
- settings.set('tor_bridges_use_obfs4', False)
- settings.set('tor_bridges_use_meek_lite_amazon', True)
settings.set('tor_bridges_use_meek_lite_azure', False)
settings.set('tor_bridges_use_custom_bridges', '')
if self.tor_bridges_use_meek_lite_azure_radio.isChecked():
settings.set('no_bridges', False)
settings.set('tor_bridges_use_obfs4', False)
- settings.set('tor_bridges_use_meek_lite_amazon', False)
settings.set('tor_bridges_use_meek_lite_azure', True)
settings.set('tor_bridges_use_custom_bridges', '')
if self.tor_bridges_use_custom_radio.isChecked():
settings.set('no_bridges', False)
settings.set('tor_bridges_use_obfs4', False)
- settings.set('tor_bridges_use_meek_lite_amazon', False)
settings.set('tor_bridges_use_meek_lite_azure', False)
# Insert a 'Bridge' line at the start of each bridge.
@@ -846,41 +1038,42 @@ class SettingsDialog(QtWidgets.QDialog):
new_bridges = ''.join(new_bridges)
settings.set('tor_bridges_use_custom_bridges', new_bridges)
else:
- Alert(strings._('gui_settings_tor_bridges_invalid', True))
+ Alert(self.common, strings._('gui_settings_tor_bridges_invalid'))
settings.set('no_bridges', True)
return False
return settings
def closeEvent(self, e):
- common.log('SettingsDialog', 'closeEvent')
+ self.common.log('SettingsDialog', 'closeEvent')
# On close, if Tor isn't connected, then quit OnionShare altogether
- if not self.onion.is_authenticated():
- common.log('SettingsDialog', 'closeEvent', 'Closing while not connected to Tor')
+ if not self.local_only:
+ if not self.onion.is_authenticated():
+ self.common.log('SettingsDialog', 'closeEvent', 'Closing while not connected to Tor')
- # Wait 1ms for the event loop to finish, then quit
- QtCore.QTimer.singleShot(1, self.qtapp.quit)
+ # Wait 1ms for the event loop to finish, then quit
+ QtCore.QTimer.singleShot(1, self.qtapp.quit)
def _update_autoupdate_timestamp(self, autoupdate_timestamp):
- common.log('SettingsDialog', '_update_autoupdate_timestamp')
+ self.common.log('SettingsDialog', '_update_autoupdate_timestamp')
if autoupdate_timestamp:
dt = datetime.datetime.fromtimestamp(autoupdate_timestamp)
last_checked = dt.strftime('%B %d, %Y %H:%M')
else:
- last_checked = strings._('gui_settings_autoupdate_timestamp_never', True)
- self.autoupdate_timestamp.setText(strings._('gui_settings_autoupdate_timestamp', True).format(last_checked))
+ last_checked = strings._('gui_settings_autoupdate_timestamp_never')
+ self.autoupdate_timestamp.setText(strings._('gui_settings_autoupdate_timestamp').format(last_checked))
def _tor_status_update(self, progress, summary):
- self.tor_status.setText('<strong>{}</strong><br>{}% {}'.format(strings._('connecting_to_tor', True), progress, summary))
+ self.tor_status.setText('<strong>{}</strong><br>{}% {}'.format(strings._('connecting_to_tor'), progress, summary))
self.qtapp.processEvents()
if 'Done' in summary:
self.tor_status.hide()
self._enable_buttons()
def _disable_buttons(self):
- common.log('SettingsDialog', '_disable_buttons')
+ self.common.log('SettingsDialog', '_disable_buttons')
self.check_for_updates_button.setEnabled(False)
self.connection_type_test_button.setEnabled(False)
@@ -888,7 +1081,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.cancel_button.setEnabled(False)
def _enable_buttons(self):
- common.log('SettingsDialog', '_enable_buttons')
+ self.common.log('SettingsDialog', '_enable_buttons')
# We can't check for updates if we're still not connected to Tor
if not self.onion.connected_to_tor:
self.check_for_updates_button.setEnabled(False)
diff --git a/onionshare_gui/threads.py b/onionshare_gui/threads.py
new file mode 100644
index 00000000..3b05bebf
--- /dev/null
+++ b/onionshare_gui/threads.py
@@ -0,0 +1,77 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+import time
+from PyQt5 import QtCore
+
+from onionshare.onion import *
+
+
+class OnionThread(QtCore.QThread):
+ """
+ Starts the onion service, and waits for it to finish
+ """
+ success = QtCore.pyqtSignal()
+ error = QtCore.pyqtSignal(str)
+
+ def __init__(self, mode):
+ super(OnionThread, self).__init__()
+ self.mode = mode
+ self.mode.common.log('OnionThread', '__init__')
+
+ # allow this thread to be terminated
+ self.setTerminationEnabled()
+
+ def run(self):
+ self.mode.common.log('OnionThread', 'run')
+
+ self.mode.app.stay_open = not self.mode.common.settings.get('close_after_first_download')
+
+ # start onionshare http service in new thread
+ self.mode.web_thread = WebThread(self.mode)
+ self.mode.web_thread.start()
+
+ # wait for modules in thread to load, preventing a thread-related cx_Freeze crash
+ time.sleep(0.2)
+
+ try:
+ self.mode.app.start_onion_service()
+ self.success.emit()
+
+ except (TorTooOld, TorErrorInvalidSetting, TorErrorAutomatic, TorErrorSocketPort, TorErrorSocketFile, TorErrorMissingPassword, TorErrorUnreadableCookieFile, TorErrorAuthError, TorErrorProtocolError, BundledTorTimeout, OSError) as e:
+ self.error.emit(e.args[0])
+ return
+
+
+class WebThread(QtCore.QThread):
+ """
+ Starts the web service
+ """
+ success = QtCore.pyqtSignal()
+ error = QtCore.pyqtSignal(str)
+
+ def __init__(self, mode):
+ super(WebThread, self).__init__()
+ self.mode = mode
+ self.mode.common.log('WebThread', '__init__')
+
+ def run(self):
+ self.mode.common.log('WebThread', 'run')
+ self.mode.app.choose_port()
+ self.mode.web.start(self.mode.app.port, self.mode.app.stay_open, self.mode.common.settings.get('public_mode'), self.mode.common.settings.get('slug'))
diff --git a/onionshare_gui/tor_connection_dialog.py b/onionshare_gui/tor_connection_dialog.py
index 12730c32..2bcbf1a6 100644
--- a/onionshare_gui/tor_connection_dialog.py
+++ b/onionshare_gui/tor_connection_dialog.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -19,10 +19,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from PyQt5 import QtCore, QtWidgets, QtGui
-from onionshare import strings, common
+from onionshare import strings
from onionshare.onion import *
-from .alert import Alert
+from .widgets import Alert
class TorConnectionDialog(QtWidgets.QProgressDialog):
"""
@@ -30,21 +30,28 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
"""
open_settings = QtCore.pyqtSignal()
- def __init__(self, qtapp, settings, onion):
+ def __init__(self, common, qtapp, onion, custom_settings=False):
super(TorConnectionDialog, self).__init__(None)
- common.log('TorConnectionDialog', '__init__')
+
+ self.common = common
+
+ if custom_settings:
+ self.settings = custom_settings
+ else:
+ self.settings = self.common.settings
+
+ self.common.log('TorConnectionDialog', '__init__')
self.qtapp = qtapp
- self.settings = settings
self.onion = onion
self.setWindowTitle("OnionShare")
- self.setWindowIcon(QtGui.QIcon(common.get_resource_path('images/logo.png')))
+ self.setWindowIcon(QtGui.QIcon(self.common.get_resource_path('images/logo.png')))
self.setModal(True)
self.setFixedSize(400, 150)
# Label
- self.setLabelText(strings._('connecting_to_tor', True))
+ self.setLabelText(strings._('connecting_to_tor'))
# Progress bar ticks from 0 to 100
self.setRange(0, 100)
@@ -55,9 +62,9 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
self._tor_status_update(0, '')
def start(self):
- common.log('TorConnectionDialog', 'start')
+ self.common.log('TorConnectionDialog', 'start')
- t = TorConnectionThread(self, self.settings, self.onion)
+ t = TorConnectionThread(self.common, self.settings, self, self.onion)
t.tor_status_update.connect(self._tor_status_update)
t.connected_to_tor.connect(self._connected_to_tor)
t.canceled_connecting_to_tor.connect(self._canceled_connecting_to_tor)
@@ -74,17 +81,17 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
def _tor_status_update(self, progress, summary):
self.setValue(int(progress))
- self.setLabelText("<strong>{}</strong><br>{}".format(strings._('connecting_to_tor', True), summary))
+ self.setLabelText("<strong>{}</strong><br>{}".format(strings._('connecting_to_tor'), summary))
def _connected_to_tor(self):
- common.log('TorConnectionDialog', '_connected_to_tor')
+ self.common.log('TorConnectionDialog', '_connected_to_tor')
self.active = False
# Close the dialog after connecting
self.setValue(self.maximum())
def _canceled_connecting_to_tor(self):
- common.log('TorConnectionDialog', '_canceled_connecting_to_tor')
+ self.common.log('TorConnectionDialog', '_canceled_connecting_to_tor')
self.active = False
self.onion.cleanup()
@@ -92,12 +99,12 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
QtCore.QTimer.singleShot(1, self.cancel)
def _error_connecting_to_tor(self, msg):
- common.log('TorConnectionDialog', '_error_connecting_to_tor')
+ self.common.log('TorConnectionDialog', '_error_connecting_to_tor')
self.active = False
def alert_and_open_settings():
# Display the exception in an alert box
- Alert("{}\n\n{}".format(msg, strings._('gui_tor_connection_error_settings', True)), QtWidgets.QMessageBox.Warning)
+ Alert(self.common, "{}\n\n{}".format(msg, strings._('gui_tor_connection_error_settings')), QtWidgets.QMessageBox.Warning)
# Open settings
self.open_settings.emit()
@@ -113,16 +120,20 @@ class TorConnectionThread(QtCore.QThread):
canceled_connecting_to_tor = QtCore.pyqtSignal()
error_connecting_to_tor = QtCore.pyqtSignal(str)
- def __init__(self, dialog, settings, onion):
+ def __init__(self, common, settings, dialog, onion):
super(TorConnectionThread, self).__init__()
- common.log('TorConnectionThread', '__init__')
- self.dialog = dialog
+ self.common = common
+
+ self.common.log('TorConnectionThread', '__init__')
+
self.settings = settings
+
+ self.dialog = dialog
self.onion = onion
def run(self):
- common.log('TorConnectionThread', 'run')
+ self.common.log('TorConnectionThread', 'run')
# Connect to the Onion
try:
@@ -133,11 +144,11 @@ class TorConnectionThread(QtCore.QThread):
self.canceled_connecting_to_tor.emit()
except BundledTorCanceled as e:
- common.log('TorConnectionThread', 'run', 'caught exception: BundledTorCanceled')
+ self.common.log('TorConnectionThread', 'run', 'caught exception: BundledTorCanceled')
self.canceled_connecting_to_tor.emit()
except Exception as e:
- common.log('TorConnectionThread', 'run', 'caught exception: {}'.format(e.args[0]))
+ self.common.log('TorConnectionThread', 'run', 'caught exception: {}'.format(e.args[0]))
self.error_connecting_to_tor.emit(str(e.args[0]))
def _tor_status_update(self, progress, summary):
diff --git a/onionshare_gui/update_checker.py b/onionshare_gui/update_checker.py
index 5d73efb4..a7e0b99c 100644
--- a/onionshare_gui/update_checker.py
+++ b/onionshare_gui/update_checker.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -19,13 +19,13 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from PyQt5 import QtCore
import datetime, time, socket, re, platform
+import socks
from distutils.version import LooseVersion as Version
-from onionshare import socks
from onionshare.settings import Settings
from onionshare.onion import Onion
-from . import strings, common
+from . import strings
class UpdateCheckerCheckError(Exception):
"""
@@ -53,18 +53,21 @@ class UpdateChecker(QtCore.QObject):
update_available = QtCore.pyqtSignal(str, str, str)
update_not_available = QtCore.pyqtSignal()
update_error = QtCore.pyqtSignal()
- update_invalid_version = QtCore.pyqtSignal()
+ update_invalid_version = QtCore.pyqtSignal(str)
- def __init__(self, onion, config=False):
+ def __init__(self, common, onion, config=False):
super(UpdateChecker, self).__init__()
- common.log('UpdateChecker', '__init__')
+
+ self.common = common
+
+ self.common.log('UpdateChecker', '__init__')
self.onion = onion
self.config = config
def check(self, force=False, config=False):
- common.log('UpdateChecker', 'check', 'force={}'.format(force))
+ self.common.log('UpdateChecker', 'check', 'force={}'.format(force))
# Load the settings
- settings = Settings(config)
+ settings = Settings(self.common, config)
settings.load()
# If force=True, then definitely check
@@ -87,11 +90,11 @@ class UpdateChecker(QtCore.QObject):
# Check for updates
if check_for_updates:
- common.log('UpdateChecker', 'check', 'checking for updates')
+ self.common.log('UpdateChecker', 'check', 'checking for updates')
# Download the latest-version file over Tor
try:
# User agent string includes OnionShare version and platform
- user_agent = 'OnionShare {}, {}'.format(common.get_version(), platform.system())
+ user_agent = 'OnionShare {}, {}'.format(self.common.version, self.common.platform)
# If the update is forced, add '?force=1' to the URL, to more
# accurately measure daily users
@@ -104,7 +107,7 @@ class UpdateChecker(QtCore.QObject):
else:
onion_domain = 'elx57ue5uyfplgva.onion'
- common.log('UpdateChecker', 'check', 'loading http://{}{}'.format(onion_domain, path))
+ self.common.log('UpdateChecker', 'check', 'loading http://{}{}'.format(onion_domain, path))
(socks_address, socks_port) = self.onion.get_tor_socks_port()
socks.set_default_proxy(socks.SOCKS5, socks_address, socks_port)
@@ -122,10 +125,10 @@ class UpdateChecker(QtCore.QObject):
http_response = s.recv(1024)
latest_version = http_response[http_response.find(b'\r\n\r\n'):].strip().decode('utf-8')
- common.log('UpdateChecker', 'check', 'latest OnionShare version: {}'.format(latest_version))
+ self.common.log('UpdateChecker', 'check', 'latest OnionShare version: {}'.format(latest_version))
except Exception as e:
- common.log('UpdateChecker', 'check', '{}'.format(e))
+ self.common.log('UpdateChecker', 'check', '{}'.format(e))
self.update_error.emit()
raise UpdateCheckerCheckError
@@ -133,7 +136,7 @@ class UpdateChecker(QtCore.QObject):
# This regex is: 1-3 dot-separated numeric components
version_re = r"^(\d+\.)?(\d+\.)?(\d+)$"
if not re.match(version_re, latest_version):
- self.update_invalid_version.emit()
+ self.update_invalid_version.emit(latest_version)
raise UpdateCheckerInvalidLatestVersion(latest_version)
# Update the last checked timestamp (dropping the seconds and milliseconds)
@@ -145,7 +148,7 @@ class UpdateChecker(QtCore.QObject):
# Do we need to update?
update_url = 'https://github.com/micahflee/onionshare/releases/tag/v{}'.format(latest_version)
- installed_version = common.get_version()
+ installed_version = self.common.version
if installed_version < latest_version:
self.update_available.emit(update_url, installed_version, latest_version)
return
@@ -157,19 +160,22 @@ class UpdateThread(QtCore.QThread):
update_available = QtCore.pyqtSignal(str, str, str)
update_not_available = QtCore.pyqtSignal()
update_error = QtCore.pyqtSignal()
- update_invalid_version = QtCore.pyqtSignal()
+ update_invalid_version = QtCore.pyqtSignal(str)
- def __init__(self, onion, config=False, force=False):
+ def __init__(self, common, onion, config=False, force=False):
super(UpdateThread, self).__init__()
- common.log('UpdateThread', '__init__')
+
+ self.common = common
+
+ self.common.log('UpdateThread', '__init__')
self.onion = onion
self.config = config
self.force = force
def run(self):
- common.log('UpdateThread', 'run')
+ self.common.log('UpdateThread', 'run')
- u = UpdateChecker(self.onion, self.config)
+ u = UpdateChecker(self.common, self.onion, self.config)
u.update_available.connect(self._update_available)
u.update_not_available.connect(self._update_not_available)
u.update_error.connect(self._update_error)
@@ -179,25 +185,25 @@ class UpdateThread(QtCore.QThread):
u.check(config=self.config,force=self.force)
except Exception as e:
# If update check fails, silently ignore
- common.log('UpdateThread', 'run', '{}'.format(e))
+ self.common.log('UpdateThread', 'run', '{}'.format(e))
pass
def _update_available(self, update_url, installed_version, latest_version):
- common.log('UpdateThread', '_update_available')
+ self.common.log('UpdateThread', '_update_available')
self.active = False
self.update_available.emit(update_url, installed_version, latest_version)
def _update_not_available(self):
- common.log('UpdateThread', '_update_not_available')
+ self.common.log('UpdateThread', '_update_not_available')
self.active = False
self.update_not_available.emit()
def _update_error(self):
- common.log('UpdateThread', '_update_error')
+ self.common.log('UpdateThread', '_update_error')
self.active = False
self.update_error.emit()
- def _update_invalid_version(self):
- common.log('UpdateThread', '_update_invalid_version')
+ def _update_invalid_version(self, latest_version):
+ self.common.log('UpdateThread', '_update_invalid_version')
self.active = False
- self.update_invalid_version.emit()
+ self.update_invalid_version.emit(latest_version)
diff --git a/onionshare_gui/widgets.py b/onionshare_gui/widgets.py
new file mode 100644
index 00000000..eaa5904d
--- /dev/null
+++ b/onionshare_gui/widgets.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+from PyQt5 import QtCore, QtWidgets, QtGui
+
+class Alert(QtWidgets.QMessageBox):
+ """
+ An alert box dialog.
+ """
+ def __init__(self, common, message, icon=QtWidgets.QMessageBox.NoIcon, buttons=QtWidgets.QMessageBox.Ok, autostart=True):
+ super(Alert, self).__init__(None)
+
+ self.common = common
+
+ self.common.log('Alert', '__init__')
+
+ self.setWindowTitle("OnionShare")
+ self.setWindowIcon(QtGui.QIcon(self.common.get_resource_path('images/logo.png')))
+ self.setText(message)
+ self.setIcon(icon)
+ self.setStandardButtons(buttons)
+
+ if autostart:
+ self.exec_()
+
+
+class AddFileDialog(QtWidgets.QFileDialog):
+ """
+ Overridden version of QFileDialog which allows us to select folders as well
+ as, or instead of, files. For adding files/folders to share.
+ """
+ def __init__(self, common, *args, **kwargs):
+ QtWidgets.QFileDialog.__init__(self, *args, **kwargs)
+
+ self.common = common
+ self.common.log('AddFileDialog', '__init__')
+
+ self.setOption(self.DontUseNativeDialog, True)
+ self.setOption(self.ReadOnly, True)
+ self.setOption(self.ShowDirsOnly, False)
+ self.setFileMode(self.ExistingFiles)
+ tree_view = self.findChild(QtWidgets.QTreeView)
+ tree_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
+ list_view = self.findChild(QtWidgets.QListView, "listView")
+ list_view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
+
+ def accept(self):
+ self.common.log('AddFileDialog', 'accept')
+ QtWidgets.QDialog.accept(self)
diff --git a/screenshots/client.png b/screenshots/client.png
deleted file mode 100644
index fdf69fd0..00000000
--- a/screenshots/client.png
+++ /dev/null
Binary files differ
diff --git a/screenshots/onionshare-receive-client.png b/screenshots/onionshare-receive-client.png
new file mode 100644
index 00000000..7702a4bd
--- /dev/null
+++ b/screenshots/onionshare-receive-client.png
Binary files differ
diff --git a/screenshots/onionshare-receive-server.png b/screenshots/onionshare-receive-server.png
new file mode 100644
index 00000000..0962a74f
--- /dev/null
+++ b/screenshots/onionshare-receive-server.png
Binary files differ
diff --git a/screenshots/onionshare-share-client.png b/screenshots/onionshare-share-client.png
new file mode 100644
index 00000000..7cb6c3c8
--- /dev/null
+++ b/screenshots/onionshare-share-client.png
Binary files differ
diff --git a/screenshots/onionshare-share-server.png b/screenshots/onionshare-share-server.png
new file mode 100644
index 00000000..76830876
--- /dev/null
+++ b/screenshots/onionshare-share-server.png
Binary files differ
diff --git a/screenshots/server.png b/screenshots/server.png
deleted file mode 100644
index 8bdf2971..00000000
--- a/screenshots/server.png
+++ /dev/null
Binary files differ
diff --git a/setup.py b/setup.py
index 14cf05b1..86b71f82 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -47,12 +47,15 @@ license = 'GPL v3'
keywords = 'onion, share, onionshare, tor, anonymous, web server'
data_files=[
(os.path.join(sys.prefix, 'share/applications'), ['install/onionshare.desktop']),
- (os.path.join(sys.prefix, 'share/appdata'), ['install/onionshare.appdata.xml']),
+ (os.path.join(sys.prefix, 'share/metainfo'), ['install/onionshare.appdata.xml']),
(os.path.join(sys.prefix, 'share/pixmaps'), ['install/onionshare80.xpm']),
(os.path.join(sys.prefix, 'share/onionshare'), file_list('share')),
(os.path.join(sys.prefix, 'share/onionshare/images'), file_list('share/images')),
(os.path.join(sys.prefix, 'share/onionshare/locale'), file_list('share/locale')),
- (os.path.join(sys.prefix, 'share/onionshare/html'), file_list('share/html')),
+ (os.path.join(sys.prefix, 'share/onionshare/templates'), file_list('share/templates')),
+ (os.path.join(sys.prefix, 'share/onionshare/static/css'), file_list('share/static/css')),
+ (os.path.join(sys.prefix, 'share/onionshare/static/img'), file_list('share/static/img')),
+ (os.path.join(sys.prefix, 'share/onionshare/static/js'), file_list('share/static/js'))
]
if platform.system() != 'OpenBSD':
data_files.append(('/usr/share/nautilus-python/extensions/', ['install/scripts/onionshare-nautilus.py']))
@@ -62,7 +65,14 @@ setup(
description=description, long_description=long_description,
author=author, author_email=author_email,
url=url, license=license, keywords=keywords,
- packages=['onionshare', 'onionshare_gui'],
+ packages=[
+ 'onionshare',
+ 'onionshare.web',
+ 'onionshare_gui',
+ 'onionshare_gui.mode',
+ 'onionshare_gui.mode.share_mode',
+ 'onionshare_gui.mode.receive_mode'
+ ],
include_package_data=True,
scripts=['install/scripts/onionshare', 'install/scripts/onionshare-gui'],
data_files=data_files
diff --git a/share/html/404.html b/share/html/404.html
deleted file mode 100644
index 09d0fc3c..00000000
--- a/share/html/404.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Error 404</title>
- <link href="data:image/x-icon;base64,{{favicon_b64}}" rel="icon" type="image/x-icon" />
- <style type="text/css">
- body {
- background-color: #FFC4D5;
- color: #FF0048;
- text-align: center;
- font-size: 20em;
- }
- </style>
- </head>
- <body>404</body>
-</html>
diff --git a/share/html/denied.html b/share/html/denied.html
deleted file mode 100644
index a82ac027..00000000
--- a/share/html/denied.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>OnionShare</title>
- <link href="data:image/x-icon;base64,{{favicon_b64}}" rel="icon" type="image/x-icon" />
- <style>
- body {
- background-color: #222222;
- color: #ffffff;
- text-align: center;
- font-family: sans-serif;
- padding: 5em 1em;
- }
- </style>
- </head>
- <body>
- <p>OnionShare download in progress</p>
- </body>
-</html>
diff --git a/share/html/index.html b/share/html/index.html
deleted file mode 100644
index 57711e02..00000000
--- a/share/html/index.html
+++ /dev/null
@@ -1,208 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>OnionShare</title>
- <link href="data:image/x-icon;base64,{{favicon_b64}}" rel="icon" type="image/x-icon" />
- <style type="text/css">
- .clearfix:after {
- content: ".";
- display: block;
- clear: both;
- visibility: hidden;
- line-height: 0;
- height: 0;
- }
-
- body {
- margin: 0;
- font-family: Helvetica;
- }
-
- header {
- border-bottom: 1px solid rgba(0, 0, 0, 0.1);
- background: #fcfcfc;
- background: -webkit-linear-gradient(top, #fcfcfc 0%, #f2f2f2 100%);
- padding: 0.8rem;
- }
-
- header .logo {
- vertical-align: middle;
- width: 45px;
- height: 45px;
- }
-
- header h1 {
- display: inline-block;
- margin: 0 0 0 0.5rem;
- vertical-align: middle;
- font-weight: normal;
- font-size: 1.5rem;
- color: #666666;
- }
-
- header .right {
- float: right;
- font-size: .75rem;
- }
-
- header .right ul li {
- display: inline;
- margin: 0 0 0 .5rem;
- font-size: 1rem;
- }
-
- header .button {
- color: #ffffff;
- background-color: #4e064f;
- padding: 10px;
- border-radius: 5px;
- text-decoration: none;
- margin-left: 1rem;
- cursor: pointer;
- }
-
- table.file-list {
- width: 100%;
- margin: 0 auto;
- border-collapse: collapse;
- }
-
- table.file-list th {
- text-align: left;
- text-transform: uppercase;
- font-weight: normal;
- color: #666666;
- padding: 0.5rem;
- }
-
- table.file-list tr {
- border-bottom: 1px solid #e0e0e0;
- }
-
- table.file-list td {
- white-space: nowrap;
- padding: 0.5rem 10rem 0.5rem 0.8rem;
- }
-
- table.file-list td img {
- vertical-align: middle;
- margin-right: 0.5rem;
- }
-
- table.file-list td:last-child {
- width: 100%;
- }
- </style>
- <meta name="onionshare-filename" content="{{ filename }}">
- <meta name="onionshare-filesize" content="{{ filesize }}">
- </head>
- <body>
-
- <header class="clearfix">
- <div class="right">
- <ul>
- <li>Total size: <strong>{{ filesize_human }}</strong> (compressed)</li>
- <li><a class="button" href='/{{ slug }}/download'>Download Files</a></li>
- </ul>
- </div>
- <img class="logo" src="data:image/png;base64,{{logo_b64}}" title="OnionShare">
- <h1>OnionShare</h1>
- </header>
-
- <table class="file-list" id="file-list">
- <tr>
- <th onclick="sortTable(0)">Filename</th>
- <th onclick="sortTable(1)">Size</th>
- <th></th>
- </tr>
- {% for info in file_info.dirs %}
- <tr>
- <td>
- <img width="30" height="30" title="" alt="" src="data:image/png;base64,{{ folder_b64 }}" />
- {{ info.basename }}
- </td>
- <td>{{ info.size_human }}</td>
- <td></td>
- </tr>
- {% endfor %}
- {% for info in file_info.files %}
- <tr>
- <td>
- <img width="30" height="30" title="" alt="" src="data:image/png;base64,{{ file_b64 }}" />
- {{ info.basename }}
- </td>
- <td>{{ info.size_human }}</td>
- <td></td>
- </tr>
- {% endfor %}
- </table>
- <script>
- // Function to convert human-readable sizes back to bytes, for sorting
- function unhumanize(text) {
- var powers = {'b': 0, 'k': 1, 'm': 2, 'g': 3, 't': 4};
- var regex = /(\d+(?:\.\d+)?)\s?(B|K|M|G|T)?/i;
- var res = regex.exec(text);
- if(res[2] === undefined) {
- // Account for alphabetical words (file/dir names)
- return text;
- } else {
- return res[1] * Math.pow(1024, powers[res[2].toLowerCase()]);
- }
- }
- function sortTable(n) {
- var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
- table = document.getElementById("file-list");
- switching = true;
- // Set the sorting direction to ascending:
- dir = "asc";
- /* Make a loop that will continue until
- no switching has been done: */
- while (switching) {
- // Start by saying: no switching is done:
- switching = false;
- rows = table.getElementsByTagName("TR");
- /* Loop through all table rows (except the
- first, which contains table headers): */
- for (i = 1; i < (rows.length - 1); i++) {
- // Start by saying there should be no switching:
- shouldSwitch = false;
- /* Get the two elements you want to compare,
- one from current row and one from the next: */
- x = rows[i].getElementsByTagName("TD")[n];
- y = rows[i + 1].getElementsByTagName("TD")[n];
- /* Check if the two rows should switch place,
- based on the direction, asc or desc: */
- if (dir == "asc") {
- if (unhumanize(x.innerHTML.toLowerCase()) > unhumanize(y.innerHTML.toLowerCase())) {
- // If so, mark as a switch and break the loop:
- shouldSwitch= true;
- break;
- }
- } else if (dir == "desc") {
- if (unhumanize(x.innerHTML.toLowerCase()) < unhumanize(y.innerHTML.toLowerCase())) {
- // If so, mark as a switch and break the loop:
- shouldSwitch= true;
- break;
- }
- }
- }
- if (shouldSwitch) {
- /* If a switch has been marked, make the switch
- and mark that a switch has been done: */
- rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
- switching = true;
- // Each time a switch is done, increase this count by 1:
- switchcount ++;
- } else {
- /* If no switching has been done AND the direction is "asc",
- set the direction to "desc" and run the while loop again. */
- if (switchcount == 0 && dir == "asc") {
- dir = "desc";
- switching = true;
- }
- }
- }
- }
- </script>
- </body>
-</html>
diff --git a/share/images/downloads.png b/share/images/downloads.png
new file mode 100644
index 00000000..ad879b6e
--- /dev/null
+++ b/share/images/downloads.png
Binary files differ
diff --git a/share/images/downloads_toggle.png b/share/images/downloads_toggle.png
new file mode 100644
index 00000000..846ececb
--- /dev/null
+++ b/share/images/downloads_toggle.png
Binary files differ
diff --git a/share/images/downloads_toggle_selected.png b/share/images/downloads_toggle_selected.png
new file mode 100644
index 00000000..127ce208
--- /dev/null
+++ b/share/images/downloads_toggle_selected.png
Binary files differ
diff --git a/share/images/downloads_transparent.png b/share/images/downloads_transparent.png
new file mode 100644
index 00000000..99207097
--- /dev/null
+++ b/share/images/downloads_transparent.png
Binary files differ
diff --git a/share/images/open_folder.png b/share/images/open_folder.png
new file mode 100644
index 00000000..0a734c41
--- /dev/null
+++ b/share/images/open_folder.png
Binary files differ
diff --git a/share/images/settings.png b/share/images/settings.png
index 4c69de07..ec35400a 100644
--- a/share/images/settings.png
+++ b/share/images/settings.png
Binary files differ
diff --git a/share/images/download_completed.png b/share/images/share_completed.png
index e68fe5a2..e68fe5a2 100644
--- a/share/images/download_completed.png
+++ b/share/images/share_completed.png
Binary files differ
diff --git a/share/images/download_completed_none.png b/share/images/share_completed_none.png
index 8dbd6939..8dbd6939 100644
--- a/share/images/download_completed_none.png
+++ b/share/images/share_completed_none.png
Binary files differ
diff --git a/share/images/download_in_progress.png b/share/images/share_in_progress.png
index 19694659..19694659 100644
--- a/share/images/download_in_progress.png
+++ b/share/images/share_in_progress.png
Binary files differ
diff --git a/share/images/download_in_progress_none.png b/share/images/share_in_progress_none.png
index 2d61dba4..2d61dba4 100644
--- a/share/images/download_in_progress_none.png
+++ b/share/images/share_in_progress_none.png
Binary files differ
diff --git a/share/images/uploads.png b/share/images/uploads.png
new file mode 100644
index 00000000..cd9bd98e
--- /dev/null
+++ b/share/images/uploads.png
Binary files differ
diff --git a/share/images/uploads_toggle.png b/share/images/uploads_toggle.png
new file mode 100644
index 00000000..87303c9f
--- /dev/null
+++ b/share/images/uploads_toggle.png
Binary files differ
diff --git a/share/images/uploads_toggle_selected.png b/share/images/uploads_toggle_selected.png
new file mode 100644
index 00000000..0ba52cff
--- /dev/null
+++ b/share/images/uploads_toggle_selected.png
Binary files differ
diff --git a/share/images/uploads_transparent.png b/share/images/uploads_transparent.png
new file mode 100644
index 00000000..3648c3fb
--- /dev/null
+++ b/share/images/uploads_transparent.png
Binary files differ
diff --git a/share/locale/cs.json b/share/locale/cs.json
index 53525ea3..a595ce67 100644
--- a/share/locale/cs.json
+++ b/share/locale/cs.json
@@ -1,23 +1,15 @@
{
"config_onion_service": "Nastavuji onion service na portu {0:d}.",
"preparing_files": "Připravuji soubory ke sdílení.",
- "wait_for_hs": "Čekám na HS až bude připravena:",
- "wait_for_hs_trying": "Zkouším...",
- "wait_for_hs_nope": "Ještě nepřipraven.",
- "wait_for_hs_yup": "Připraven!",
"give_this_url": "Dejte tuto URL osobě, které dané soubory posíláte:",
"give_this_url_stealth": "Give this URL and HidServAuth line to the person you're sending the file to:",
"ctrlc_to_stop": "Stiskněte Ctrl-C pro zastavení serveru",
"not_a_file": "{0:s} není soubor.",
- "download_page_loaded": "Download page loaded",
"other_page_loaded": "URL loaded",
"closing_automatically": "Zastavuji automaticky, protože stahování skončilo",
"large_filesize": "Varování: Posílání velkých souborů může trvat hodiny",
- "error_tails_invalid_port": "Nesprávná hodnota, port musí být celé číslo",
- "error_tails_unknown_root": "Neznámá chyba s Tails root procesem",
"help_local_only": "Nepoužívat Tor: jen pro vývoj",
"help_stay_open": "Nechat běžet onion service po skončení stahování",
- "help_transparent_torification": "My system is transparently torified",
"help_stealth": "Create stealth onion service (advanced)",
"help_debug": "Zaznamenat chyby na disk",
"help_filename": "Seznam souborů a složek ke sdílení",
@@ -25,34 +17,26 @@
"gui_add": "Přidat",
"gui_delete": "Smazat",
"gui_choose_items": "Vybrat",
- "gui_start_server": "Spustit sdílení",
- "gui_stop_server": "Zastavit sdílení",
+ "gui_share_start_server": "Spustit sdílení",
+ "gui_share_stop_server": "Zastavit sdílení",
"gui_copy_url": "Kopírovat URL",
"gui_copy_hidservauth": "Kopírovat HidServAuth",
"gui_downloads": "Stahování:",
"gui_canceled": "Zrušeno",
"gui_copied_url": "URL zkopírováno do schránky",
"gui_copied_hidservauth": "Copied HidServAuth line to clipboard",
- "gui_starting_server1": "Spouštím Tor onion service...",
- "gui_starting_server2": "Zpracovávám soubory...",
"gui_please_wait": "Prosím čekejte...",
- "error_hs_dir_cannot_create": "Nejde vytvořit složka onion service {0:s}",
- "error_hs_dir_not_writable": "nejde zapisovat do složky onion service {0:s}",
- "using_ephemeral": "Starting ephemeral Tor onion service and awaiting publication",
- "gui_download_progress_complete": "%p%, Uplynulý čas: {0:s}",
- "gui_download_progress_starting": "{0:s}, %p% (Computing ETA)",
- "gui_download_progress_eta": "{0:s}, ETA: {1:s}, %p%",
+ "gui_download_upload_progress_complete": "%p%, Uplynulý čas: {0:s}",
+ "gui_download_upload_progress_starting": "{0:s}, %p% (Computing ETA)",
+ "gui_download_upload_progress_eta": "{0:s}, ETA: {1:s}, %p%",
"version_string": "Onionshare {0:s} | https://onionshare.org/",
- "gui_quit_warning": "Jste si jistí, že chcete odejít?\nURL, kterou sdílíte poté nebude existovat.",
+ "gui_share_quit_warning": "Jste si jistí, že chcete odejít?\nURL, kterou sdílíte poté nebude existovat.",
"gui_quit_warning_quit": "Zavřít",
"gui_quit_warning_dont_quit": "Zůstat",
"error_rate_limit": "Útočník možná zkouší uhodnout vaši URL. Abychom tomu předešli, OnionShare automaticky zastavil server. Pro sdílení souborů ho musíte spustit znovu a sdílet novou URL.",
"zip_progress_bar_format": "Zpracovávám soubory: %p%",
"error_stealth_not_supported": "To create stealth onion services, you need at least Tor 0.2.9.1-alpha (or Tor Browser 6.5) and at least python3-stem 1.5.0.",
"error_ephemeral_not_supported": "OnionShare vyžaduje nejméně Tor 0.2.7.1 a nejméně python3-stem 1.4.0.",
- "gui_menu_file_menu": "&File",
- "gui_menu_settings_action": "&Settings",
- "gui_menu_quit_action": "&Quit",
"gui_settings_window_title": "Nastavení",
"gui_settings_connection_type_label": "Jak by se měl OnionShare připojit k Toru?",
"gui_settings_connection_type_automatic_option": "Zkusit automatické nastavení s Tor Browserem",
@@ -63,10 +47,7 @@
"gui_settings_authenticate_label": "Autentizační možnosti Toru",
"gui_settings_authenticate_no_auth_option": "Žádná autentizace ani cookie autentizace",
"gui_settings_authenticate_password_option": "Heslo",
- "gui_settings_authenticate_cookie_option": "Cookie",
"gui_settings_password_label": "Heslo",
- "gui_settings_cookie_label": "Cesta ke cookie",
- "gui_settings_button_test": "Test Settings",
"gui_settings_button_save": "Uložit",
"gui_settings_button_cancel": "Zrušit",
"settings_saved": "Nastavení uloženo do {}",
diff --git a/share/locale/da.json b/share/locale/da.json
index 2c8d0c78..d414695b 100644
--- a/share/locale/da.json
+++ b/share/locale/da.json
@@ -1,24 +1,17 @@
{
"config_onion_service": "Konfigurerer onion-tjeneste på port {0:d}.",
"preparing_files": "Forbereder filer som skal deles.",
- "wait_for_hs": "Venter på at HS bliver klar:",
- "wait_for_hs_trying": "Prøver...",
- "wait_for_hs_nope": "Endnu ikke klar.",
- "wait_for_hs_yup": "Klar!",
"give_this_url": "Giv denne URL til personen du sender filen til:",
"give_this_url_stealth": "Giv denne URL og HidServAuth-linje til personen du sender filen til:",
"ctrlc_to_stop": "Tryk på Ctrl-C for at stoppe serveren",
"not_a_file": "{0:s} er ikke en gyldig fil.",
"not_a_readable_file": "{0:s} er ikke en læsbar fil.",
"no_available_port": "Kunne ikke starte onion-tjenesten da der ikke var nogen tilgængelig port.",
- "download_page_loaded": "Downloadside indlæst",
"other_page_loaded": "URL indlæst",
"close_on_timeout": "Lukker automatisk da timeout er nået",
"closing_automatically": "Lukker automatisk da download er færdig",
"timeout_download_still_running": "Venter på at download skal blive færdig inden automatisk stop",
"large_filesize": "Advarsel: Det kan tage timer at sende store filer",
- "error_tails_invalid_port": "Ugyldig værdi, port skal være et heltal",
- "error_tails_unknown_root": "Ukendt fejl med Tails-rodproces",
"systray_menu_exit": "Afslut",
"systray_download_started_title": "OnionShare-download startet",
"systray_download_started_message": "En bruger startede download af dine filer",
@@ -29,7 +22,6 @@
"help_local_only": "Undlad at bruge tor: kun til udvikling",
"help_stay_open": "Hold onion-tjeneste kørende efter download er færdig",
"help_shutdown_timeout": "Luk onion-tjenesten efter N sekunder",
- "help_transparent_torification": "Mit system er gennemsigtigt torifiseret",
"help_stealth": "Opret usynlig onion-tjeneste (avanceret)",
"help_debug": "Log programfejl til stdout, og log webfejl til disk",
"help_filename": "Liste over filer eller mapper som skal deles",
@@ -38,25 +30,20 @@
"gui_add": "Tilføj",
"gui_delete": "Slet",
"gui_choose_items": "Vælg",
- "gui_start_server": "Start deling",
- "gui_stop_server": "Stop deling",
+ "gui_share_start_server": "Start deling",
+ "gui_share_stop_server": "Stop deling",
"gui_copy_url": "Kopiér URL",
"gui_copy_hidservauth": "Kopiér HidServAuth",
"gui_downloads": "Downloads:",
"gui_canceled": "Annulleret",
"gui_copied_url": "Kopierede URL til udklipsholder",
"gui_copied_hidservauth": "Kopierede HidServAuth-linje til udklipsholder",
- "gui_starting_server1": "Starter Tor onion-tjeneste...",
- "gui_starting_server2": "Databehandler filer...",
"gui_please_wait": "Vent venligst...",
- "error_hs_dir_cannot_create": "Kan ikke oprette onion-tjenestens mappe {0:s}",
- "error_hs_dir_not_writable": "onion-tjenestens mappe {0:s} er skrivebeskyttet",
- "using_ephemeral": "Starter kortvarig Tor onion-tjeneste og afventer udgivelse",
- "gui_download_progress_complete": "%p%, tid forløbet: {0:s}",
- "gui_download_progress_starting": "{0:s}, %p% (udregner anslået ankomsttid)",
- "gui_download_progress_eta": "{0:s}, anslået ankomsttid: {1:s}, %p%",
+ "gui_download_upload_progress_complete": "%p%, tid forløbet: {0:s}",
+ "gui_download_upload_progress_starting": "{0:s}, %p% (udregner anslået ankomsttid)",
+ "gui_download_upload_progress_eta": "{0:s}, anslået ankomsttid: {1:s}, %p%",
"version_string": "Onionshare {0:s} | https://onionshare.org/",
- "gui_quit_warning": "Er du sikker på, at du vil afslutte?\nURL'en som du deler vil ikke eksistere længere.",
+ "gui_share_quit_warning": "Er du sikker på, at du vil afslutte?\nURL'en som du deler vil ikke eksistere længere.",
"gui_quit_warning_quit": "Afslut",
"gui_quit_warning_dont_quit": "Afslut ikke",
"error_rate_limit": "En angriber forsøger måske at gætte din URL. For at forhindre det, har OnionShare automatisk stoppet serveren. For at dele filerne skal du starte den igen og dele den nye URL.",
@@ -64,9 +51,7 @@
"error_stealth_not_supported": "For at oprette usynlige onion-tjenester, skal du mindst have Tor 0.2.9.1-alpha (eller Tor Browser 6.5) og mindst python3-stem 1.5.0.",
"error_ephemeral_not_supported": "OnionShare kræver mindst Tor 0.2.7.1 og mindst python3-stem 1.4.0.",
"gui_settings_window_title": "Indstillinger",
- "gui_settings_stealth_label": "Usynlig (avanceret)",
"gui_settings_stealth_option": "Opret usynlige onion-tjenester",
- "gui_settings_stealth_option_details": "Det gør OnionShare mere sikker, men også mere besværlig for modtageren at oprette forbindelse til den.<br><a href=\"https://github.com/micahflee/onionshare/wiki/Stealth-Onion-Services\">Mere information</a>.",
"gui_settings_stealth_hidservauth_string": "Du har gemt den private nøgle til at blive brugt igen, så din HidServAuth-streng bruges også igen.\nKlik nedenfor, for at kopiere HidServAuth.",
"gui_settings_autoupdate_label": "Søg efter opdateringer",
"gui_settings_autoupdate_option": "Giv mig besked når der findes opdateringer",
@@ -75,7 +60,6 @@
"gui_settings_autoupdate_check_button": "Søg efter opdateringer",
"gui_settings_sharing_label": "Valgmuligheder for deling",
"gui_settings_close_after_first_download_option": "Stop deling efter første download",
- "gui_settings_systray_notifications": "Vis skrivebordsnotifikationer",
"gui_settings_connection_type_label": "Hvordan skal OnionShare oprette forbindelse til Tor?",
"gui_settings_connection_type_bundled_option": "Brug Tor som er bundet med OnionShare",
"gui_settings_connection_type_automatic_option": "Prøv automatisk konfiguration med Tor Browser",
@@ -88,9 +72,7 @@
"gui_settings_authenticate_label": "Valgmuligheder for Tor-autentifikation",
"gui_settings_authenticate_no_auth_option": "Ingen autentifikation, eller cookieautentifikation",
"gui_settings_authenticate_password_option": "Adgangskode",
- "gui_settings_authenticate_cookie_option": "Cookie",
"gui_settings_password_label": "Adgangskode",
- "gui_settings_cookie_label": "Cookiesti",
"gui_settings_tor_bridges": "Understøttelse af Tor-bro",
"gui_settings_tor_bridges_no_bridges_radio_option": "Brug ikke broer",
"gui_settings_tor_bridges_obfs4_radio_option": "Brug indbygget obfs4 udskiftelige transporter",
@@ -101,7 +83,6 @@
"gui_settings_button_save": "Gem",
"gui_settings_button_cancel": "Annuller",
"gui_settings_button_help": "Hjælp",
- "gui_settings_shutdown_timeout_choice": "Sæt timer til automatisk stop?",
"gui_settings_shutdown_timeout": "Stop delingen ved:",
"settings_saved": "Indstillinger gemt til {}",
"settings_error_unknown": "Kan ikke oprette forbindelse til Tor-kontroller da indstillingerne ikke giver mening.",
@@ -113,7 +94,6 @@
"settings_error_unreadable_cookie_file": "Forbundet til Tor-kontroller, men kan ikke autentificere da din adgangskode kan være forkert, og din bruger ikke har tilladelse til at læse cookiefilen.",
"settings_error_bundled_tor_not_supported": "Bundet Tor understøttes ikke når der ikke bruges udviklertilstand i Windows eller MacOS.",
"settings_error_bundled_tor_timeout": "Det tager for længe at oprette forbindelse til Tor. Din computer er måske offline, eller dit ur går forkert.",
- "settings_error_bundled_tor_canceled": "Tor-processen lukkede inden den blev færdig med at oprette forbindelse.",
"settings_error_bundled_tor_broken": "Der er noget galt med OnionShare som opretter forbindelse til Tor i baggrunden:\n{}",
"settings_test_success": "Tillykke, OnionShare kan oprette forbindelse til Tor-kontrolleren.\n\nTor version: {}\nUnderstøtter kortvarige onion-tjenester: {}\nUnderstøtter usynlige onion-tjenester: {}",
"error_tor_protocol_error": "Fejl under snak med Tor-kontrolleren.\nHvis du bruger Whonix, så tjek https://www.whonix.org/wiki/onionshare for at få OnionShare til at virke.",
@@ -131,6 +111,5 @@
"gui_server_started_after_timeout": "Serveren startede efter dit valgte automatiske timeout.\nStart venligst en ny deling.",
"gui_server_timeout_expired": "Den valgte timeout er allerede udløbet.\nOpdater venligst timeouten og herefter kan du starte deling.",
"share_via_onionshare": "Del via OnionShare",
- "gui_save_private_key_checkbox": "Brug en vedvarende URL\n(fravalg vil slette gemte URL)",
- "persistent_url_in_use": "Denne deling bruger en vedvarende URL"
+ "gui_save_private_key_checkbox": "Brug en vedvarende URL\n(fravalg vil slette gemte URL)"
}
diff --git a/share/locale/de.json b/share/locale/de.json
index 7347e031..1d0436a0 100644
--- a/share/locale/de.json
+++ b/share/locale/de.json
@@ -1,22 +1,11 @@
{
- "connecting_ctrlport": "Verbinde zum Tor-Kontrollport um den versteckten Dienst auf Port {0:d} laufen zu lassen.",
- "cant_connect_ctrlport": "Konnte keine Verbindung zum Tor-Kontrollport auf Port {0:s} aufbauen. Läuft Tor?",
- "cant_connect_socksport": "Konnte keine Verbindung zum Tor SOCKS5 Server auf Port {0:s} herstellen. OnionShare setzt voraus dass Tor Browser im Hintergrund läuft. Wenn du noch ihn noch noch nicht hast kannst du ihn unter https://www.torproject.org/ herunterladen.",
"preparing_files": "Dateien werden vorbereitet.",
- "wait_for_hs": "Warte auf HS:",
- "wait_for_hs_trying": "Verbindungsversuch...",
- "wait_for_hs_nope": "Noch nicht bereit.",
- "wait_for_hs_yup": "Bereit!",
"give_this_url": "Geben Sie diese URL der Person, der Sie die Datei zusenden möchten:",
"ctrlc_to_stop": "Drücken Sie Strg+C um den Server anzuhalten",
"not_a_file": "{0:s} ist keine Datei.",
- "download_page_loaded": "Seite geladen",
"other_page_loaded": "URL geladen",
"closing_automatically": "Halte automatisch an, da der Download beendet wurde",
"large_filesize": "Warnung: Das Senden von großen Dateien kann Stunden dauern",
- "error_tails_invalid_port": "Ungültiger Wert, Port muss eine ganze Zahl sein",
- "error_tails_unknown_root": "Unbekannter Fehler mit Tails root Prozess",
- "help_tails_port": "Nur für Tails: Port um den Firewall zu öffnen, starte onion service",
"help_local_only": "Nicht mit Tor benutzen, nur für Entwicklung",
"help_stay_open": "Den onion service nicht anhalten nachdem ein Download beendet wurde",
"help_debug": "Fehler auf Festplatte schreiben",
@@ -25,8 +14,8 @@
"gui_add": "Hinzufügen",
"gui_delete": "Löschen",
"gui_choose_items": "Auswählen",
- "gui_start_server": "Server starten",
- "gui_stop_server": "Server anhalten",
+ "gui_share_start_server": "Server starten",
+ "gui_share_stop_server": "Server anhalten",
"gui_copy_url": "URL kopieren",
"gui_downloads": "Downloads:",
"gui_copied_url": "URL wurde in die Zwischenablage kopiert",
diff --git a/share/locale/en.json b/share/locale/en.json
index 09ead591..7fb30df8 100644
--- a/share/locale/en.json
+++ b/share/locale/en.json
@@ -1,24 +1,20 @@
{
- "config_onion_service": "Configuring onion service on port {0:d}.",
- "preparing_files": "Preparing files to share.",
- "wait_for_hs": "Waiting for HS to be ready:",
- "wait_for_hs_trying": "Trying...",
- "wait_for_hs_nope": "Not ready yet.",
- "wait_for_hs_yup": "Ready!",
- "give_this_url": "Give this address to the person you're sending the file to:",
- "give_this_url_stealth": "Give this address and HidServAuth line to the person you're sending the file to:",
- "ctrlc_to_stop": "Press Ctrl-C to stop server",
+ "config_onion_service": "Setting up onion service on port {0:d}.",
+ "preparing_files": "Compressing files.",
+ "give_this_url": "Give this address to the recipient:",
+ "give_this_url_stealth": "Give this address and HidServAuth line to the recipient:",
+ "give_this_url_receive": "Give this address to the sender:",
+ "give_this_url_receive_stealth": "Give this address and HidServAuth to the sender:",
+ "ctrlc_to_stop": "Press Ctrl+C to stop the server",
"not_a_file": "{0:s} is not a valid file.",
"not_a_readable_file": "{0:s} is not a readable file.",
- "no_available_port": "Could not start the Onion service as there was no available port.",
- "download_page_loaded": "Download page loaded",
+ "no_available_port": "Could not find an available port to start the onion service",
"other_page_loaded": "Address loaded",
- "close_on_timeout": "Stopped because timer expired",
+ "close_on_timeout": "Stopped because auto-stop timer ran out",
"closing_automatically": "Stopped because download finished",
"timeout_download_still_running": "Waiting for download to complete",
- "large_filesize": "Warning: Sending large files could take hours",
- "error_tails_invalid_port": "Invalid value, port must be an integer",
- "error_tails_unknown_root": "Unknown error with Tails root process",
+ "timeout_upload_still_running": "Waiting for upload to complete",
+ "large_filesize": "Warning: Sending a large share could take hours",
"systray_menu_exit": "Quit",
"systray_download_started_title": "OnionShare Download Started",
"systray_download_started_message": "A user started downloading your files",
@@ -26,131 +22,164 @@
"systray_download_completed_message": "The user finished downloading your files",
"systray_download_canceled_title": "OnionShare Download Canceled",
"systray_download_canceled_message": "The user canceled the download",
- "help_local_only": "Do not attempt to use tor: for development only",
- "help_stay_open": "Keep onion service running after download has finished",
- "help_shutdown_timeout": "Shut down the onion service after N seconds",
- "help_transparent_torification": "My system is transparently torified",
- "help_stealth": "Create stealth onion service (advanced)",
- "help_debug": "Log application errors to stdout, and log web errors to disk",
+ "systray_upload_started_title": "OnionShare Upload Started",
+ "systray_upload_started_message": "A user started uploading files to your computer",
+ "help_local_only": "Don't use Tor (only for development)",
+ "help_stay_open": "Keep sharing after first download",
+ "help_shutdown_timeout": "Stop sharing after a given amount of seconds",
+ "help_stealth": "Use client authorization (advanced)",
+ "help_receive": "Receive shares instead of sending them",
+ "help_debug": "Log OnionShare errors to stdout, and web errors to disk",
"help_filename": "List of files or folders to share",
- "help_config": "Path to a custom JSON config file (optional)",
+ "help_config": "Custom JSON config file location (optional)",
"gui_drag_and_drop": "Drag and drop files and folders\nto start sharing",
"gui_add": "Add",
"gui_delete": "Delete",
"gui_choose_items": "Choose",
- "gui_start_server": "Start Sharing",
- "gui_stop_server": "Stop Sharing",
- "gui_stop_server_shutdown_timeout": "Stop Sharing ({}s remaining)",
- "gui_stop_server_shutdown_timeout_tooltip": "Share will stop automatically at {}",
+ "gui_share_start_server": "Start sharing",
+ "gui_share_stop_server": "Stop sharing",
+ "gui_share_stop_server_shutdown_timeout": "Stop Sharing ({}s remaining)",
+ "gui_share_stop_server_shutdown_timeout_tooltip": "Auto-stop timer ends at {}",
+ "gui_receive_start_server": "Start Receive Mode",
+ "gui_receive_stop_server": "Stop Receive Mode",
+ "gui_receive_stop_server_shutdown_timeout": "Stop Receive Mode ({}s remaining)",
+ "gui_receive_stop_server_shutdown_timeout_tooltip": "Auto-stop timer ends at {}",
"gui_copy_url": "Copy Address",
"gui_copy_hidservauth": "Copy HidServAuth",
- "gui_downloads": "Downloads:",
+ "gui_downloads": "Download History",
+ "gui_no_downloads": "No Downloads Yet",
"gui_canceled": "Canceled",
- "gui_copied_url_title": "Copied OnionShare address",
- "gui_copied_url": "The OnionShare address has been copied to clipboard",
+ "gui_copied_url_title": "Copied OnionShare Address",
+ "gui_copied_url": "OnionShare address copied to clipboard",
"gui_copied_hidservauth_title": "Copied HidServAuth",
- "gui_copied_hidservauth": "The HidServAuth line has been copied to clipboard",
- "gui_starting_server1": "Starting Tor onion service...",
- "gui_starting_server2": "Crunching files...",
- "gui_please_wait": "Starting... Click to cancel",
- "error_hs_dir_cannot_create": "Cannot create onion service dir {0:s}",
- "error_hs_dir_not_writable": "onion service dir {0:s} is not writable",
- "using_ephemeral": "Starting ephemeral Tor onion service and awaiting publication",
- "gui_download_progress_complete": "%p%, Time Elapsed: {0:s}",
- "gui_download_progress_starting": "{0:s}, %p% (Computing ETA)",
- "gui_download_progress_eta": "{0:s}, ETA: {1:s}, %p%",
- "version_string": "Onionshare {0:s} | https://onionshare.org/",
- "gui_quit_title": "Transfer in Progress",
- "gui_quit_warning": "You're in the process of sending files. Are you sure you want to quit OnionShare?",
+ "gui_copied_hidservauth": "HidServAuth line copied to clipboard",
+ "gui_please_wait": "Starting… Click to cancel.",
+ "gui_download_upload_progress_complete": "%p%, {0:s} elapsed.",
+ "gui_download_upload_progress_starting": "{0:s}, %p% (calculating)",
+ "gui_download_upload_progress_eta": "{0:s}, ETA: {1:s}, %p%",
+ "version_string": "OnionShare {0:s} | https://onionshare.org/",
+ "gui_quit_title": "Not so fast",
+ "gui_share_quit_warning": "You're in the process of sending files. Are you sure you want to quit OnionShare?",
+ "gui_receive_quit_warning": "You're in the process of receiving files. Are you sure you want to quit OnionShare?",
"gui_quit_warning_quit": "Quit",
"gui_quit_warning_dont_quit": "Cancel",
- "error_rate_limit": "An attacker might be trying to guess your address. To prevent this, OnionShare has automatically stopped the server. To share the files you must start it again and share the new address.",
- "zip_progress_bar_format": "Crunching files: %p%",
- "error_stealth_not_supported": "To create stealth onion services, you need at least Tor 0.2.9.1-alpha (or Tor Browser 6.5) and at least python3-stem 1.5.0.",
- "error_ephemeral_not_supported": "OnionShare requires at least Tor 0.2.7.1 and at least python3-stem 1.4.0.",
+ "error_rate_limit": "Someone has made too many wrong attempts on your address, which means they could be trying to guess it, so OnionShare has stopped the server. Start sharing again and send the recipient a new address to share.",
+ "zip_progress_bar_format": "Compressing: %p%",
+ "error_stealth_not_supported": "To use client authorization, you need at least both Tor 0.2.9.1-alpha (or Tor Browser 6.5) and python3-stem 1.5.0.",
+ "error_ephemeral_not_supported": "OnionShare requires at least both Tor 0.2.7.1 and python3-stem 1.4.0.",
"gui_settings_window_title": "Settings",
- "gui_settings_stealth_label": "Stealth (advanced)",
- "gui_settings_stealth_option": "Create stealth onion services",
- "gui_settings_stealth_option_details": "This makes OnionShare more secure, but also more difficult for the recipient to connect to it.<br><a href=\"https://github.com/micahflee/onionshare/wiki/Stealth-Onion-Services\">More information</a>.",
- "gui_settings_stealth_hidservauth_string": "You have saved the private key for reuse, so your HidServAuth string is also reused.\nClick below to copy the HidServAuth.",
- "gui_settings_autoupdate_label": "Check for updates",
- "gui_settings_autoupdate_option": "Notify me when updates are available",
+ "gui_settings_whats_this": "<a href='{0:s}'>What's this?</a>",
+ "gui_settings_stealth_option": "Use client authorization (legacy)",
+ "gui_settings_stealth_hidservauth_string": "Having saved your private key for reuse, means you can now\nclick to copy your HidServAuth.",
+ "gui_settings_autoupdate_label": "Check for new version",
+ "gui_settings_autoupdate_option": "Notify me when a new version is available",
"gui_settings_autoupdate_timestamp": "Last checked: {}",
"gui_settings_autoupdate_timestamp_never": "Never",
- "gui_settings_autoupdate_check_button": "Check For Updates",
- "gui_settings_sharing_label": "Sharing options",
+ "gui_settings_autoupdate_check_button": "Check for New Version",
+ "gui_settings_general_label": "General settings",
+ "gui_settings_sharing_label": "Sharing settings",
"gui_settings_close_after_first_download_option": "Stop sharing after first download",
- "gui_settings_systray_notifications": "Show desktop notifications",
"gui_settings_connection_type_label": "How should OnionShare connect to Tor?",
- "gui_settings_connection_type_bundled_option": "Use Tor that is bundled with OnionShare",
- "gui_settings_connection_type_automatic_option": "Attempt automatic configuration with Tor Browser",
+ "gui_settings_connection_type_bundled_option": "Use the Tor version built into OnionShare",
+ "gui_settings_connection_type_automatic_option": "Attempt auto-configuration with Tor Browser",
"gui_settings_connection_type_control_port_option": "Connect using control port",
"gui_settings_connection_type_socket_file_option": "Connect using socket file",
- "gui_settings_connection_type_test_button": "Test Tor Settings",
+ "gui_settings_connection_type_test_button": "Test Connection to Tor",
"gui_settings_control_port_label": "Control port",
"gui_settings_socket_file_label": "Socket file",
"gui_settings_socks_label": "SOCKS port",
- "gui_settings_authenticate_label": "Tor authentication options",
+ "gui_settings_authenticate_label": "Tor authentication settings",
"gui_settings_authenticate_no_auth_option": "No authentication, or cookie authentication",
"gui_settings_authenticate_password_option": "Password",
- "gui_settings_authenticate_cookie_option": "Cookie",
"gui_settings_password_label": "Password",
- "gui_settings_cookie_label": "Cookie path",
- "gui_settings_tor_bridges": "Tor Bridge support",
+ "gui_settings_tor_bridges": "Tor bridge support",
"gui_settings_tor_bridges_no_bridges_radio_option": "Don't use bridges",
"gui_settings_tor_bridges_obfs4_radio_option": "Use built-in obfs4 pluggable transports",
"gui_settings_tor_bridges_obfs4_radio_option_no_obfs4proxy": "Use built-in obfs4 pluggable transports (requires obfs4proxy)",
- "gui_settings_tor_bridges_meek_lite_amazon_radio_option": "Use built-in meek_lite (Amazon) pluggable transports",
- "gui_settings_tor_bridges_meek_lite_amazon_radio_option_no_obfs4proxy": "Use built-in meek_lite (Amazon) pluggable transports (requires obfs4proxy)",
"gui_settings_tor_bridges_meek_lite_azure_radio_option": "Use built-in meek_lite (Azure) pluggable transports",
"gui_settings_tor_bridges_meek_lite_azure_radio_option_no_obfs4proxy": "Use built-in meek_lite (Azure) pluggable transports (requires obfs4proxy)",
+ "gui_settings_meek_lite_expensive_warning": "Warning: The meek_lite bridges are very costly for the Tor Project to run.<br><br>Only use them if unable to connect to Tor directly, via obfs4 transports, or other normal bridges.",
"gui_settings_tor_bridges_custom_radio_option": "Use custom bridges",
"gui_settings_tor_bridges_custom_label": "You can get bridges from <a href=\"https://bridges.torproject.org/options\">https://bridges.torproject.org</a>",
- "gui_settings_tor_bridges_invalid": "None of the bridges you supplied seem to be valid.\nPlease try again with valid bridges.",
+ "gui_settings_tor_bridges_invalid": "None of the bridges you added work.\nDouble-check them or add others.",
"gui_settings_button_save": "Save",
"gui_settings_button_cancel": "Cancel",
"gui_settings_button_help": "Help",
"gui_settings_shutdown_timeout_checkbox": "Use auto-stop timer",
"gui_settings_shutdown_timeout": "Stop the share at:",
- "settings_saved": "Settings saved to {}",
- "settings_error_unknown": "Can't connect to Tor controller because the settings don't make sense.",
- "settings_error_automatic": "Can't connect to Tor controller. Is Tor Browser running in the background? If you don't have it you can get it from:\nhttps://www.torproject.org/.",
- "settings_error_socket_port": "Can't connect to Tor controller on {}:{}.",
- "settings_error_socket_file": "Can't connect to Tor controller using socket file {}.",
+ "settings_error_unknown": "Can't connect to Tor controller because your settings don't make sense.",
+ "settings_error_automatic": "Could not connect to the Tor controller. Is Tor Browser (available from torproject.org) running in the background?",
+ "settings_error_socket_port": "Can't connect to the Tor controller at {}:{}.",
+ "settings_error_socket_file": "Can't connect to the Tor controller using socket file {}.",
"settings_error_auth": "Connected to {}:{}, but can't authenticate. Maybe this isn't a Tor controller?",
"settings_error_missing_password": "Connected to Tor controller, but it requires a password to authenticate.",
- "settings_error_unreadable_cookie_file": "Connected to Tor controller, but can't authenticate because your password may be wrong, and your user doesn't have permission to read the cookie file.",
- "settings_error_bundled_tor_not_supported": "Bundled Tor is not supported when not using developer mode in Windows or macOS.",
- "settings_error_bundled_tor_timeout": "Connecting to Tor is taking too long. Maybe your computer is offline, or your clock isn't accurate.",
- "settings_error_bundled_tor_canceled": "The Tor process closed before it could finish connecting.",
- "settings_error_bundled_tor_broken": "Something is wrong with OnionShare connecting to Tor in the background:\n{}",
- "settings_test_success": "Congratulations, OnionShare can connect to the Tor controller.\n\nTor version: {}\nSupports ephemeral onion services: {}\nSupports stealth onion services: {}",
- "error_tor_protocol_error": "Error talking to the Tor controller.\nIf you're using Whonix, check out https://www.whonix.org/wiki/onionshare to make OnionShare work.",
+ "settings_error_unreadable_cookie_file": "Connected to the Tor controller, but password may be wrong, or your user is not permitted to read the cookie file.",
+ "settings_error_bundled_tor_not_supported": "Using the Tor version that comes with OnionShare does not work in developer mode on Windows or macOS.",
+ "settings_error_bundled_tor_timeout": "Taking too long to connect to Tor. Maybe you aren't connected to the Internet, or have an inaccurate system clock?",
+ "settings_error_bundled_tor_broken": "OnionShare could not connect to Tor in the background:\n{}",
+ "settings_test_success": "Connected to the Tor controller.\n\nTor version: {}\nSupports ephemeral onion services: {}.\nSupports client authentication: {}.\nSupports next-gen .onion addresses: {}.",
+ "error_tor_protocol_error": "There was an error with Tor: {}",
+ "error_tor_protocol_error_unknown": "There was an unknown error with Tor",
+ "error_invalid_private_key": "This private key type is unsupported",
"connecting_to_tor": "Connecting to the Tor network",
- "update_available": "There is an OnionShare update available. <a href='{}'>Click here</a> to download it.<br><br>Installed version: {}<br>Latest version: {}",
- "update_error_check_error": "Error checking for updates: Maybe you're not connected to Tor, or maybe the OnionShare website is down.",
- "update_error_invalid_latest_version": "Error checking for updates: The OnionShare website responded saying the latest version is '{}', but that doesn't appear to be a valid version string.",
- "update_not_available": "You are running the latest version of OnionShare.",
- "gui_tor_connection_ask": "Would you like to open OnionShare settings to troubleshoot connecting to Tor?",
- "gui_tor_connection_ask_open_settings": "Open Settings",
+ "update_available": "New OnionShare out. <a href='{}'>Click here</a> to get it.<br><br>You are using {} and the latest is {}.",
+ "update_error_check_error": "Could not check for new versions: The OnionShare website is saying the latest version is the unrecognizable '{}'…",
+ "update_error_invalid_latest_version": "Could not check for new version: Maybe you're not connected to Tor, or the OnionShare website is down?",
+ "update_not_available": "You are running the latest OnionShare.",
+ "gui_tor_connection_ask": "Open the settings to sort out connection to Tor?",
+ "gui_tor_connection_ask_open_settings": "Yes",
"gui_tor_connection_ask_quit": "Quit",
- "gui_tor_connection_error_settings": "Try adjusting how OnionShare connects to the Tor network in Settings.",
- "gui_tor_connection_canceled": "OnionShare cannot connect to Tor.\n\nMake sure you're connected to the internet, then re-open OnionShare to configure the Tor connection.",
+ "gui_tor_connection_error_settings": "Try changing how OnionShare connects to the Tor network in the settings.",
+ "gui_tor_connection_canceled": "Could not connect to Tor.\n\nEnsure you are connected to the Internet, then re-open OnionShare and set up its connection to Tor.",
"gui_tor_connection_lost": "Disconnected from Tor.",
- "gui_server_started_after_timeout": "The server started after your chosen auto-timeout.\nPlease start a new share.",
- "gui_server_timeout_expired": "The chosen timeout has already expired.\nPlease update the timeout and then you may start sharing.",
- "share_via_onionshare": "Share via OnionShare",
- "gui_save_private_key_checkbox": "Use a persistent address\n(unchecking will delete any saved address)",
- "gui_url_description": "<b>Anyone</b> with this link can <b>download</b> your files using <b>Tor Browser</b>: <img src='{}' />",
- "gui_url_label_persistent": "This share will not stop automatically unless a timer is set.<br><br>Every share will have the same address (to use one-time addresses, disable persistence in the Settings)",
- "gui_url_label_stay_open": "This share will not stop automatically unless a timer is set.",
- "gui_url_label_onetime": "This share will stop after the first download",
- "gui_url_label_onetime_and_persistent": "This share will stop after the first download<br><br>Every share will have the same address (to use one-time addresses, disable persistence in the Settings)",
- "gui_status_indicator_stopped": "Ready to Share",
- "gui_status_indicator_working": "Starting...",
- "gui_status_indicator_started": "Sharing",
- "gui_file_info": "{} Files, {}",
- "gui_file_info_single": "{} File, {}",
- "info_in_progress_downloads_tooltip": "{} download(s) in progress",
- "info_completed_downloads_tooltip": "{} download(s) completed"
+ "gui_server_started_after_timeout": "The auto-stop timer ran out before the server started.\nPlease make a new share.",
+ "gui_server_timeout_expired": "The auto-stop timer already ran out.\nPlease update it to start sharing.",
+ "share_via_onionshare": "OnionShare it",
+ "gui_use_legacy_v2_onions_checkbox": "Use legacy addresses",
+ "gui_save_private_key_checkbox": "Use a persistent address (legacy)",
+ "gui_share_url_description": "<b>Anyone</b> with this OnionShare address can <b>download</b> your files using the <b>Tor Browser</b>: <img src='{}' />",
+ "gui_receive_url_description": "<b>Anyone</b> with this OnionShare address can <b>upload</b> files to your computer using the <b>Tor Browser</b>: <img src='{}' />",
+ "gui_url_label_persistent": "This share will not auto-stop.<br><br>Every subsequent share reuses the address. (To use one-time addresses, turn off \"Use persistent address\" in the settings.)",
+ "gui_url_label_stay_open": "This share will not auto-stop.",
+ "gui_url_label_onetime": "This share will stop after first completion.",
+ "gui_url_label_onetime_and_persistent": "This share will not auto-stop.<br><br>Every subsequent share will reuse the address. (To use one-time addresses, turn off \"Use persistent address\" in the settings.)",
+ "gui_status_indicator_share_stopped": "Ready to share",
+ "gui_status_indicator_share_working": "Starting…",
+ "gui_status_indicator_share_started": "Sharing",
+ "gui_status_indicator_receive_stopped": "Ready to receive",
+ "gui_status_indicator_receive_working": "Starting…",
+ "gui_status_indicator_receive_started": "Receiving",
+ "gui_file_info": "{} files, {}",
+ "gui_file_info_single": "{} file, {}",
+ "history_in_progress_tooltip": "{} in progress",
+ "history_completed_tooltip": "{} completed",
+ "info_in_progress_uploads_tooltip": "{} upload(s) in progress",
+ "info_completed_uploads_tooltip": "{} upload(s) completed",
+ "error_cannot_create_downloads_dir": "Could not create receive mode folder: {}",
+ "receive_mode_downloads_dir": "Files sent to you appear in this folder: {}",
+ "receive_mode_warning": "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing.",
+ "gui_receive_mode_warning": "Receive mode lets people upload files to your computer.<br><br><b>Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing.</b>",
+ "receive_mode_upload_starting": "Upload of total size {} is starting",
+ "receive_mode_received_file": "Received: {}",
+ "gui_mode_share_button": "Share Files",
+ "gui_mode_receive_button": "Receive Files",
+ "gui_settings_receiving_label": "Receiving settings",
+ "gui_settings_downloads_label": "Save files to",
+ "gui_settings_downloads_button": "Browse",
+ "gui_settings_public_mode_checkbox": "Public mode",
+ "systray_close_server_title": "OnionShare Server Closed",
+ "systray_close_server_message": "A user closed the server",
+ "systray_page_loaded_title": "OnionShare Page Loaded",
+ "systray_download_page_loaded_message": "A user loaded the download page",
+ "systray_upload_page_loaded_message": "A user loaded the upload page",
+ "gui_uploads": "Upload History",
+ "gui_no_uploads": "No Uploads Yet",
+ "gui_clear_history": "Clear All",
+ "gui_upload_in_progress": "Upload Started {}",
+ "gui_upload_finished_range": "Uploaded {} to {}",
+ "gui_upload_finished": "Uploaded {}",
+ "gui_download_in_progress": "Download Started {}",
+ "gui_open_folder_error_nautilus": "Cannot open folder because nautilus is not available. The file is here: {}",
+ "gui_settings_language_label": "Preferred language",
+ "gui_settings_language_changed_notice": "Restart OnionShare for your change in language to take effect."
}
diff --git a/share/locale/eo.json b/share/locale/eo.json
index 6d904dc0..9902e4ae 100644
--- a/share/locale/eo.json
+++ b/share/locale/eo.json
@@ -1,23 +1,15 @@
{
"config_onion_service": "Agordas onion service je pordo {0:d}.",
"preparing_files": "Preparas dosierojn por kundivido.",
- "wait_for_hs": "Atendas al hidden sevice por esti preta:",
- "wait_for_hs_trying": "Provas...",
- "wait_for_hs_nope": "Ankoraŭ ne preta.",
- "wait_for_hs_yup": "Preta!",
"give_this_url": "Donu ĉi tiun URL al la persono al kiu vi sendas la dosieron:",
"give_this_url_stealth": "Give this URL and HidServAuth line to the person you're sending the file to:",
"ctrlc_to_stop": "Presu Ctrl-C por halti la servilon",
"not_a_file": "{0:s} ne estas dosiero.",
- "download_page_loaded": "Download page loaded",
"other_page_loaded": "URL loaded",
"closing_automatically": "Haltas aŭtomate ĉar la elŝuto finiĝis",
"large_filesize": "Atentigo: Sendado de grandaj dosieroj povas daŭri horojn",
- "error_tails_invalid_port": "Malĝusta valoro, pordo-numero devas esti plena numero",
- "error_tails_unknown_root": "Nekonata eraro kun Tails-root-procezo",
"help_local_only": "Ne strebu uzi tor: nur por evoluado",
"help_stay_open": "Lasu onion service funkcii post fino de elŝuto",
- "help_transparent_torification": "My system is transparently torified",
"help_stealth": "Create stealth onion service (advanced)",
"help_debug": "Protokoli erarojn sur disko",
"help_filename": "Listo de dosieroj aŭ dosierujoj por kundividi",
@@ -25,34 +17,26 @@
"gui_add": "Aldoni",
"gui_delete": "Forviŝi",
"gui_choose_items": "Elekti",
- "gui_start_server": "Komenci kundividon",
- "gui_stop_server": "Ĉesigi kundividon",
+ "gui_share_start_server": "Komenci kundividon",
+ "gui_share_stop_server": "Ĉesigi kundividon",
"gui_copy_url": "Kopii URL",
"gui_copy_hidservauth": "Kopii HidServAuth",
"gui_downloads": "Elŝutoj:",
"gui_canceled": "Nuligita",
"gui_copied_url": "URL kopiita en tondujon",
"gui_copied_hidservauth": "Copied HidServAuth line to clipboard",
- "gui_starting_server1": "Startigas Tor onion service...",
- "gui_starting_server2": "Crunching files...",
"gui_please_wait": "Bonvolu atendi...",
- "error_hs_dir_cannot_create": "Ne eblas krei hidden-service-dosierujon {0:s}",
- "error_hs_dir_not_writable": "ne eblas konservi dosierojn en hidden-service-dosierujo {0:s}",
- "using_ephemeral": "Starting ephemeral Tor onion service and awaiting publication",
- "gui_download_progress_complete": "%p%, Tempo pasinta: {0:s}",
- "gui_download_progress_starting": "{0:s}, %p% (Computing ETA)",
- "gui_download_progress_eta": "{0:s}, ETA: {1:s}, %p%",
+ "gui_download_upload_progress_complete": "%p%, Tempo pasinta: {0:s}",
+ "gui_download_upload_progress_starting": "{0:s}, %p% (Computing ETA)",
+ "gui_download_upload_progress_eta": "{0:s}, ETA: {1:s}, %p%",
"version_string": "Onionshare {0:s} | https://onionshare.org/",
- "gui_quit_warning": "Ĉu vi certas ke vi volas foriri?\nLa URL, kiun vi kundividas ne plu ekzistos.",
+ "gui_share_quit_warning": "Ĉu vi certas ke vi volas foriri?\nLa URL, kiun vi kundividas ne plu ekzistos.",
"gui_quit_warning_quit": "Foriri",
"gui_quit_warning_dont_quit": "Ne foriri",
"error_rate_limit": "Iu atankanto povas provi diveni vian URL. Por eviti tion, OnionShare aŭtomate haltis la servilon. Por kundividi la dosierojn vi devas starti ĝin denove kaj kundividi la novan URL.",
- "zip_progress_bar_format": "Crunching files: %p%",
+ "zip_progress_bar_format": "Compressing files: %p%",
"error_stealth_not_supported": "To create stealth onion services, you need at least Tor 0.2.9.1-alpha (or Tor Browser 6.5) and at least python3-stem 1.5.0.",
"error_ephemeral_not_supported": "OnionShare postulas almenaŭ Tor 0.2.7.1 kaj almenaŭ python3-stem 1.4.0.",
- "gui_menu_file_menu": "&File",
- "gui_menu_settings_action": "&Settings",
- "gui_menu_quit_action": "&Quit",
"gui_settings_window_title": "Settings",
"gui_settings_connection_type_label": "Kiel OnionShare devus konektiĝi al Tor?",
"gui_settings_connection_type_automatic_option": "Provi aŭtomate agordi kun Tor Browser",
@@ -63,10 +47,7 @@
"gui_settings_authenticate_label": "Tor authentication options",
"gui_settings_authenticate_no_auth_option": "No authentication, or cookie authentication",
"gui_settings_authenticate_password_option": "Pasvorto",
- "gui_settings_authenticate_cookie_option": "Kuketo",
"gui_settings_password_label": "Pasvorto",
- "gui_settings_cookie_label": "Cookie path",
- "gui_settings_button_test": "Test Settings",
"gui_settings_button_save": "Konservi",
"gui_settings_button_cancel": "Nuligi",
"settings_saved": "Agordoj konservitaj en {}",
diff --git a/share/locale/es.json b/share/locale/es.json
index 5d9f8dcd..8c9945a8 100644
--- a/share/locale/es.json
+++ b/share/locale/es.json
@@ -1,21 +1,10 @@
{
- "connecting_ctrlport": "Conectando a puerto control de Tor para configurar servicio oculto en puerto {0:d}.",
- "cant_connect_ctrlport": "No se pudo conectar a puerto control de Tor en puertos {0:s}. ¿Está funcionando Tor?",
- "cant_connect_socksport": "No se pudo conectar al servidor SOCKS5 de Tor en el puerto {0:s}. ¿Está funcionando Tor?",
"preparing_files": "Preparando los archivos para compartir.",
- "wait_for_hs": "Esperando a que HS esté listo:",
- "wait_for_hs_trying": "Probando...",
- "wait_for_hs_nope": "No está listo todavía.",
- "wait_for_hs_yup": "Listo!",
"give_this_url": "Entregue esta URL a la persona a la que está enviando el archivo:",
"ctrlc_to_stop": "Pulse Ctrl-C para detener el servidor",
"not_a_file": "{0:s} no es un archivo.",
- "download_page_loaded": "La página de descarga está lista.",
"other_page_loaded": "La URL está lista.",
"closing_automatically": "Apagando automáticamente porque la descarga finalizó",
- "error_tails_invalid_port": "Valor inválido, el puerto debe ser un entero",
- "error_tails_unknown_root": "Error desconocido en el proceso de Tails ejecutando como roo",
- "help_tails_port": "Sólo Tails: puerto para abrir en el firewall, al levantar el servicio oculto",
"help_local_only": "No intentar usar Tor: sólo para desarrollo",
"help_stay_open": "Mantener el servicio oculto ejecutando después de que la descarga haya finalizado",
"help_debug": "Guardar registro de errores en el disco",
@@ -24,8 +13,8 @@
"gui_add": "Añadir",
"gui_delete": "Eliminar",
"gui_choose_items": "Elegir",
- "gui_start_server": "Encender el Servidor",
- "gui_stop_server": "Detener el Servidor",
+ "gui_share_start_server": "Encender el Servidor",
+ "gui_share_stop_server": "Detener el Servidor",
"gui_copy_url": "Copiar URL",
"gui_downloads": "Descargas:",
"gui_copied_url": "Se copió la URL en el portapapeles"
diff --git a/share/locale/fi.json b/share/locale/fi.json
index 25fda84b..d0ee80ff 100644
--- a/share/locale/fi.json
+++ b/share/locale/fi.json
@@ -1,43 +1,25 @@
{
- "connecting_ctrlport": "Yhdistetään Torin ohjausporttiin että saadaan salattu palvelin porttiin {0:d}.",
- "cant_connect_ctrlport": "Ei voi yhdistää Torin ohjausporttiin portissa {0:s}. OnionShare tarvitsee Tor Browserin toimimaan taustalla. Jos sinulla ei ole sitä niin voit hakea sen osoitteesta https://www.torproject.org/.",
- "cant_connect_socksport": "Ei voi yhdistää Tor SOCKS5 palveluun portissa {0:s}. OnionShare tarvitsee Tor Browserin toimimaan taustalla. Jos sinulla ei ole sitä niin voit hakea sen osoitteesta https://www.torproject.org/.",
"preparing_files": "Valmistellaan tiedostoja jaettavaksi.",
- "wait_for_hs": "Odotetaan piilopalvelun valmistumista:",
- "wait_for_hs_trying": "Yritetään...",
- "wait_for_hs_nope": "Ei vielä valmis.",
- "wait_for_hs_yup": "Valmis!",
"give_this_url": "Anna tämä URL-osoite henkilölle, jolle lähetät tiedostot:",
"ctrlc_to_stop": "Näppäin Ctrl-C pysäyttää palvelimen",
"not_a_file": "{0:s} Ei ole tiedosto.",
- "download_page_loaded": "Lataussivu ladattu",
"other_page_loaded": "URL-osoite ladattu",
"closing_automatically": "Lataus valmis. Suljetaan automaattisesti",
"large_filesize": "Varoitus: Isojen tiedostojen lähetys saattaa kestää tunteja",
- "error_tails_invalid_port": "Väärä arvo, portti pitää olla koknaisluku",
- "error_tails_unknown_root": "Tuntematon virhe Tailsissa",
- "help_tails_port": "Vain Tails: portti palomuurin läpi, käynnistetään salainen palvelin",
"help_local_only": "Älä käytä Toria: vain ohjelmakehitykseen",
"help_stay_open": "Pidä piilopalvelu käynnissä latauksen jälkeen.",
- "help_transparent_torification": "Järjestelmäni käyttää Toria läpinäkyvästi",
"help_debug": "Tallentaa virheet levylle",
"help_filename": "Luettele jaettavat tiedostot tai kansiot",
"gui_drag_and_drop": "Vedä ja pudota\ntiedostot tänne",
"gui_add": "Lisää",
"gui_delete": "Poista",
"gui_choose_items": "Valitse",
- "gui_start_server": "Käynnistä palvelin",
- "gui_stop_server": "Pysäytä palvelin",
+ "gui_share_start_server": "Käynnistä palvelin",
+ "gui_share_stop_server": "Pysäytä palvelin",
"gui_copy_url": "Kopioi URL-osoite",
"gui_downloads": "Lataukset:",
"gui_canceled": "Peruutettu",
"gui_copied_url": "URL-osoite kopioitu leikepöydälle",
- "gui_starting_server1": "Käynnistetään Tor piilopalvelu...",
- "gui_starting_server2": "Tiivistän tiedostoja...",
- "gui_starting_server3": "Odotetaan Tor piilopalvelua...",
"gui_please_wait": "Odota...",
- "error_hs_dir_cannot_create": "Piilopalvelulle ei pystytty luomaan hakemistoa {0:s}",
- "error_hs_dir_not_writable": "Piilopalvelun hakemistoon {0:s} ei voi kirjoittaa",
- "using_ephemeral": "Käynnistetään lyhytaikainen Tor piilopalvelu ja odotetaan julkaisua",
"zip_progress_bar_format": "Tiivistän tiedostoja: %p%"
}
diff --git a/share/locale/fr.json b/share/locale/fr.json
index a661cd26..ee206662 100644
--- a/share/locale/fr.json
+++ b/share/locale/fr.json
@@ -1,26 +1,16 @@
{
- "connecting_ctrlport": "Connexion au réseau Tor pour mettre en place un onion service sur le port {0:d}.",
- "cant_connect_ctrlport": "Impossible de se connecter au port de contrôle Tor sur le port {0:s}. Est-ce que Tor tourne ?",
"preparing_files": "Préparation des fichiers à partager.",
- "wait_for_hs": "En attente du HS:",
- "wait_for_hs_trying": "Tentative...",
- "wait_for_hs_nope": "Pas encore prêt.",
- "wait_for_hs_yup": "Prêt !",
"give_this_url": "Donnez cette URL à la personne qui doit recevoir le fichier :",
"ctrlc_to_stop": "Ctrl-C arrête le serveur",
"not_a_file": "{0:s} n'est pas un fichier.",
- "download_page_loaded": "Page de téléchargement chargée",
"other_page_loaded": "URL chargée",
"closing_automatically": "Fermeture automatique car le téléchargement est fini",
- "error_tails_invalid_port": "Valeur invalide, le port doit être un nombre entier",
- "error_tails_unknown_root": "Erreur inconnue avec un processus root sur Tails",
"systray_menu_exit": "Quitter",
"systray_download_started_title": "Téléchargement OnionShare Démarré",
"systray_download_started_message": "Un utilisateur télécharge vos fichiers",
"systray_download_completed_title": "Téléchargement OnionShare Complete",
"systray_download_canceled_title": "Téléchargement OnionShare Annulé",
"systray_download_canceled_message": "L'utilisateur a annulé le téléchargement",
- "help_tails_port": "Seulement sur Tails: port pour ouvrir le firewall, démarrage du onion service",
"help_local_only": "Ne tentez pas d'utiliser Tor, uniquement pour développement",
"help_stay_open": "Laisser tourner le onion service après que le téléchargment soit fini",
"help_debug": "Enregistrer les erreurs sur le disque",
@@ -29,8 +19,8 @@
"gui_add": "Ajouter",
"gui_delete": "Supprimer",
"gui_choose_items": "Sélectionnez",
- "gui_start_server": "Démarrer le serveur",
- "gui_stop_server": "Arrêter le serveur",
+ "gui_share_start_server": "Démarrer le serveur",
+ "gui_share_stop_server": "Arrêter le serveur",
"gui_copy_url": "Copier URL",
"gui_copy_hidservauth": "Copier HidServAuth",
"gui_downloads": "Téléchargements :",
@@ -39,5 +29,6 @@
"gui_please_wait": "Attendez-vous...",
"gui_quit_warning_quit": "Quitter",
"gui_quit_warning_dont_quit": "Ne quitter pas",
- "gui_settings_autoupdate_timestamp_never": "Jamais"
+ "gui_settings_autoupdate_timestamp_never": "Jamais",
+ "gui_settings_language_changed_notice": "Redémarrez OnionShare pour que votre changement de langue prenne effet"
}
diff --git a/share/locale/it.json b/share/locale/it.json
index 75532c34..ebe2df4e 100644
--- a/share/locale/it.json
+++ b/share/locale/it.json
@@ -1,43 +1,25 @@
{
- "connecting_ctrlport": "Connessione alla porta di controllo di Tor per inizializzare il servizio nascosto sulla porta {0:d}.",
- "cant_connect_ctrlport": "Impossibile connettere alla porta di controllo di Tor sulla porta {0:s}. OnionShare richiede l'esecuzione in background di Tor Browser per funzionare. Se non è installato puoi scaricarlo da https://www.torproject.org/.",
- "cant_connect_socksport": "Impossibile connettersi al server Tor SOCKS5 sulla porta {0:s}. OnionShare richiede l'esecuzione in background di Tor Browser per funzionare. Se non è installato puoi scaricarlo da https://www.torproject.org/.",
"preparing_files": "Preparazione dei files da condividere.",
- "wait_for_hs": "In attesa che l'HS sia pronto:",
- "wait_for_hs_trying": "Tentativo...",
- "wait_for_hs_nope": "Non è ancora pronto.",
- "wait_for_hs_yup": "Pronto!",
"give_this_url": "Dai questo URL alla persona a cui vuoi inviare il file:",
"ctrlc_to_stop": "Premi Ctrl-C per fermare il server",
"not_a_file": "{0:s} non è un file.",
- "download_page_loaded": "Pagina di Download caricata",
"other_page_loaded": "URL caricato",
"closing_automatically": "Chiusura automatica dopo aver finito il download",
"large_filesize": "Attenzione: Inviare file di grandi dimensioni può richiedere ore",
- "error_tails_invalid_port": "Valore non valido, la porta deve essere un numero intero",
- "error_tails_unknown_root": "Errore sconosciuto con il processo Tails root",
- "help_tails_port": "Solo per Tails: porta per passare il firewall, avvio del servizio nascosto",
"help_local_only": "Non usare tor: è solo per lo sviluppo",
"help_stay_open": "Mantieni il servizio nascosto avviato anche dopo aver finito il download",
- "help_transparent_torification": "Il mio sistema usa tor in modo trasparente",
"help_debug": "Registra gli errori sul disco",
"help_filename": "Lista dei file o cartelle da condividere",
"gui_drag_and_drop": "Prendi e rilascia\ni file qui sopra",
"gui_add": "Aggiungi",
"gui_delete": "Cancella",
"gui_choose_items": "Scegli",
- "gui_start_server": "Inizia la condivisione",
- "gui_stop_server": "Ferma la condivisione",
+ "gui_share_start_server": "Inizia la condivisione",
+ "gui_share_stop_server": "Ferma la condivisione",
"gui_copy_url": "Copia lo URL",
"gui_downloads": "Downloads:",
"gui_canceled": "Cancellati",
"gui_copied_url": "URL Copiato nella clipboard",
- "gui_starting_server1": "Avviamento del servizio nascosto Tor...",
- "gui_starting_server2": "Elaborazione files...",
- "gui_starting_server3": "In attesa del servizio nascosto Tor...",
"gui_please_wait": "Attendere prego...",
- "error_hs_dir_cannot_create": "Impossibile create la cartella per il servizio nascosto {0:s}",
- "error_hs_dir_not_writable": "La cartella per il servizio nascosto {0:s} non ha i permessi di scrittura",
- "using_ephemeral": "Avviamento del servizio nascosto Tor ephemeral e attesa della pubblicazione",
"zip_progress_bar_format": "Elaborazione files: %p%"
}
diff --git a/share/locale/nl.json b/share/locale/nl.json
index 3dd74664..abd14753 100644
--- a/share/locale/nl.json
+++ b/share/locale/nl.json
@@ -1,24 +1,17 @@
{
"config_onion_service": "Onion service configureren op poort {0:d}.",
"preparing_files": "Bestanden om te delen aan het voorbereiden.",
- "wait_for_hs": "Wachten op gereed zijn van HS:",
- "wait_for_hs_trying": "Proberen...",
- "wait_for_hs_nope": "Nog niet gereed.",
- "wait_for_hs_yup": "Gereed!",
"give_this_url": "Geef deze URL aan de persoon aan wie je dit bestand verzend:",
"give_this_url_stealth": "Geef deze URL en de HidServAuth regel aan de persoon aan wie je dit bestand verzend:",
"ctrlc_to_stop": "Druk Ctrl-C om de server te stoppen",
"not_a_file": "{0:s} is geen bestand.",
"not_a_readable_file": "{0:s} is geen leesbaar bestand.",
"no_available_port": "Kan de Onion service niet starten, er zijn geen poorten beschikbaar.",
- "download_page_loaded": "Downloadpagina geladen",
"other_page_loaded": "URL geladen",
"close_on_timeout": "Sluit automatisch omdat timeout bereikt is",
"closing_automatically": "Sluit automatisch omdat download gereed is",
"timeout_download_still_running": "Wachten totdat download gereed is voor automatisch sluiten",
"large_filesize": "Waarschuwing: Versturen van grote bestanden kan uren duren",
- "error_tails_invalid_port": "Ongeldige waarde, poort moet een integer zijn",
- "error_tails_unknown_root": "Onbekende fout met het Tails root proces",
"systray_menu_exit": "Afsluiten",
"systray_download_started_title": "OnionShare download gestart",
"systray_download_started_message": "Een gebruiker is begonnen met downloaden van je bestanden",
@@ -29,7 +22,6 @@
"help_local_only": "Maak geen gebruik van Tor, alleen voor ontwikkeling",
"help_stay_open": "Laat verborgen service draaien nadat download gereed is",
"help_shutdown_timeout": "Sluit de Onion service na N seconden",
- "help_transparent_torification": "Mijn systeem gebruikt Tor als proxyserver",
"help_stealth": "Maak stealth Onion service (geavanceerd)",
"help_debug": "Log fouten naar harde schijf",
"help_filename": "Lijst van bestanden of mappen om te delen",
@@ -38,25 +30,18 @@
"gui_add": "Toevoegen",
"gui_delete": "Verwijder",
"gui_choose_items": "Kies",
- "gui_start_server": "Start server",
- "gui_stop_server": "Stop server",
"gui_copy_url": "Kopieer URL",
"gui_copy_hidservauth": "Kopieer HidServAuth",
"gui_downloads": "Downloads:",
"gui_canceled": "Afgebroken",
"gui_copied_url": "URL gekopieerd naar klembord",
"gui_copied_hidservauth": "HidServAuth regel gekopieerd naar klembord",
- "gui_starting_server1": "Tor onion service wordt gestart...",
- "gui_starting_server2": "Bestanden verwerken...",
"gui_please_wait": "Moment geduld...",
- "error_hs_dir_cannot_create": "Kan verborgen service map {0:s} niet aanmaken",
- "error_hs_dir_not_writable": "Verborgen service map {0:s} is niet schrijfbaar",
- "using_ephemeral": "Kortstondige Tor onion service gestart en in afwachting van publicatie",
- "gui_download_progress_complete": "%p%, Tijd verstreken: {0:s}",
- "gui_download_progress_starting": "{0:s}, %p% (ETA berekenen)",
- "gui_download_progress_eta": "{0:s}, ETA: {1:s}, %p%",
+ "gui_download_upload_progress_complete": "%p%, Tijd verstreken: {0:s}",
+ "gui_download_upload_progress_starting": "{0:s}, %p% (ETA berekenen)",
+ "gui_download_upload_progress_eta": "{0:s}, ETA: {1:s}, %p%",
"version_string": "Onionshare {0:s} | https://onionshare.org/",
- "gui_quit_warning": "Weet je zeker dat je wilt afsluiten?\nDe URL die je aan het delen bent zal niet meer bestaan.",
+ "gui_share_quit_warning": "Weet je zeker dat je wilt afsluiten?\nDe URL die je aan het delen bent zal niet meer bestaan.",
"gui_quit_warning_quit": "Afsluiten",
"gui_quit_warning_dont_quit": "Niet afsluiten",
"error_rate_limit": "Een aanvaller probeert misschien je URL te gokken. Om dit te voorkomen heeft OnionShare de server automatisch gestopt. Om de bestanden te delen moet je de server opnieuw starten en de nieuwe URL delen.",
@@ -64,9 +49,7 @@
"error_stealth_not_supported": "Om een geheime onion service te maken heb je minstens Tor 0.2.9.1-alpha (of Tor Browser 6.5) en minstens python3-stem 1.5.0 nodig.",
"error_ephemeral_not_supported": "OnionShare vereist minstens Tor 0.2.7.1 en minstens python3-stem 1.4.0.",
"gui_settings_window_title": "Instellingen",
- "gui_settings_stealth_label": "Stealth (geavanceerd)",
"gui_settings_stealth_option": "Maak stealth onion services",
- "gui_settings_stealth_option_details": "Dit maakt OnionShare veiliger, maar ook lastiger voor de ontvanger om te verbinden.<br><a href=\"https://github.com/micahflee/onionshare/wiki/Stealth-Onion-Services\">Meer informatie</a>.",
"gui_settings_autoupdate_label": "Controleer voor updates",
"gui_settings_autoupdate_option": "Notificeer me als er updates beschikbaar zijn",
"gui_settings_autoupdate_timestamp": "Laatste controle: {}",
@@ -74,7 +57,6 @@
"gui_settings_autoupdate_check_button": "Controleer voor update",
"gui_settings_sharing_label": "Deel opties",
"gui_settings_close_after_first_download_option": "Stop delen na eerste download",
- "gui_settings_systray_notifications": "Laat desktop notificaties zien",
"gui_settings_connection_type_label": "Hoe moet OnionShare verbinden met Tor?",
"gui_settings_connection_type_bundled_option": "Gebruik Tor die is meegeleverd met OnionShare",
"gui_settings_connection_type_automatic_option": "Probeer automatische configuratie met Tor Browser",
@@ -87,13 +69,10 @@
"gui_settings_authenticate_label": "Tor authenticatie opties",
"gui_settings_authenticate_no_auth_option": "Geen authenticatie of cookie authenticatie",
"gui_settings_authenticate_password_option": "Wachtwoord",
- "gui_settings_authenticate_cookie_option": "Cookie",
"gui_settings_password_label": "Wachtwoord",
- "gui_settings_cookie_label": "Cookie pad",
"gui_settings_button_save": "Opslaan",
"gui_settings_button_cancel": "Annuleren",
"gui_settings_button_help": "Help",
- "gui_settings_shutdown_timeout_choice": "Auto-stop timer instellen?",
"gui_settings_shutdown_timeout": "Stop delen om:",
"settings_saved": "Instellingen opgeslagen in {}",
"settings_error_unknown": "Kan geen verbinding maken met de Tor controller omdat de instellingen niet kloppen.",
@@ -105,7 +84,6 @@
"settings_error_unreadable_cookie_file": "Verbonden met Tor controller, maar kan niet authenticeren omdat wachtwoord onjuist is en gebruiker heeft niet de permissies om cookie bestand te lezen.",
"settings_error_bundled_tor_not_supported": "Meegeleverde Tor is niet onersteunt wanneer je niet de ontwikkelaarsmodus gebruikt in Windows or macOS.",
"settings_error_bundled_tor_timeout": "Verbinden met Tor duurt te lang. Misschien is je computer offline, of je klok is niet accuraat.",
- "settings_error_bundled_tor_canceled": "Het Tor is afgesloten voordat het kon verbinden.",
"settings_error_bundled_tor_broken": "OnionShare kan niet verbinden met Tor op de achtergrond:\n{}",
"settings_test_success": "Gefeliciteerd, OnionShare kan verbinden met de Tor controller.\n\nTor version: {}\nOndersteunt kortstondige onion services: {}\nOndersteunt geheime onion services: {}",
"error_tor_protocol_error": "Fout bij praten met de Tor controller.\nAls je Whonix gebruikt, kijk dan hier https://www.whonix.org/wiki/onionshare om OnionShare werkend te krijgen.",
diff --git a/share/locale/no.json b/share/locale/no.json
index 8b131038..a04710d2 100644
--- a/share/locale/no.json
+++ b/share/locale/no.json
@@ -1,10 +1,7 @@
{
- "connecting_ctrlport": "Kobler til Tors kontroll-port for å sette opp en gjemt tjeneste på port {0:d}.",
- "cant_connect_ctrlport": "Klarte ikke å koble til Tors kontroll-porter {0:s}. Sjekk at Tor kjører.",
"give_this_url": "Gi personen du vil sende filen til denne URL-en:",
"ctrlc_to_stop": "Trykk Ctrl+C for å stoppe serveren.",
"not_a_file": "{0:s} er ikke en fil.",
"gui_copied_url": "Kopierte URL-en til utklippstavlen",
- "download_page_loaded": "Nedlastingsside lastet",
"other_page_loaded": "En annen side har blitt lastet"
}
diff --git a/share/locale/pt.json b/share/locale/pt_BR.json
index 71391957..1b2d3139 100644
--- a/share/locale/pt.json
+++ b/share/locale/pt_BR.json
@@ -1,10 +1,7 @@
{
- "connecting_ctrlport": "Conectando-se à porta de controle Tor para configurar serviço escondido na porta {0:d}.",
- "cant_connect_ctrlport": "Não pode conectar à porta de controle Tor na porta {0:s}. O Tor está rodando?",
"give_this_url": "Passe este URL para a pessoa que deve receber o arquivo:",
"ctrlc_to_stop": "Pressione Ctrl-C para parar o servidor",
"not_a_file": "{0:s} não é um arquivo.",
"gui_copied_url": "URL foi copiado para área de transferência",
- "download_page_loaded": "Página de download carregada",
"other_page_loaded": "Outra página tem sido carregada"
}
diff --git a/share/locale/pt_PT.json b/share/locale/pt_PT.json
new file mode 100644
index 00000000..1b2d3139
--- /dev/null
+++ b/share/locale/pt_PT.json
@@ -0,0 +1,7 @@
+{
+ "give_this_url": "Passe este URL para a pessoa que deve receber o arquivo:",
+ "ctrlc_to_stop": "Pressione Ctrl-C para parar o servidor",
+ "not_a_file": "{0:s} não é um arquivo.",
+ "gui_copied_url": "URL foi copiado para área de transferência",
+ "other_page_loaded": "Outra página tem sido carregada"
+}
diff --git a/share/locale/ru.json b/share/locale/ru.json
index 193c158d..b7c89d69 100644
--- a/share/locale/ru.json
+++ b/share/locale/ru.json
@@ -1,11 +1,8 @@
{
- "connecting_ctrlport": "Соединяемся с контрольным портом Tor для создания скрытого сервиса на порту {0:d}.",
- "cant_connect_ctrlport": "Невозможно соединиться с контрольным портом Tor на порту {0:s}. Tor запущен?",
"give_this_url": "Отправьте эту ссылку тому человеку, которому вы хотите передать файл:",
"ctrlc_to_stop": "Нажмите Ctrl-C чтобы остановить сервер",
"not_a_file": "{0:s} не является файлом.",
"gui_copied_url": "Ссылка скопирована в буфер обмена",
- "download_page_loaded": "Страница закачки загружена",
"other_page_loaded": "Другая страница была загружена",
"gui_copy_url": "Скопировать ссылку"
}
diff --git a/share/locale/tr.json b/share/locale/tr.json
index bd74f5f2..68807410 100644
--- a/share/locale/tr.json
+++ b/share/locale/tr.json
@@ -1,43 +1,25 @@
{
- "connecting_ctrlport": "{0:d} portundaki gizli hizmet(GH) kurulumu için Tor kontrol portuna bağlanıyor.",
- "cant_connect_ctrlport": "Tor kontrol {0:s} portuna bağlanamıyor. OnionShare çalışması için arkaplanda Tor Browser çalışması gerekiyor. Tor Browser indirmediyseniz, https://www.torproject.org/",
- "cant_connect_socksport": "Tor SOCKS5 sunucu {0:s} portuna bağlanamıyor. OnionShare çalışması için arkaplanda Tor Browser çalışması gerekiyor. Tor Browser indirmediyseniz, https://www.torproject.org/",
"preparing_files": "Paylaşmak için dosyalar hazırlanıyor.",
- "wait_for_hs": "GH hazır olması bekleniyor:",
- "wait_for_hs_trying": "Deneniyor...",
- "wait_for_hs_nope": "Henüz hazır değil.",
- "wait_for_hs_yup": "Hazır!",
"give_this_url": "Dosyayı gönderdiğin kişiye bu URL'i verin:",
"ctrlc_to_stop": "Sunucuyu durdurmak için, Ctrl-C basın",
"not_a_file": "{0:s} dosya değil.",
- "download_page_loaded": "İndirme sayfası yüklendi",
"other_page_loaded": "Diğer sayfa yüklendi",
"closing_automatically": "İndirme işlemi tamamlandığı için kendiliğinden durduruluyor",
"large_filesize": "Uyarı: Büyük dosyaların gönderimi saatler sürebilir",
- "error_tails_invalid_port": "Geçersiz değer, port sayı olmalıdır",
- "error_tails_unknown_root": "Tails ana işlemi ile ilgili bilinmeyen hata",
- "help_tails_port": "Sadece Tails: port for opening firewall, starting onion service",
"help_local_only": "Tor kullanmaya kalkışmayın: sadece geliştirme için",
"help_stay_open": "İndirme tamamlandıktan sonra gizli hizmeti çalıştırmaya devam et",
- "help_transparent_torification": "Sistemim apaçık torlu",
"help_debug": "Hata kayıtlarını diske kaydet",
"help_filename": "Paylaşmak için dosya ve klasörler listesi",
"gui_drag_and_drop": "Dosyaları buraya\n Sürükle ve Bırak",
"gui_add": "Ekle",
"gui_delete": "Sil",
"gui_choose_items": "Seç",
- "gui_start_server": "Paylaşımı Başlat",
- "gui_stop_server": "Paylaşımı Durdur",
+ "gui_share_start_server": "Paylaşımı Başlat",
+ "gui_share_stop_server": "Paylaşımı Durdur",
"gui_copy_url": "URL Kopyala",
"gui_downloads": "İndirilenler:",
"gui_canceled": "İptal edilen",
"gui_copied_url": "Panoya kopyalanan URL",
- "gui_starting_server1": "Tor gizli hizmeti başlatılıyor...",
- "gui_starting_server2": "Dosyalar hazırlanıyor...",
- "gui_starting_server3": "Tor gizli hizmeti bekleniyor...",
"gui_please_wait": "Lütfen bekleyin...",
- "error_hs_dir_cannot_create": "Gizli hizmet klasörü {0:s} oluşturulamıyor",
- "error_hs_dir_not_writable": "Gizle hizmet klasörü {0:s} yazılabilir değil",
- "using_ephemeral": "Geçici Tor gizli hizmetine bakılıyor ve yayımı bekleniyor",
"zip_progress_bar_format": "Dosyalar hazırlanıyor: %p%"
}
diff --git a/share/static/css/style.css b/share/static/css/style.css
new file mode 100644
index 00000000..fd10ecdf
--- /dev/null
+++ b/share/static/css/style.css
@@ -0,0 +1,194 @@
+.clearfix:after {
+ content: ".";
+ display: block;
+ clear: both;
+ visibility: hidden;
+ line-height: 0;
+ height: 0;
+}
+
+body {
+ margin: 0;
+ font-family: Helvetica;
+}
+
+header {
+ border-bottom: 1px solid rgba(0, 0, 0, 0.1);
+ background: #fcfcfc;
+ background: -webkit-linear-gradient(top, #fcfcfc 0%, #f2f2f2 100%);
+ padding: 0.8rem;
+}
+
+header .logo {
+ vertical-align: middle;
+ width: 45px;
+ height: 45px;
+}
+
+header h1 {
+ display: inline-block;
+ margin: 0 0 0 0.5rem;
+ vertical-align: middle;
+ font-weight: normal;
+ font-size: 1.5rem;
+ color: #666666;
+}
+
+header .right {
+ float: right;
+ font-size: .75rem;
+}
+
+header .right ul li {
+ display: inline;
+ margin: 0 0 0 .5rem;
+ font-size: 1rem;
+}
+
+.button {
+ color: #ffffff;
+ background-color: #4e064f;
+ padding: 10px;
+ border: 0;
+ border-radius: 5px;
+ text-decoration: none;
+ margin-left: 1rem;
+ cursor: pointer;
+}
+
+.close-button {
+ color: #ffffff;
+ background-color: #c90c0c;
+ padding: 10px;
+ border: 0;
+ border-radius: 5px;
+ text-decoration: none;
+ margin-left: 1rem;
+ cursor: pointer;
+ position: absolute;
+ right: 10px;
+ bottom: 10px;
+}
+
+table.file-list {
+ width: 100%;
+ margin: 0 auto;
+ border-collapse: collapse;
+}
+
+table.file-list th {
+ text-align: left;
+ text-transform: uppercase;
+ font-weight: normal;
+ color: #666666;
+ padding: 0.5rem;
+}
+
+table.file-list tr {
+ border-bottom: 1px solid #e0e0e0;
+}
+
+table.file-list td {
+ white-space: nowrap;
+ padding: 0.5rem 10rem 0.5rem 0.8rem;
+}
+
+table.file-list td img {
+ vertical-align: middle;
+ margin-right: 0.5rem;
+}
+
+table.file-list td:last-child {
+ width: 100%;
+}
+
+.upload-wrapper {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 400px;
+}
+
+.upload {
+ text-align: center;
+}
+
+.upload img {
+ width: 120px;
+ height: 120px;
+}
+
+.upload .upload-header {
+ font-size: 30px;
+ font-weight: normal;
+ color: #666666;
+ margin: 0 0 10px 0;
+}
+
+.upload .upload-description {
+ color: #666666;
+ margin: 0 0 20px 0;
+}
+
+ul.flashes {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ color: #cc0000;
+ text-align: left;
+}
+
+ul.flashes li {
+ margin: 0;
+ padding: 10px;
+}
+
+li.error {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ color: #ffffff;
+ background-color: #c90c0c;
+ border: 0;
+ border-radius: 5px;
+ text-align: left;
+}
+
+li.info {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ color: #000000;
+ background-color: #a9e26c;
+ border: 0;
+ border-radius: 5px;
+ text-align: left;
+}
+
+.closed-wrapper {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 400px;
+}
+
+.info {
+ text-align: center;
+}
+
+.info img {
+ width: 120px;
+ height: 120px;
+}
+
+.info .info-header {
+ font-size: 30px;
+ font-weight: normal;
+ color: #666666;
+ margin: 0 0 10px 0;
+}
+
+.info .info-description {
+ color: #666666;
+ margin: 0 0 20px 0;
+}
diff --git a/share/images/favicon.ico b/share/static/img/favicon.ico
index 63e65d8b..63e65d8b 100644
--- a/share/images/favicon.ico
+++ b/share/static/img/favicon.ico
Binary files differ
diff --git a/share/static/img/logo.png b/share/static/img/logo.png
new file mode 100644
index 00000000..43884c1f
--- /dev/null
+++ b/share/static/img/logo.png
Binary files differ
diff --git a/share/static/img/logo_large.png b/share/static/img/logo_large.png
new file mode 100644
index 00000000..ee8f26ac
--- /dev/null
+++ b/share/static/img/logo_large.png
Binary files differ
diff --git a/share/images/web_file.png b/share/static/img/web_file.png
index 1931aff0..1931aff0 100644
--- a/share/images/web_file.png
+++ b/share/static/img/web_file.png
Binary files differ
diff --git a/share/images/web_folder.png b/share/static/img/web_folder.png
index 3ca5df21..3ca5df21 100644
--- a/share/images/web_folder.png
+++ b/share/static/img/web_folder.png
Binary files differ
diff --git a/share/static/js/send.js b/share/static/js/send.js
new file mode 100644
index 00000000..43e9892d
--- /dev/null
+++ b/share/static/js/send.js
@@ -0,0 +1,75 @@
+// Function to convert human-readable sizes back to bytes, for sorting
+function unhumanize(text) {
+ var powers = {'b': 0, 'k': 1, 'm': 2, 'g': 3, 't': 4};
+ var regex = /(\d+(?:\.\d+)?)\s?(B|K|M|G|T)?/i;
+ var res = regex.exec(text);
+ if(res[2] === undefined) {
+ // Account for alphabetical words (file/dir names)
+ return text;
+ } else {
+ return res[1] * Math.pow(1024, powers[res[2].toLowerCase()]);
+ }
+}
+function sortTable(n) {
+ var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
+ table = document.getElementById("file-list");
+ switching = true;
+ // Set the sorting direction to ascending:
+ dir = "asc";
+ /* Make a loop that will continue until
+ no switching has been done: */
+ while (switching) {
+ // Start by saying: no switching is done:
+ switching = false;
+ rows = table.getElementsByTagName("TR");
+ /* Loop through all table rows (except the
+ first, which contains table headers): */
+ for (i = 1; i < (rows.length - 1); i++) {
+ // Start by saying there should be no switching:
+ shouldSwitch = false;
+ /* Get the two elements you want to compare,
+ one from current row and one from the next: */
+ x = rows[i].getElementsByTagName("TD")[n];
+ y = rows[i + 1].getElementsByTagName("TD")[n];
+ /* Check if the two rows should switch place,
+ based on the direction, asc or desc: */
+ if (dir == "asc") {
+ if (unhumanize(x.innerHTML.toLowerCase()) > unhumanize(y.innerHTML.toLowerCase())) {
+ // If so, mark as a switch and break the loop:
+ shouldSwitch= true;
+ break;
+ }
+ } else if (dir == "desc") {
+ if (unhumanize(x.innerHTML.toLowerCase()) < unhumanize(y.innerHTML.toLowerCase())) {
+ // If so, mark as a switch and break the loop:
+ shouldSwitch= true;
+ break;
+ }
+ }
+ }
+ if (shouldSwitch) {
+ /* If a switch has been marked, make the switch
+ and mark that a switch has been done: */
+ rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
+ switching = true;
+ // Each time a switch is done, increase this count by 1:
+ switchcount ++;
+ } else {
+ /* If no switching has been done AND the direction is "asc",
+ set the direction to "desc" and run the while loop again. */
+ if (switchcount == 0 && dir == "asc") {
+ dir = "desc";
+ switching = true;
+ }
+ }
+ }
+}
+
+
+// Set click handlers
+document.getElementById("filename-header").addEventListener("click", function(){
+ sortTable(0);
+});
+document.getElementById("size-header").addEventListener("click", function(){
+ sortTable(1);
+});
diff --git a/share/templates/403.html b/share/templates/403.html
new file mode 100644
index 00000000..df81f3e7
--- /dev/null
+++ b/share/templates/403.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>OnionShare: 403 Forbidden</title>
+ <link href="/static/img/favicon.ico" rel="icon" type="image/x-icon" />
+ <link href="/static/css/style.css" rel="stylesheet" type="text/css" />
+ </head>
+ <body>
+ <div class="info-wrapper">
+ <div class="info">
+ <p><img class="logo" src="/static/img/logo_large.png" title="OnionShare"></p>
+ <p class="info-header">You are not allowed to perform that action at this time.</p>
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/share/templates/404.html b/share/templates/404.html
new file mode 100644
index 00000000..264ca517
--- /dev/null
+++ b/share/templates/404.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>OnionShare: 404 Not Found</title>
+ <link href="/static/img/favicon.ico" rel="icon" type="image/x-icon" />
+ <link href="/static/css/style.css" rel="stylesheet" type="text/css" />
+ </head>
+ <body>
+ <div class="info-wrapper">
+ <div class="info">
+ <p><img class="logo" src="/static/img/logo_large.png" title="OnionShare"></p>
+ <p class="info-header">404 Not Found</p>
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/share/templates/denied.html b/share/templates/denied.html
new file mode 100644
index 00000000..5d411d62
--- /dev/null
+++ b/share/templates/denied.html
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>OnionShare</title>
+ <link href="/static/img/favicon.ico" rel="icon" type="image/x-icon" />
+ </head>
+ <body>
+ <p>OnionShare download in progress</p>
+ </body>
+</html>
diff --git a/share/templates/receive.html b/share/templates/receive.html
new file mode 100644
index 00000000..e85b6ff9
--- /dev/null
+++ b/share/templates/receive.html
@@ -0,0 +1,38 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>OnionShare</title>
+ <link href="/static/img/favicon.ico" rel="icon" type="image/x-icon" />
+ <link href="/static/css/style.css" rel="stylesheet" type="text/css" />
+ </head>
+ <body>
+
+ <header class="clearfix">
+ <img class="logo" src="/static/img/logo.png" title="OnionShare">
+ <h1>OnionShare</h1>
+ </header>
+
+ <div class="upload-wrapper">
+ <div class="upload">
+ <p><img class="logo" src="/static/img/logo_large.png" title="OnionShare"></p>
+ <p class="upload-header">Send Files</p>
+ <p class="upload-description">Select the files you want to send, then click "Send Files"...</p>
+ <form method="post" enctype="multipart/form-data" action="{{ upload_action }}">
+ <p><input type="file" name="file[]" multiple /></p>
+ <p><input type="submit" class="button" value="Send Files" /></p>
+ <div>
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ <ul class=flashes>
+ {% for category, message in messages %}
+ <li class="{{ category }}">{{ message }}</li>
+ {% endfor %}
+ </ul>
+ {% endif %}
+ {% endwith %}
+ </div>
+ </form>
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/share/templates/send.html b/share/templates/send.html
new file mode 100644
index 00000000..e7e1fde0
--- /dev/null
+++ b/share/templates/send.html
@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>OnionShare</title>
+ <link href="/static/img/favicon.ico" rel="icon" type="image/x-icon" />
+ <link href="/static/css/style.css" rel="stylesheet" type="text/css" />
+ <meta name="onionshare-filename" content="{{ filename }}">
+ <meta name="onionshare-filesize" content="{{ filesize }}">
+ </head>
+ <body>
+
+ <header class="clearfix">
+ <div class="right">
+ <ul>
+ <li>Total size: <strong>{{ filesize_human }}</strong> {% if is_zipped %} (compressed){% endif %}</li>
+ {% if slug %}
+ <li><a class="button" href='/{{ slug }}/download'>Download Files</a></li>
+ {% else %}
+ <li><a class="button" href='/download'>Download Files</a></li>
+ {% endif %}
+ </ul>
+ </div>
+ <img class="logo" src="/static/img/logo.png" title="OnionShare">
+ <h1>OnionShare</h1>
+ </header>
+
+ <table class="file-list" id="file-list">
+ <tr>
+ <th id="filename-header">Filename</th>
+ <th id="size-header">Size</th>
+ <th></th>
+ </tr>
+ {% for info in file_info.dirs %}
+ <tr>
+ <td>
+ <img width="30" height="30" title="" alt="" src="/static/img/web_folder.png" />
+ {{ info.basename }}
+ </td>
+ <td>{{ info.size_human }}</td>
+ <td></td>
+ </tr>
+ {% endfor %}
+ {% for info in file_info.files %}
+ <tr>
+ <td>
+ <img width="30" height="30" title="" alt="" src="/static/img/web_file.png" />
+ {{ info.basename }}
+ </td>
+ <td>{{ info.size_human }}</td>
+ <td></td>
+ </tr>
+ {% endfor %}
+ </table>
+ <script src="/static/js/send.js"></script>
+ </body>
+</html>
diff --git a/share/templates/thankyou.html b/share/templates/thankyou.html
new file mode 100644
index 00000000..64c8b369
--- /dev/null
+++ b/share/templates/thankyou.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>OnionShare is closed</title>
+ <link href="/static/img/favicon.ico" rel="icon" type="image/x-icon" />
+ <link href="/static/css/style.css" rel="stylesheet" type="text/css" />
+ </head>
+ <body>
+ <header class="clearfix">
+ <img class="logo" src="/static/img/logo.png" title="OnionShare">
+ <h1>OnionShare</h1>
+ </header>
+
+ <div class="info-wrapper">
+ <div class="info">
+ <p><img class="logo" src="/static/img/logo_large.png" title="OnionShare"></p>
+ <p class="info-header">Thank you for using OnionShare</p>
+ <p class="info-description">You may now close this window.</p>
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/share/version.txt b/share/version.txt
index 3a3cd8cc..22351bb8 100644
--- a/share/version.txt
+++ b/share/version.txt
@@ -1 +1 @@
-1.3.1
+2.0.dev
diff --git a/stdeb.cfg b/stdeb.cfg
index 334502c0..6729d1b7 100644
--- a/stdeb.cfg
+++ b/stdeb.cfg
@@ -1,6 +1,6 @@
[DEFAULT]
Package3: onionshare
-Depends3: python3-flask, python3-stem, python3-pyqt5, python-nautilus, tor, obfs4proxy
-Build-Depends: python3-pytest, python3-flask, python3-stem, python3-pyqt5
-Suite: xenial
-X-Python3-Version: >= 3.4
+Depends3: python3-flask, python3-stem, python3-pyqt5, python3-crypto, python3-socks, python-nautilus, tor, obfs4proxy
+Build-Depends: python3-pytest, python3-flask, python3-stem, python3-pyqt5, python3-crypto, python3-socks, python-nautilus, tor, obfs4proxy
+Suite: bionic
+X-Python3-Version: >= 3.5.3
diff --git a/tests/GuiBaseTest.py b/tests/GuiBaseTest.py
new file mode 100644
index 00000000..c557fc15
--- /dev/null
+++ b/tests/GuiBaseTest.py
@@ -0,0 +1,323 @@
+import json
+import os
+import requests
+import shutil
+import socket
+import socks
+
+from PyQt5 import QtCore, QtTest
+
+from onionshare import strings
+from onionshare.common import Common
+from onionshare.settings import Settings
+from onionshare.onion import Onion
+from onionshare.web import Web
+from onionshare_gui import Application, OnionShare, OnionShareGui
+from onionshare_gui.mode.share_mode import ShareMode
+from onionshare_gui.mode.receive_mode import ReceiveMode
+
+
+class GuiBaseTest(object):
+ @staticmethod
+ def set_up(test_settings):
+ '''Create GUI with given settings'''
+ # Create our test file
+ testfile = open('/tmp/test.txt', 'w')
+ testfile.write('onionshare')
+ testfile.close()
+
+ # Create a test dir and files
+ if not os.path.exists('/tmp/testdir'):
+ testdir = os.mkdir('/tmp/testdir')
+ testfile = open('/tmp/testdir/test', 'w')
+ testfile.write('onionshare')
+ testfile.close()
+
+ common = Common()
+ common.settings = Settings(common)
+ common.define_css()
+ strings.load_strings(common)
+
+ # Get all of the settings in test_settings
+ test_settings['downloads_dir'] = '/tmp/OnionShare'
+ for key, val in common.settings.default_settings.items():
+ if key not in test_settings:
+ test_settings[key] = val
+
+ # Start the Onion
+ testonion = Onion(common)
+ global qtapp
+ qtapp = Application(common)
+ app = OnionShare(common, testonion, True, 0)
+
+ web = Web(common, False, True)
+ open('/tmp/settings.json', 'w').write(json.dumps(test_settings))
+
+ gui = OnionShareGui(common, testonion, qtapp, app, ['/tmp/test.txt', '/tmp/testdir'], '/tmp/settings.json', True)
+ return gui
+
+ @staticmethod
+ def tear_down():
+ '''Clean up after tests'''
+ try:
+ os.remove('/tmp/test.txt')
+ os.remove('/tmp/settings.json')
+ os.remove('/tmp/large_file')
+ os.remove('/tmp/download.zip')
+ os.remove('/tmp/webpage')
+ shutil.rmtree('/tmp/testdir')
+ shutil.rmtree('/tmp/OnionShare')
+ except:
+ pass
+
+
+ def gui_loaded(self):
+ '''Test that the GUI actually is shown'''
+ self.assertTrue(self.gui.show)
+
+
+ def windowTitle_seen(self):
+ '''Test that the window title is OnionShare'''
+ self.assertEqual(self.gui.windowTitle(), 'OnionShare')
+
+
+ def settings_button_is_visible(self):
+ '''Test that the settings button is visible'''
+ self.assertTrue(self.gui.settings_button.isVisible())
+
+
+ def settings_button_is_hidden(self):
+ '''Test that the settings button is hidden when the server starts'''
+ self.assertFalse(self.gui.settings_button.isVisible())
+
+
+ def server_status_bar_is_visible(self):
+ '''Test that the status bar is visible'''
+ self.assertTrue(self.gui.status_bar.isVisible())
+
+
+ def click_mode(self, mode):
+ '''Test that we can switch Mode by clicking the button'''
+ if type(mode) == ReceiveMode:
+ QtTest.QTest.mouseClick(self.gui.receive_mode_button, QtCore.Qt.LeftButton)
+ self.assertTrue(self.gui.mode, self.gui.MODE_RECEIVE)
+ if type(mode) == ShareMode:
+ QtTest.QTest.mouseClick(self.gui.share_mode_button, QtCore.Qt.LeftButton)
+ self.assertTrue(self.gui.mode, self.gui.MODE_SHARE)
+
+
+ def click_toggle_history(self, mode):
+ '''Test that we can toggle Download or Upload history by clicking the toggle button'''
+ currently_visible = mode.history.isVisible()
+ QtTest.QTest.mouseClick(mode.toggle_history, QtCore.Qt.LeftButton)
+ self.assertEqual(mode.history.isVisible(), not currently_visible)
+
+
+ def history_indicator(self, mode, public_mode):
+ '''Test that we can make sure the history is toggled off, do an action, and the indiciator works'''
+ # Make sure history is toggled off
+ if mode.history.isVisible():
+ QtTest.QTest.mouseClick(mode.toggle_history, QtCore.Qt.LeftButton)
+ self.assertFalse(mode.history.isVisible())
+
+ # Indicator should not be visible yet
+ self.assertFalse(mode.toggle_history.indicator_label.isVisible())
+
+ if type(mode) == ReceiveMode:
+ # Upload a file
+ files = {'file[]': open('/tmp/test.txt', 'rb')}
+ if not public_mode:
+ path = 'http://127.0.0.1:{}/{}/upload'.format(self.gui.app.port, mode.web.slug)
+ else:
+ path = 'http://127.0.0.1:{}/upload'.format(self.gui.app.port)
+ response = requests.post(path, files=files)
+ QtTest.QTest.qWait(2000)
+
+ if type(mode) == ShareMode:
+ # Download files
+ if public_mode:
+ url = "http://127.0.0.1:{}/download".format(self.gui.app.port)
+ else:
+ url = "http://127.0.0.1:{}/{}/download".format(self.gui.app.port, mode.web.slug)
+ r = requests.get(url)
+ QtTest.QTest.qWait(2000)
+
+ # Indicator should be visible, have a value of "1"
+ self.assertTrue(mode.toggle_history.indicator_label.isVisible())
+ self.assertEqual(mode.toggle_history.indicator_label.text(), "1")
+
+ # Toggle history back on, indicator should be hidden again
+ QtTest.QTest.mouseClick(mode.toggle_history, QtCore.Qt.LeftButton)
+ self.assertFalse(mode.toggle_history.indicator_label.isVisible())
+
+
+ def history_is_not_visible(self, mode):
+ '''Test that the History section is not visible'''
+ self.assertFalse(mode.history.isVisible())
+
+
+ def history_is_visible(self, mode):
+ '''Test that the History section is visible'''
+ self.assertTrue(mode.history.isVisible())
+
+
+ def server_working_on_start_button_pressed(self, mode):
+ '''Test we can start the service'''
+ # Should be in SERVER_WORKING state
+ QtTest.QTest.mouseClick(mode.server_status.server_button, QtCore.Qt.LeftButton)
+ self.assertEqual(mode.server_status.status, 1)
+
+
+ def server_status_indicator_says_starting(self, mode):
+ '''Test that the Server Status indicator shows we are Starting'''
+ self.assertEqual(mode.server_status_label.text(), strings._('gui_status_indicator_share_working'))
+
+
+ def server_is_started(self, mode, startup_time=2000):
+ '''Test that the server has started'''
+ QtTest.QTest.qWait(startup_time)
+ # Should now be in SERVER_STARTED state
+ self.assertEqual(mode.server_status.status, 2)
+
+
+ def web_server_is_running(self):
+ '''Test that the web server has started'''
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+
+ self.assertEqual(sock.connect_ex(('127.0.0.1',self.gui.app.port)), 0)
+
+
+ def have_a_slug(self, mode, public_mode):
+ '''Test that we have a valid slug'''
+ if not public_mode:
+ self.assertRegex(mode.server_status.web.slug, r'(\w+)-(\w+)')
+ else:
+ self.assertIsNone(mode.server_status.web.slug, r'(\w+)-(\w+)')
+
+
+ def url_description_shown(self, mode):
+ '''Test that the URL label is showing'''
+ self.assertTrue(mode.server_status.url_description.isVisible())
+
+
+ def have_copy_url_button(self, mode, public_mode):
+ '''Test that the Copy URL button is shown and that the clipboard is correct'''
+ self.assertTrue(mode.server_status.copy_url_button.isVisible())
+
+ QtTest.QTest.mouseClick(mode.server_status.copy_url_button, QtCore.Qt.LeftButton)
+ clipboard = self.gui.qtapp.clipboard()
+ if public_mode:
+ self.assertEqual(clipboard.text(), 'http://127.0.0.1:{}'.format(self.gui.app.port))
+ else:
+ self.assertEqual(clipboard.text(), 'http://127.0.0.1:{}/{}'.format(self.gui.app.port, mode.server_status.web.slug))
+
+
+ def server_status_indicator_says_started(self, mode):
+ '''Test that the Server Status indicator shows we are started'''
+ if type(mode) == ReceiveMode:
+ self.assertEqual(mode.server_status_label.text(), strings._('gui_status_indicator_receive_started'))
+ if type(mode) == ShareMode:
+ self.assertEqual(mode.server_status_label.text(), strings._('gui_status_indicator_share_started'))
+
+
+ def web_page(self, mode, string, public_mode):
+ '''Test that the web page contains a string'''
+ s = socks.socksocket()
+ s.settimeout(60)
+ s.connect(('127.0.0.1', self.gui.app.port))
+
+ if not public_mode:
+ path = '/{}'.format(mode.server_status.web.slug)
+ else:
+ path = '/'
+
+ http_request = 'GET {} HTTP/1.0\r\n'.format(path)
+ http_request += 'Host: 127.0.0.1\r\n'
+ http_request += '\r\n'
+ s.sendall(http_request.encode('utf-8'))
+
+ with open('/tmp/webpage', 'wb') as file_to_write:
+ while True:
+ data = s.recv(1024)
+ if not data:
+ break
+ file_to_write.write(data)
+ file_to_write.close()
+
+ f = open('/tmp/webpage')
+ self.assertTrue(string in f.read())
+ f.close()
+
+
+ def history_widgets_present(self, mode):
+ '''Test that the relevant widgets are present in the history view after activity has taken place'''
+ self.assertFalse(mode.history.empty.isVisible())
+ self.assertTrue(mode.history.not_empty.isVisible())
+
+
+ def counter_incremented(self, mode, count):
+ '''Test that the counter has incremented'''
+ self.assertEqual(mode.history.completed_count, count)
+
+
+ def server_is_stopped(self, mode, stay_open):
+ '''Test that the server stops when we click Stop'''
+ if type(mode) == ReceiveMode or (type(mode) == ShareMode and stay_open):
+ QtTest.QTest.mouseClick(mode.server_status.server_button, QtCore.Qt.LeftButton)
+ self.assertEqual(mode.server_status.status, 0)
+
+
+ def web_server_is_stopped(self):
+ '''Test that the web server also stopped'''
+ QtTest.QTest.qWait(2000)
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+
+ # We should be closed by now. Fail if not!
+ self.assertNotEqual(sock.connect_ex(('127.0.0.1',self.gui.app.port)), 0)
+
+
+ def server_status_indicator_says_closed(self, mode, stay_open):
+ '''Test that the Server Status indicator shows we closed'''
+ if type(mode) == ReceiveMode:
+ self.assertEqual(self.gui.receive_mode.server_status_label.text(), strings._('gui_status_indicator_receive_stopped'))
+ if type(mode) == ShareMode:
+ if stay_open:
+ self.assertEqual(self.gui.share_mode.server_status_label.text(), strings._('gui_status_indicator_share_stopped'))
+ else:
+ self.assertEqual(self.gui.share_mode.server_status_label.text(), strings._('closing_automatically'))
+
+
+ # Auto-stop timer tests
+ def set_timeout(self, mode, timeout):
+ '''Test that the timeout can be set'''
+ timer = QtCore.QDateTime.currentDateTime().addSecs(timeout)
+ mode.server_status.shutdown_timeout.setDateTime(timer)
+ self.assertTrue(mode.server_status.shutdown_timeout.dateTime(), timer)
+
+
+ def timeout_widget_hidden(self, mode):
+ '''Test that the timeout widget is hidden when share has started'''
+ self.assertFalse(mode.server_status.shutdown_timeout_container.isVisible())
+
+
+ def server_timed_out(self, mode, wait):
+ '''Test that the server has timed out after the timer ran out'''
+ QtTest.QTest.qWait(wait)
+ # We should have timed out now
+ self.assertEqual(mode.server_status.status, 0)
+
+ # Hack to close an Alert dialog that would otherwise block tests
+ def accept_dialog(self):
+ window = self.gui.qtapp.activeWindow()
+ if window:
+ window.close()
+
+ # 'Grouped' tests follow from here
+
+ def run_all_common_setup_tests(self):
+ self.gui_loaded()
+ self.windowTitle_seen()
+ self.settings_button_is_visible()
+ self.server_status_bar_is_visible()
+
+
diff --git a/tests/GuiReceiveTest.py b/tests/GuiReceiveTest.py
new file mode 100644
index 00000000..eaed8343
--- /dev/null
+++ b/tests/GuiReceiveTest.py
@@ -0,0 +1,124 @@
+import os
+import requests
+from datetime import datetime, timedelta
+from PyQt5 import QtCore, QtTest
+from .GuiBaseTest import GuiBaseTest
+
+class GuiReceiveTest(GuiBaseTest):
+ def upload_file(self, public_mode, file_to_upload, expected_basename):
+ '''Test that we can upload the file'''
+ files = {'file[]': open(file_to_upload, 'rb')}
+ if not public_mode:
+ path = 'http://127.0.0.1:{}/{}/upload'.format(self.gui.app.port, self.gui.receive_mode.web.slug)
+ else:
+ path = 'http://127.0.0.1:{}/upload'.format(self.gui.app.port)
+ response = requests.post(path, files=files)
+ QtTest.QTest.qWait(2000)
+
+ # Make sure the file is within the last 10 seconds worth of filenames
+ exists = False
+ now = datetime.now()
+ for i in range(10):
+ date_dir = now.strftime("%Y-%m-%d")
+ time_dir = now.strftime("%H.%M.%S")
+ receive_mode_dir = os.path.join(self.gui.common.settings.get('downloads_dir'), date_dir, time_dir)
+ expected_filename = os.path.join(receive_mode_dir, expected_basename)
+ if os.path.exists(expected_filename):
+ exists = True
+ break
+ now = now - timedelta(seconds=1)
+
+ self.assertTrue(exists)
+
+ def upload_file_should_fail(self, public_mode):
+ '''Test that we can't upload the file when permissions are wrong, and expected content is shown'''
+ files = {'file[]': open('/tmp/test.txt', 'rb')}
+ if not public_mode:
+ path = 'http://127.0.0.1:{}/{}/upload'.format(self.gui.app.port, self.gui.receive_mode.web.slug)
+ else:
+ path = 'http://127.0.0.1:{}/upload'.format(self.gui.app.port)
+ response = requests.post(path, files=files)
+
+ QtCore.QTimer.singleShot(1000, self.accept_dialog)
+ self.assertTrue('Error uploading, please inform the OnionShare user' in response.text)
+
+ def upload_dir_permissions(self, mode=0o755):
+ '''Manipulate the permissions on the upload dir in between tests'''
+ os.chmod('/tmp/OnionShare', mode)
+
+ def try_public_paths_in_non_public_mode(self):
+ response = requests.post('http://127.0.0.1:{}/upload'.format(self.gui.app.port))
+ self.assertEqual(response.status_code, 404)
+ response = requests.get('http://127.0.0.1:{}/close'.format(self.gui.app.port))
+ self.assertEqual(response.status_code, 404)
+
+ def run_receive_mode_sender_closed_tests(self, public_mode):
+ '''Test that the share can be stopped by the sender in receive mode'''
+ if not public_mode:
+ path = 'http://127.0.0.1:{}/{}/close'.format(self.gui.app.port, self.gui.receive_mode.web.slug)
+ else:
+ path = 'http://127.0.0.1:{}/close'.format(self.gui.app.port)
+ response = requests.post(path)
+ self.server_is_stopped(self.gui.receive_mode, False)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.receive_mode, False)
+
+
+ # 'Grouped' tests follow from here
+
+ def run_all_receive_mode_setup_tests(self, public_mode):
+ '''Set up a share in Receive mode and start it'''
+ self.click_mode(self.gui.receive_mode)
+ self.history_is_not_visible(self.gui.receive_mode)
+ self.click_toggle_history(self.gui.receive_mode)
+ self.history_is_visible(self.gui.receive_mode)
+ self.server_working_on_start_button_pressed(self.gui.receive_mode)
+ self.server_status_indicator_says_starting(self.gui.receive_mode)
+ self.settings_button_is_hidden()
+ self.server_is_started(self.gui.receive_mode)
+ self.web_server_is_running()
+ self.have_a_slug(self.gui.receive_mode, public_mode)
+ self.url_description_shown(self.gui.receive_mode)
+ self.have_copy_url_button(self.gui.receive_mode, public_mode)
+ self.server_status_indicator_says_started(self.gui.receive_mode)
+ self.web_page(self.gui.receive_mode, 'Select the files you want to send, then click', public_mode)
+
+ def run_all_receive_mode_tests(self, public_mode, receive_allow_receiver_shutdown):
+ '''Upload files in receive mode and stop the share'''
+ self.run_all_receive_mode_setup_tests(public_mode)
+ if not public_mode:
+ self.try_public_paths_in_non_public_mode()
+ self.upload_file(public_mode, '/tmp/test.txt', 'test.txt')
+ self.history_widgets_present(self.gui.receive_mode)
+ self.counter_incremented(self.gui.receive_mode, 1)
+ self.upload_file(public_mode, '/tmp/test.txt', 'test.txt')
+ self.counter_incremented(self.gui.receive_mode, 2)
+ self.upload_file(public_mode, '/tmp/testdir/test', 'test')
+ self.counter_incremented(self.gui.receive_mode, 3)
+ self.upload_file(public_mode, '/tmp/testdir/test', 'test')
+ self.counter_incremented(self.gui.receive_mode, 4)
+ self.history_indicator(self.gui.receive_mode, public_mode)
+ self.server_is_stopped(self.gui.receive_mode, False)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.receive_mode, False)
+ self.server_working_on_start_button_pressed(self.gui.receive_mode)
+ self.server_is_started(self.gui.receive_mode)
+ self.history_indicator(self.gui.receive_mode, public_mode)
+
+ def run_all_receive_mode_unwritable_dir_tests(self, public_mode, receive_allow_receiver_shutdown):
+ '''Attempt to upload (unwritable) files in receive mode and stop the share'''
+ self.run_all_receive_mode_setup_tests(public_mode)
+ self.upload_dir_permissions(0o400)
+ self.upload_file_should_fail(public_mode)
+ self.server_is_stopped(self.gui.receive_mode, True)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.receive_mode, False)
+ self.upload_dir_permissions(0o755)
+
+ def run_all_receive_mode_timer_tests(self, public_mode):
+ """Auto-stop timer tests in receive mode"""
+ self.run_all_receive_mode_setup_tests(public_mode)
+ self.set_timeout(self.gui.receive_mode, 5)
+ self.timeout_widget_hidden(self.gui.receive_mode)
+ self.server_timed_out(self.gui.receive_mode, 15000)
+ self.web_server_is_stopped()
diff --git a/tests/GuiShareTest.py b/tests/GuiShareTest.py
new file mode 100644
index 00000000..716bab73
--- /dev/null
+++ b/tests/GuiShareTest.py
@@ -0,0 +1,204 @@
+import os
+import requests
+import socks
+import zipfile
+from PyQt5 import QtCore, QtTest
+from .GuiBaseTest import GuiBaseTest
+
+class GuiShareTest(GuiBaseTest):
+ # Persistence tests
+ def have_same_slug(self, slug):
+ '''Test that we have the same slug'''
+ self.assertEqual(self.gui.share_mode.server_status.web.slug, slug)
+
+ # Share-specific tests
+
+ def file_selection_widget_has_files(self, num=2):
+ '''Test that the number of items in the list is as expected'''
+ self.assertEqual(self.gui.share_mode.server_status.file_selection.get_num_files(), num)
+
+
+ def deleting_all_files_hides_delete_button(self):
+ '''Test that clicking on the file item shows the delete button. Test that deleting the only item in the list hides the delete button'''
+ rect = self.gui.share_mode.server_status.file_selection.file_list.visualItemRect(self.gui.share_mode.server_status.file_selection.file_list.item(0))
+ QtTest.QTest.mouseClick(self.gui.share_mode.server_status.file_selection.file_list.viewport(), QtCore.Qt.LeftButton, pos=rect.center())
+ # Delete button should be visible
+ self.assertTrue(self.gui.share_mode.server_status.file_selection.delete_button.isVisible())
+ # Click delete, delete button should still be visible since we have one more file
+ QtTest.QTest.mouseClick(self.gui.share_mode.server_status.file_selection.delete_button, QtCore.Qt.LeftButton)
+
+ rect = self.gui.share_mode.server_status.file_selection.file_list.visualItemRect(self.gui.share_mode.server_status.file_selection.file_list.item(0))
+ QtTest.QTest.mouseClick(self.gui.share_mode.server_status.file_selection.file_list.viewport(), QtCore.Qt.LeftButton, pos=rect.center())
+ self.assertTrue(self.gui.share_mode.server_status.file_selection.delete_button.isVisible())
+ QtTest.QTest.mouseClick(self.gui.share_mode.server_status.file_selection.delete_button, QtCore.Qt.LeftButton)
+
+ # No more files, the delete button should be hidden
+ self.assertFalse(self.gui.share_mode.server_status.file_selection.delete_button.isVisible())
+
+
+ def add_a_file_and_delete_using_its_delete_widget(self):
+ '''Test that we can also delete a file by clicking on its [X] widget'''
+ self.gui.share_mode.server_status.file_selection.file_list.add_file('/etc/hosts')
+ QtTest.QTest.mouseClick(self.gui.share_mode.server_status.file_selection.file_list.item(0).item_button, QtCore.Qt.LeftButton)
+ self.file_selection_widget_has_files(0)
+
+
+ def file_selection_widget_readd_files(self):
+ '''Re-add some files to the list so we can share'''
+ self.gui.share_mode.server_status.file_selection.file_list.add_file('/etc/hosts')
+ self.gui.share_mode.server_status.file_selection.file_list.add_file('/tmp/test.txt')
+ self.file_selection_widget_has_files(2)
+
+
+ def add_large_file(self):
+ '''Add a large file to the share'''
+ size = 1024*1024*155
+ with open('/tmp/large_file', 'wb') as fout:
+ fout.write(os.urandom(size))
+ self.gui.share_mode.server_status.file_selection.file_list.add_file('/tmp/large_file')
+
+
+ def add_delete_buttons_hidden(self):
+ '''Test that the add and delete buttons are hidden when the server starts'''
+ self.assertFalse(self.gui.share_mode.server_status.file_selection.add_button.isVisible())
+ self.assertFalse(self.gui.share_mode.server_status.file_selection.delete_button.isVisible())
+
+
+ def download_share(self, public_mode):
+ '''Test that we can download the share'''
+ s = socks.socksocket()
+ s.settimeout(60)
+ s.connect(('127.0.0.1', self.gui.app.port))
+
+ if public_mode:
+ path = '/download'
+ else:
+ path = '{}/download'.format(self.gui.share_mode.web.slug)
+
+ http_request = 'GET {} HTTP/1.0\r\n'.format(path)
+ http_request += 'Host: 127.0.0.1\r\n'
+ http_request += '\r\n'
+ s.sendall(http_request.encode('utf-8'))
+
+ with open('/tmp/download.zip', 'wb') as file_to_write:
+ while True:
+ data = s.recv(1024)
+ if not data:
+ break
+ file_to_write.write(data)
+ file_to_write.close()
+
+ zip = zipfile.ZipFile('/tmp/download.zip')
+ QtTest.QTest.qWait(2000)
+ self.assertEqual('onionshare', zip.read('test.txt').decode('utf-8'))
+
+ def hit_404(self, public_mode):
+ '''Test that the server stops after too many 404s, or doesn't when in public_mode'''
+ bogus_path = '/gimme'
+ url = "http://127.0.0.1:{}/{}".format(self.gui.app.port, bogus_path)
+
+ for _ in range(20):
+ r = requests.get(url)
+
+ # A nasty hack to avoid the Alert dialog that blocks the rest of the test
+ if not public_mode:
+ QtCore.QTimer.singleShot(1000, self.accept_dialog)
+
+ # In public mode, we should still be running (no rate-limiting)
+ if public_mode:
+ self.web_server_is_running()
+ # In non-public mode, we should be shut down (rate-limiting)
+ else:
+ self.web_server_is_stopped()
+
+
+ def add_button_visible(self):
+ '''Test that the add button should be visible'''
+ self.assertTrue(self.gui.share_mode.server_status.file_selection.add_button.isVisible())
+
+
+ # 'Grouped' tests follow from here
+
+ def run_all_share_mode_setup_tests(self):
+ """Tests in share mode prior to starting a share"""
+ self.click_mode(self.gui.share_mode)
+ self.file_selection_widget_has_files()
+ self.history_is_not_visible(self.gui.share_mode)
+ self.click_toggle_history(self.gui.share_mode)
+ self.history_is_visible(self.gui.share_mode)
+ self.deleting_all_files_hides_delete_button()
+ self.add_a_file_and_delete_using_its_delete_widget()
+ self.file_selection_widget_readd_files()
+
+
+ def run_all_share_mode_started_tests(self, public_mode, startup_time=2000):
+ """Tests in share mode after starting a share"""
+ self.server_working_on_start_button_pressed(self.gui.share_mode)
+ self.server_status_indicator_says_starting(self.gui.share_mode)
+ self.add_delete_buttons_hidden()
+ self.settings_button_is_hidden()
+ self.server_is_started(self.gui.share_mode, startup_time)
+ self.web_server_is_running()
+ self.have_a_slug(self.gui.share_mode, public_mode)
+ self.url_description_shown(self.gui.share_mode)
+ self.have_copy_url_button(self.gui.share_mode, public_mode)
+ self.server_status_indicator_says_started(self.gui.share_mode)
+
+
+ def run_all_share_mode_download_tests(self, public_mode, stay_open):
+ """Tests in share mode after downloading a share"""
+ self.web_page(self.gui.share_mode, 'Total size', public_mode)
+ self.download_share(public_mode)
+ self.history_widgets_present(self.gui.share_mode)
+ self.server_is_stopped(self.gui.share_mode, stay_open)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.share_mode, stay_open)
+ self.add_button_visible()
+ self.server_working_on_start_button_pressed(self.gui.share_mode)
+ self.server_is_started(self.gui.share_mode)
+ self.history_indicator(self.gui.share_mode, public_mode)
+
+
+ def run_all_share_mode_tests(self, public_mode, stay_open):
+ """End-to-end share tests"""
+ self.run_all_share_mode_setup_tests()
+ self.run_all_share_mode_started_tests(public_mode)
+ self.run_all_share_mode_download_tests(public_mode, stay_open)
+
+
+ def run_all_large_file_tests(self, public_mode, stay_open):
+ """Same as above but with a larger file"""
+ self.run_all_share_mode_setup_tests()
+ self.add_large_file()
+ self.run_all_share_mode_started_tests(public_mode, startup_time=15000)
+ self.assertTrue(self.gui.share_mode.filesize_warning.isVisible())
+ self.server_is_stopped(self.gui.share_mode, stay_open)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.share_mode, stay_open)
+
+
+ def run_all_share_mode_persistent_tests(self, public_mode, stay_open):
+ """Same as end-to-end share tests but also test the slug is the same on multiple shared"""
+ self.run_all_share_mode_setup_tests()
+ self.run_all_share_mode_started_tests(public_mode)
+ slug = self.gui.share_mode.server_status.web.slug
+ self.run_all_share_mode_download_tests(public_mode, stay_open)
+ self.have_same_slug(slug)
+
+
+ def run_all_share_mode_timer_tests(self, public_mode):
+ """Auto-stop timer tests in share mode"""
+ self.run_all_share_mode_setup_tests()
+ self.set_timeout(self.gui.share_mode, 5)
+ self.run_all_share_mode_started_tests(public_mode)
+ self.timeout_widget_hidden(self.gui.share_mode)
+ self.server_timed_out(self.gui.share_mode, 10000)
+ self.web_server_is_stopped()
+
+
+ def run_all_share_mode_unreadable_file_tests(self):
+ '''Attempt to share an unreadable file'''
+ self.run_all_share_mode_setup_tests()
+ QtCore.QTimer.singleShot(1000, self.accept_dialog)
+ self.gui.share_mode.server_status.file_selection.file_list.add_file('/tmp/nonexistent.txt')
+ self.file_selection_widget_has_files(2)
diff --git a/tests/SettingsGuiBaseTest.py b/tests/SettingsGuiBaseTest.py
new file mode 100644
index 00000000..e59a58a8
--- /dev/null
+++ b/tests/SettingsGuiBaseTest.py
@@ -0,0 +1,44 @@
+import json
+import os
+
+from onionshare import strings
+from onionshare.common import Common
+from onionshare.settings import Settings
+from onionshare.onion import Onion
+from onionshare_gui import Application, OnionShare
+from onionshare_gui.settings_dialog import SettingsDialog
+
+class SettingsGuiBaseTest(object):
+ @staticmethod
+ def set_up(test_settings):
+ '''Create the GUI'''
+ # Create our test file
+ testfile = open('/tmp/test.txt', 'w')
+ testfile.write('onionshare')
+ testfile.close()
+
+ common = Common()
+ common.settings = Settings(common)
+ common.define_css()
+ strings.load_strings(common)
+
+ # Start the Onion
+ testonion = Onion(common)
+ global qtapp
+ qtapp = Application(common)
+ app = OnionShare(common, testonion, True, 0)
+
+ for key, val in common.settings.default_settings.items():
+ if key not in test_settings:
+ test_settings[key] = val
+
+ open('/tmp/settings.json', 'w').write(json.dumps(test_settings))
+
+ gui = SettingsDialog(common, testonion, qtapp, '/tmp/settings.json', True)
+ return gui
+
+
+ @staticmethod
+ def tear_down():
+ '''Clean up after tests'''
+ os.remove('/tmp/settings.json')
diff --git a/tests/TorGuiBaseTest.py b/tests/TorGuiBaseTest.py
new file mode 100644
index 00000000..9a0bda3e
--- /dev/null
+++ b/tests/TorGuiBaseTest.py
@@ -0,0 +1,173 @@
+import json
+import os
+import requests
+import socks
+
+from PyQt5 import QtCore, QtTest
+
+from onionshare import strings
+from onionshare.common import Common
+from onionshare.settings import Settings
+from onionshare.onion import Onion
+from onionshare.web import Web
+from onionshare_gui import Application, OnionShare, OnionShareGui
+from onionshare_gui.mode.share_mode import ShareMode
+from onionshare_gui.mode.receive_mode import ReceiveMode
+
+from .GuiBaseTest import GuiBaseTest
+
+class TorGuiBaseTest(GuiBaseTest):
+ @staticmethod
+ def set_up(test_settings):
+ '''Create GUI with given settings'''
+ # Create our test file
+ testfile = open('/tmp/test.txt', 'w')
+ testfile.write('onionshare')
+ testfile.close()
+
+ # Create a test dir and files
+ if not os.path.exists('/tmp/testdir'):
+ testdir = os.mkdir('/tmp/testdir')
+ testfile = open('/tmp/testdir/test.txt', 'w')
+ testfile.write('onionshare')
+ testfile.close()
+
+ common = Common()
+ common.settings = Settings(common)
+ common.define_css()
+ strings.load_strings(common)
+
+ # Get all of the settings in test_settings
+ test_settings['connection_type'] = 'automatic'
+ test_settings['downloads_dir'] = '/tmp/OnionShare'
+ for key, val in common.settings.default_settings.items():
+ if key not in test_settings:
+ test_settings[key] = val
+
+ # Start the Onion
+ testonion = Onion(common)
+ global qtapp
+ qtapp = Application(common)
+ app = OnionShare(common, testonion, False, 0)
+
+ web = Web(common, False, False)
+ open('/tmp/settings.json', 'w').write(json.dumps(test_settings))
+
+ gui = OnionShareGui(common, testonion, qtapp, app, ['/tmp/test.txt', '/tmp/testdir'], '/tmp/settings.json', False)
+ return gui
+
+ def history_indicator(self, mode, public_mode):
+ '''Test that we can make sure the history is toggled off, do an action, and the indiciator works'''
+ # Make sure history is toggled off
+ if mode.history.isVisible():
+ QtTest.QTest.mouseClick(mode.toggle_history, QtCore.Qt.LeftButton)
+ self.assertFalse(mode.history.isVisible())
+
+ # Indicator should not be visible yet
+ self.assertFalse(mode.toggle_history.indicator_label.isVisible())
+
+ # Set up connecting to the onion
+ (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
+ session = requests.session()
+ session.proxies = {}
+ session.proxies['http'] = 'socks5h://{}:{}'.format(socks_address, socks_port)
+
+ if type(mode) == ReceiveMode:
+ # Upload a file
+ files = {'file[]': open('/tmp/test.txt', 'rb')}
+ if not public_mode:
+ path = 'http://{}/{}/upload'.format(self.gui.app.onion_host, mode.web.slug)
+ else:
+ path = 'http://{}/upload'.format(self.gui.app.onion_host)
+ response = session.post(path, files=files)
+ QtTest.QTest.qWait(4000)
+
+ if type(mode) == ShareMode:
+ # Download files
+ if public_mode:
+ path = "http://{}/download".format(self.gui.app.onion_host)
+ else:
+ path = "http://{}/{}/download".format(self.gui.app.onion_host, mode.web.slug)
+ response = session.get(path)
+ QtTest.QTest.qWait(4000)
+
+ # Indicator should be visible, have a value of "1"
+ self.assertTrue(mode.toggle_history.indicator_label.isVisible())
+ self.assertEqual(mode.toggle_history.indicator_label.text(), "1")
+
+ # Toggle history back on, indicator should be hidden again
+ QtTest.QTest.mouseClick(mode.toggle_history, QtCore.Qt.LeftButton)
+ self.assertFalse(mode.toggle_history.indicator_label.isVisible())
+
+ def have_an_onion_service(self):
+ '''Test that we have a valid Onion URL'''
+ self.assertRegex(self.gui.app.onion_host, r'[a-z2-7].onion')
+
+ def web_page(self, mode, string, public_mode):
+ '''Test that the web page contains a string'''
+ (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
+ socks.set_default_proxy(socks.SOCKS5, socks_address, socks_port)
+ s = socks.socksocket()
+ s.settimeout(60)
+ s.connect((self.gui.app.onion_host, 80))
+ if not public_mode:
+ path = '/{}'.format(mode.server_status.web.slug)
+ else:
+ path = '/'
+ http_request = 'GET {} HTTP/1.0\r\n'.format(path)
+ http_request += 'Host: {}\r\n'.format(self.gui.app.onion_host)
+ http_request += '\r\n'
+ s.sendall(http_request.encode('utf-8'))
+ with open('/tmp/webpage', 'wb') as file_to_write:
+ while True:
+ data = s.recv(1024)
+ if not data:
+ break
+ file_to_write.write(data)
+ file_to_write.close()
+ f = open('/tmp/webpage')
+ self.assertTrue(string in f.read())
+ f.close()
+
+ def have_copy_url_button(self, mode, public_mode):
+ '''Test that the Copy URL button is shown and that the clipboard is correct'''
+ self.assertTrue(mode.server_status.copy_url_button.isVisible())
+
+ QtTest.QTest.mouseClick(mode.server_status.copy_url_button, QtCore.Qt.LeftButton)
+ clipboard = self.gui.qtapp.clipboard()
+ if public_mode:
+ self.assertEqual(clipboard.text(), 'http://{}'.format(self.gui.app.onion_host))
+ else:
+ self.assertEqual(clipboard.text(), 'http://{}/{}'.format(self.gui.app.onion_host, mode.server_status.web.slug))
+
+ def cancel_the_share(self, mode):
+ '''Test that we can cancel this share before it's started up '''
+ self.server_working_on_start_button_pressed(self.gui.share_mode)
+ self.server_status_indicator_says_starting(self.gui.share_mode)
+ self.add_delete_buttons_hidden()
+ self.settings_button_is_hidden()
+ QtTest.QTest.mousePress(mode.server_status.server_button, QtCore.Qt.LeftButton)
+ QtTest.QTest.qWait(1000)
+ QtTest.QTest.mouseRelease(mode.server_status.server_button, QtCore.Qt.LeftButton)
+ self.assertEqual(mode.server_status.status, 0)
+ self.server_is_stopped(self.gui.share_mode, False)
+ self.web_server_is_stopped()
+
+
+ # Stealth tests
+ def copy_have_hidserv_auth_button(self, mode):
+ '''Test that the Copy HidservAuth button is shown'''
+ self.assertTrue(mode.server_status.copy_hidservauth_button.isVisible())
+
+ def hidserv_auth_string(self):
+ '''Test the validity of the HidservAuth string'''
+ self.assertRegex(self.gui.app.auth_string, r'HidServAuth {} [a-zA-Z1-9]'.format(self.gui.app.onion_host))
+
+
+
+ # Miscellaneous tests
+ def tor_killed_statusbar_message_shown(self, mode):
+ '''Test that the status bar message shows Tor was disconnected'''
+ self.gui.app.onion.c = None
+ QtTest.QTest.qWait(1000)
+ self.assertTrue(mode.status_bar.currentMessage(), strings._('gui_tor_connection_lost'))
diff --git a/tests/TorGuiReceiveTest.py b/tests/TorGuiReceiveTest.py
new file mode 100644
index 00000000..a21dd4fc
--- /dev/null
+++ b/tests/TorGuiReceiveTest.py
@@ -0,0 +1,59 @@
+import os
+import requests
+from PyQt5 import QtTest
+from .TorGuiBaseTest import TorGuiBaseTest
+
+class TorGuiReceiveTest(TorGuiBaseTest):
+
+ def upload_file(self, public_mode, file_to_upload, expected_file):
+ '''Test that we can upload the file'''
+ (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
+ session = requests.session()
+ session.proxies = {}
+ session.proxies['http'] = 'socks5h://{}:{}'.format(socks_address, socks_port)
+ files = {'file[]': open(file_to_upload, 'rb')}
+ if not public_mode:
+ path = 'http://{}/{}/upload'.format(self.gui.app.onion_host, self.gui.receive_mode.web.slug)
+ else:
+ path = 'http://{}/upload'.format(self.gui.app.onion_host)
+ response = session.post(path, files=files)
+ QtTest.QTest.qWait(4000)
+ self.assertTrue(os.path.isfile(expected_file))
+
+
+ # 'Grouped' tests follow from here
+
+ def run_all_receive_mode_tests(self, public_mode, receive_allow_receiver_shutdown):
+ '''Run a full suite of tests in Receive mode'''
+ self.click_mode(self.gui.receive_mode)
+ self.history_is_not_visible(self.gui.receive_mode)
+ self.click_toggle_history(self.gui.receive_mode)
+ self.history_is_visible(self.gui.receive_mode)
+ self.server_working_on_start_button_pressed(self.gui.receive_mode)
+ self.server_status_indicator_says_starting(self.gui.receive_mode)
+ self.settings_button_is_hidden()
+ self.server_is_started(self.gui.receive_mode, startup_time=45000)
+ self.web_server_is_running()
+ self.have_an_onion_service()
+ self.have_a_slug(self.gui.receive_mode, public_mode)
+ self.url_description_shown(self.gui.receive_mode)
+ self.have_copy_url_button(self.gui.receive_mode, public_mode)
+ self.server_status_indicator_says_started(self.gui.receive_mode)
+ self.web_page(self.gui.receive_mode, 'Select the files you want to send, then click', public_mode)
+ self.upload_file(public_mode, '/tmp/test.txt', '/tmp/OnionShare/test.txt')
+ self.history_widgets_present(self.gui.receive_mode)
+ self.counter_incremented(self.gui.receive_mode, 1)
+ self.upload_file(public_mode, '/tmp/test.txt', '/tmp/OnionShare/test-2.txt')
+ self.counter_incremented(self.gui.receive_mode, 2)
+ self.upload_file(public_mode, '/tmp/testdir/test', '/tmp/OnionShare/test')
+ self.counter_incremented(self.gui.receive_mode, 3)
+ self.upload_file(public_mode, '/tmp/testdir/test', '/tmp/OnionShare/test-2')
+ self.counter_incremented(self.gui.receive_mode, 4)
+ self.history_indicator(self.gui.receive_mode, public_mode)
+ self.server_is_stopped(self.gui.receive_mode, False)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.receive_mode, False)
+ self.server_working_on_start_button_pressed(self.gui.receive_mode)
+ self.server_is_started(self.gui.receive_mode, startup_time=45000)
+ self.history_indicator(self.gui.receive_mode, public_mode)
+
diff --git a/tests/TorGuiShareTest.py b/tests/TorGuiShareTest.py
new file mode 100644
index 00000000..53641dce
--- /dev/null
+++ b/tests/TorGuiShareTest.py
@@ -0,0 +1,95 @@
+import requests
+import zipfile
+from PyQt5 import QtTest
+from .TorGuiBaseTest import TorGuiBaseTest
+from .GuiShareTest import GuiShareTest
+
+class TorGuiShareTest(TorGuiBaseTest, GuiShareTest):
+ def download_share(self, public_mode):
+ '''Test downloading a share'''
+ # Set up connecting to the onion
+ (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
+ session = requests.session()
+ session.proxies = {}
+ session.proxies['http'] = 'socks5h://{}:{}'.format(socks_address, socks_port)
+
+ # Download files
+ if public_mode:
+ path = "http://{}/download".format(self.gui.app.onion_host)
+ else:
+ path = "http://{}/{}/download".format(self.gui.app.onion_host, self.gui.share_mode.web.slug)
+ response = session.get(path, stream=True)
+ QtTest.QTest.qWait(4000)
+
+ if response.status_code == 200:
+ with open('/tmp/download.zip', 'wb') as file_to_write:
+ for chunk in response.iter_content(chunk_size=128):
+ file_to_write.write(chunk)
+ file_to_write.close()
+ zip = zipfile.ZipFile('/tmp/download.zip')
+ QtTest.QTest.qWait(4000)
+ self.assertEqual('onionshare', zip.read('test.txt').decode('utf-8'))
+
+
+ # Persistence tests
+ def have_same_onion(self, onion):
+ '''Test that we have the same onion'''
+ self.assertEqual(self.gui.app.onion_host, onion)
+
+ # legacy v2 onion test
+ def have_v2_onion(self):
+ '''Test that the onion is a v2 style onion'''
+ self.assertRegex(self.gui.app.onion_host, r'[a-z2-7].onion')
+ self.assertEqual(len(self.gui.app.onion_host), 22)
+
+ # 'Grouped' tests follow from here
+
+ def run_all_share_mode_started_tests(self, public_mode):
+ '''Tests in share mode after starting a share'''
+ self.server_working_on_start_button_pressed(self.gui.share_mode)
+ self.server_status_indicator_says_starting(self.gui.share_mode)
+ self.add_delete_buttons_hidden()
+ self.settings_button_is_hidden()
+ self.server_is_started(self.gui.share_mode, startup_time=45000)
+ self.web_server_is_running()
+ self.have_an_onion_service()
+ self.have_a_slug(self.gui.share_mode, public_mode)
+ self.url_description_shown(self.gui.share_mode)
+ self.have_copy_url_button(self.gui.share_mode, public_mode)
+ self.server_status_indicator_says_started(self.gui.share_mode)
+
+
+ def run_all_share_mode_download_tests(self, public_mode, stay_open):
+ """Tests in share mode after downloading a share"""
+ self.web_page(self.gui.share_mode, 'Total size', public_mode)
+ self.download_share(public_mode)
+ self.history_widgets_present(self.gui.share_mode)
+ self.server_is_stopped(self.gui.share_mode, stay_open)
+ self.web_server_is_stopped()
+ self.server_status_indicator_says_closed(self.gui.share_mode, stay_open)
+ self.add_button_visible()
+ self.server_working_on_start_button_pressed(self.gui.share_mode)
+ self.server_is_started(self.gui.share_mode, startup_time=45000)
+ self.history_indicator(self.gui.share_mode, public_mode)
+
+
+ def run_all_share_mode_persistent_tests(self, public_mode, stay_open):
+ """Same as end-to-end share tests but also test the slug is the same on multiple shared"""
+ self.run_all_share_mode_setup_tests()
+ self.run_all_share_mode_started_tests(public_mode)
+ slug = self.gui.share_mode.server_status.web.slug
+ onion = self.gui.app.onion_host
+ self.run_all_share_mode_download_tests(public_mode, stay_open)
+ self.have_same_onion(onion)
+ self.have_same_slug(slug)
+
+
+ def run_all_share_mode_timer_tests(self, public_mode):
+ """Auto-stop timer tests in share mode"""
+ self.run_all_share_mode_setup_tests()
+ self.set_timeout(self.gui.share_mode, 120)
+ self.run_all_share_mode_started_tests(public_mode)
+ self.timeout_widget_hidden(self.gui.share_mode)
+ self.server_timed_out(self.gui.share_mode, 125000)
+ self.web_server_is_stopped()
+
diff --git a/test/__init__.py b/tests/__init__.py
index e69de29b..e69de29b 100644
--- a/test/__init__.py
+++ b/tests/__init__.py
diff --git a/test/conftest.py b/tests/conftest.py
index 8f10162b..688b22d8 100644
--- a/test/conftest.py
+++ b/tests/conftest.py
@@ -8,7 +8,23 @@ import tempfile
import pytest
-from onionshare import common
+from onionshare import common, web, settings, strings
+
+def pytest_addoption(parser):
+ parser.addoption(
+ "--runtor", action="store_true", default=False, help="run tor tests"
+ )
+
+
+def pytest_collection_modifyitems(config, items):
+ if config.getoption("--runtor"):
+ # --runtor given in cli: do not skip tor tests
+ return
+ skip_tor = pytest.mark.skip(reason="need --runtor option to run")
+ for item in items:
+ if "tor" in item.keywords:
+ item.add_marker(skip_tor)
+
@pytest.fixture
def temp_dir_1024():
@@ -64,8 +80,9 @@ def temp_file_1024_delete():
# pytest > 2.9 only needs @pytest.fixture
@pytest.yield_fixture(scope='session')
def custom_zw():
- zw = common.ZipWriter(
- zip_filename=common.random_string(4, 6),
+ zw = web.share_mode.ZipWriter(
+ common.Common(),
+ zip_filename=common.Common.random_string(4, 6),
processed_size_callback=lambda _: 'custom_callback'
)
yield zw
@@ -76,7 +93,7 @@ def custom_zw():
# pytest > 2.9 only needs @pytest.fixture
@pytest.yield_fixture(scope='session')
def default_zw():
- zw = common.ZipWriter()
+ zw = web.share_mode.ZipWriter(common.Common())
yield zw
zw.close()
tmp_dir = os.path.dirname(zw.zip_filename)
@@ -119,16 +136,6 @@ def platform_windows(monkeypatch):
@pytest.fixture
-def set_debug_false(monkeypatch):
- monkeypatch.setattr('onionshare.common.debug', False)
-
-
-@pytest.fixture
-def set_debug_true(monkeypatch):
- monkeypatch.setattr('onionshare.common.debug', True)
-
-
-@pytest.fixture
def sys_argv_sys_prefix(monkeypatch):
monkeypatch.setattr('sys.argv', [sys.prefix])
@@ -157,3 +164,14 @@ def time_time_100(monkeypatch):
@pytest.fixture
def time_strftime(monkeypatch):
monkeypatch.setattr('time.strftime', lambda _: 'Jun 06 2013 11:05:00')
+
+@pytest.fixture
+def common_obj():
+ return common.Common()
+
+@pytest.fixture
+def settings_obj(sys_onionshare_dev_mode, platform_linux):
+ _common = common.Common()
+ _common.version = 'DUMMY_VERSION_1.2.3'
+ strings.load_strings(_common)
+ return settings.Settings(_common)
diff --git a/tests/local_onionshare_404_public_mode_skips_ratelimit_test.py b/tests/local_onionshare_404_public_mode_skips_ratelimit_test.py
new file mode 100644
index 00000000..11feb6f0
--- /dev/null
+++ b/tests/local_onionshare_404_public_mode_skips_ratelimit_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class Local404PublicModeRateLimitTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "close_after_first_download": False,
+ "public_mode": True
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(True, True)
+ self.hit_404(True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_404_triggers_ratelimit_test.py b/tests/local_onionshare_404_triggers_ratelimit_test.py
new file mode 100644
index 00000000..ad49c3f8
--- /dev/null
+++ b/tests/local_onionshare_404_triggers_ratelimit_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class Local404RateLimitTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "close_after_first_download": False
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, True)
+ self.hit_404(False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_quitting_during_share_prompts_warning_test.py b/tests/local_onionshare_quitting_during_share_prompts_warning_test.py
new file mode 100644
index 00000000..d2fe4986
--- /dev/null
+++ b/tests/local_onionshare_quitting_during_share_prompts_warning_test.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+import unittest
+from PyQt5 import QtCore, QtTest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalQuittingDuringSharePromptsWarningTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "close_after_first_download": False
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, True)
+ # Prepare our auto-accept of prompt
+ QtCore.QTimer.singleShot(5000, self.accept_dialog)
+ # Try to close the app
+ self.gui.close()
+ # Server should still be running (we've been prompted first)
+ self.server_is_started(self.gui.share_mode, 0)
+ self.web_server_is_running()
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_receive_mode_sender_closed_test.py b/tests/local_onionshare_receive_mode_sender_closed_test.py
new file mode 100644
index 00000000..e177d2ef
--- /dev/null
+++ b/tests/local_onionshare_receive_mode_sender_closed_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiReceiveTest import GuiReceiveTest
+
+class LocalReceiveModeSenderClosedTest(unittest.TestCase, GuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = GuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiReceiveTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_tests(False, True)
+ self.run_receive_mode_sender_closed_tests(False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_receive_mode_timer_test.py b/tests/local_onionshare_receive_mode_timer_test.py
new file mode 100644
index 00000000..88002f94
--- /dev/null
+++ b/tests/local_onionshare_receive_mode_timer_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiReceiveTest import GuiReceiveTest
+
+class LocalReceiveModeTimerTest(unittest.TestCase, GuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": False,
+ "shutdown_timeout": True,
+ }
+ cls.gui = GuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiReceiveTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_timer_tests(False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_receive_mode_upload_non_writable_dir_test.py b/tests/local_onionshare_receive_mode_upload_non_writable_dir_test.py
new file mode 100644
index 00000000..7d7b2780
--- /dev/null
+++ b/tests/local_onionshare_receive_mode_upload_non_writable_dir_test.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiReceiveTest import GuiReceiveTest
+
+class LocalReceiveModeUnwritableTest(unittest.TestCase, GuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = GuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiReceiveTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_unwritable_dir_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_receive_mode_upload_public_mode_non_writable_dir_test.py b/tests/local_onionshare_receive_mode_upload_public_mode_non_writable_dir_test.py
new file mode 100644
index 00000000..cdc4e62a
--- /dev/null
+++ b/tests/local_onionshare_receive_mode_upload_public_mode_non_writable_dir_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiReceiveTest import GuiReceiveTest
+
+class LocalReceivePublicModeUnwritableTest(unittest.TestCase, GuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": True,
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = GuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiReceiveTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_unwritable_dir_tests(True, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_receive_mode_upload_public_mode_test.py b/tests/local_onionshare_receive_mode_upload_public_mode_test.py
new file mode 100644
index 00000000..bedb7ae2
--- /dev/null
+++ b/tests/local_onionshare_receive_mode_upload_public_mode_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiReceiveTest import GuiReceiveTest
+
+class LocalReceiveModePublicModeTest(unittest.TestCase, GuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": True,
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = GuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiReceiveTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_tests(True, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_receive_mode_upload_test.py b/tests/local_onionshare_receive_mode_upload_test.py
new file mode 100644
index 00000000..82baf3fd
--- /dev/null
+++ b/tests/local_onionshare_receive_mode_upload_test.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiReceiveTest import GuiReceiveTest
+
+class LocalReceiveModeTest(unittest.TestCase, GuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = GuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiReceiveTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_settings_dialog_test.py b/tests/local_onionshare_settings_dialog_test.py
new file mode 100644
index 00000000..c1e48122
--- /dev/null
+++ b/tests/local_onionshare_settings_dialog_test.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+import json
+import unittest
+from PyQt5 import QtCore, QtTest
+
+from onionshare import strings
+from .SettingsGuiBaseTest import SettingsGuiBaseTest
+
+class SettingsGuiTest(unittest.TestCase, SettingsGuiBaseTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "no_bridges": False,
+ "tor_bridges_use_custom_bridges": "Bridge 1.2.3.4:56 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\nBridge 5.6.7.8:910 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\nBridge 11.12.13.14:1516 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n",
+ }
+ cls.gui = SettingsGuiBaseTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ SettingsGuiBaseTest.tear_down()
+
+ def test_gui(self):
+ self.gui.show()
+ # Window is shown
+ self.assertTrue(self.gui.isVisible())
+ self.assertEqual(self.gui.windowTitle(), strings._('gui_settings_window_title'))
+ # Check for updates button is hidden
+ self.assertFalse(self.gui.check_for_updates_button.isVisible())
+
+ # public mode is off
+ self.assertFalse(self.gui.public_mode_checkbox.isChecked())
+ # enable public mode
+ QtTest.QTest.mouseClick(self.gui.public_mode_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.public_mode_checkbox.height()/2))
+ self.assertTrue(self.gui.public_mode_checkbox.isChecked())
+
+ # shutdown timer is off
+ self.assertFalse(self.gui.shutdown_timeout_checkbox.isChecked())
+ # enable shutdown timer
+ QtTest.QTest.mouseClick(self.gui.shutdown_timeout_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.shutdown_timeout_checkbox.height()/2))
+ self.assertTrue(self.gui.shutdown_timeout_checkbox.isChecked())
+
+ # legacy mode checkbox and related widgets
+ # legacy mode is off
+ self.assertFalse(self.gui.use_legacy_v2_onions_checkbox.isChecked())
+ # persistence, stealth is hidden and disabled
+ self.assertFalse(self.gui.save_private_key_widget.isVisible())
+ self.assertFalse(self.gui.save_private_key_checkbox.isChecked())
+ self.assertFalse(self.gui.use_stealth_widget.isVisible())
+ self.assertFalse(self.gui.stealth_checkbox.isChecked())
+ self.assertFalse(self.gui.hidservauth_copy_button.isVisible())
+
+ # enable legacy mode
+ QtTest.QTest.mouseClick(self.gui.use_legacy_v2_onions_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.use_legacy_v2_onions_checkbox.height()/2))
+ self.assertTrue(self.gui.use_legacy_v2_onions_checkbox.isChecked())
+ self.assertTrue(self.gui.save_private_key_checkbox.isVisible())
+ self.assertTrue(self.gui.use_stealth_widget.isVisible())
+ # enable persistent mode
+ QtTest.QTest.mouseClick(self.gui.save_private_key_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.save_private_key_checkbox.height()/2))
+ self.assertTrue(self.gui.save_private_key_checkbox.isChecked())
+ # enable stealth mode
+ QtTest.QTest.mouseClick(self.gui.stealth_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.stealth_checkbox.height()/2))
+ self.assertTrue(self.gui.stealth_checkbox.isChecked())
+ # now that stealth, persistence are enabled, we can't turn off legacy mode
+ self.assertFalse(self.gui.use_legacy_v2_onions_checkbox.isEnabled())
+ # disable stealth, persistence
+ QtTest.QTest.mouseClick(self.gui.save_private_key_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.save_private_key_checkbox.height()/2))
+ QtTest.QTest.mouseClick(self.gui.stealth_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.stealth_checkbox.height()/2))
+ # legacy mode checkbox is enabled again
+ self.assertTrue(self.gui.use_legacy_v2_onions_checkbox.isEnabled())
+ # uncheck legacy mode
+ QtTest.QTest.mouseClick(self.gui.use_legacy_v2_onions_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.use_legacy_v2_onions_checkbox.height()/2))
+ # legacy options hidden again
+ self.assertFalse(self.gui.save_private_key_widget.isVisible())
+ self.assertFalse(self.gui.use_stealth_widget.isVisible())
+ # enable them all again so that we can see the setting stick in settings.json
+ QtTest.QTest.mouseClick(self.gui.use_legacy_v2_onions_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.use_legacy_v2_onions_checkbox.height()/2))
+ QtTest.QTest.mouseClick(self.gui.save_private_key_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.save_private_key_checkbox.height()/2))
+ QtTest.QTest.mouseClick(self.gui.stealth_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.stealth_checkbox.height()/2))
+
+
+ # stay open toggled off, on
+ self.assertTrue(self.gui.close_after_first_download_checkbox.isChecked())
+ QtTest.QTest.mouseClick(self.gui.close_after_first_download_checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.close_after_first_download_checkbox.height()/2))
+ self.assertFalse(self.gui.close_after_first_download_checkbox.isChecked())
+
+ # receive mode
+ self.gui.downloads_dir_lineedit.setText('/tmp/OnionShareSettingsTest')
+
+
+ # bundled mode is enabled
+ self.assertTrue(self.gui.connection_type_bundled_radio.isEnabled())
+ self.assertTrue(self.gui.connection_type_bundled_radio.isChecked())
+ # bridge options are shown
+ self.assertTrue(self.gui.connection_type_bridges_radio_group.isVisible())
+ # bridges are set to custom
+ self.assertFalse(self.gui.tor_bridges_no_bridges_radio.isChecked())
+ self.assertTrue(self.gui.tor_bridges_use_custom_radio.isChecked())
+
+ # switch to obfs4
+ QtTest.QTest.mouseClick(self.gui.tor_bridges_use_obfs4_radio, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.tor_bridges_use_obfs4_radio.height()/2))
+ self.assertTrue(self.gui.tor_bridges_use_obfs4_radio.isChecked())
+
+ # custom bridges are hidden
+ self.assertFalse(self.gui.tor_bridges_use_custom_textbox_options.isVisible())
+ # other modes are unchecked but enabled
+ self.assertTrue(self.gui.connection_type_automatic_radio.isEnabled())
+ self.assertTrue(self.gui.connection_type_control_port_radio.isEnabled())
+ self.assertTrue(self.gui.connection_type_socket_file_radio.isEnabled())
+ self.assertFalse(self.gui.connection_type_automatic_radio.isChecked())
+ self.assertFalse(self.gui.connection_type_control_port_radio.isChecked())
+ self.assertFalse(self.gui.connection_type_socket_file_radio.isChecked())
+
+ # enable automatic mode
+ QtTest.QTest.mouseClick(self.gui.connection_type_automatic_radio, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.connection_type_automatic_radio.height()/2))
+ self.assertTrue(self.gui.connection_type_automatic_radio.isChecked())
+ # bundled is off
+ self.assertFalse(self.gui.connection_type_bundled_radio.isChecked())
+ # bridges are hidden
+ self.assertFalse(self.gui.connection_type_bridges_radio_group.isVisible())
+
+ # auth type is hidden in bundled or automatic mode
+ self.assertFalse(self.gui.authenticate_no_auth_radio.isVisible())
+ self.assertFalse(self.gui.authenticate_password_radio.isVisible())
+
+ # enable control port mode
+ QtTest.QTest.mouseClick(self.gui.connection_type_control_port_radio, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.connection_type_control_port_radio.height()/2))
+ self.assertTrue(self.gui.connection_type_control_port_radio.isChecked())
+ # automatic is off
+ self.assertFalse(self.gui.connection_type_automatic_radio.isChecked())
+ # auth options appear
+ self.assertTrue(self.gui.authenticate_no_auth_radio.isVisible())
+ self.assertTrue(self.gui.authenticate_password_radio.isVisible())
+
+ # enable socket mode
+ QtTest.QTest.mouseClick(self.gui.connection_type_socket_file_radio, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.connection_type_socket_file_radio.height()/2))
+ self.assertTrue(self.gui.connection_type_socket_file_radio.isChecked())
+ # control port is off
+ self.assertFalse(self.gui.connection_type_control_port_radio.isChecked())
+ # auth options are still present
+ self.assertTrue(self.gui.authenticate_no_auth_radio.isVisible())
+ self.assertTrue(self.gui.authenticate_password_radio.isVisible())
+
+ # re-enable bundled mode
+ QtTest.QTest.mouseClick(self.gui.connection_type_bundled_radio, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.connection_type_bundled_radio.height()/2))
+ # go back to custom bridges
+ QtTest.QTest.mouseClick(self.gui.tor_bridges_use_custom_radio, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,self.gui.tor_bridges_use_custom_radio.height()/2))
+ self.assertTrue(self.gui.tor_bridges_use_custom_radio.isChecked())
+ self.assertTrue(self.gui.tor_bridges_use_custom_textbox.isVisible())
+ self.assertFalse(self.gui.tor_bridges_use_obfs4_radio.isChecked())
+ self.gui.tor_bridges_use_custom_textbox.setPlainText('94.242.249.2:83 E25A95F1DADB739F0A83EB0223A37C02FD519306\n148.251.90.59:7510 019F727CA6DCA6CA5C90B55E477B7D87981E75BC\n93.80.47.217:41727 A6A0D497D98097FCFE91D639548EE9E34C15CDD3')
+
+ # Test that the Settings Dialog can save the settings and close itself
+ QtTest.QTest.mouseClick(self.gui.save_button, QtCore.Qt.LeftButton)
+ self.assertFalse(self.gui.isVisible())
+
+ # Test our settings are reflected in the settings json
+ with open('/tmp/settings.json') as f:
+ data = json.load(f)
+
+ self.assertTrue(data["public_mode"])
+ self.assertTrue(data["shutdown_timeout"])
+ self.assertTrue(data["use_legacy_v2_onions"])
+ self.assertTrue(data["save_private_key"])
+ self.assertTrue(data["use_stealth"])
+ self.assertEqual(data["downloads_dir"], "/tmp/OnionShareSettingsTest")
+ self.assertFalse(data["close_after_first_download"])
+ self.assertEqual(data["connection_type"], "bundled")
+ self.assertFalse(data["tor_bridges_use_obfs4"])
+ self.assertEqual(data["tor_bridges_use_custom_bridges"], "Bridge 94.242.249.2:83 E25A95F1DADB739F0A83EB0223A37C02FD519306\nBridge 148.251.90.59:7510 019F727CA6DCA6CA5C90B55E477B7D87981E75BC\nBridge 93.80.47.217:41727 A6A0D497D98097FCFE91D639548EE9E34C15CDD3\n")
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_download_public_mode_test.py b/tests/local_onionshare_share_mode_download_public_mode_test.py
new file mode 100644
index 00000000..d6dff13a
--- /dev/null
+++ b/tests/local_onionshare_share_mode_download_public_mode_test.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModePublicModeTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": True,
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(True, False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_download_stay_open_test.py b/tests/local_onionshare_share_mode_download_stay_open_test.py
new file mode 100644
index 00000000..54d6de51
--- /dev/null
+++ b/tests/local_onionshare_share_mode_download_stay_open_test.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModeStayOpenTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "close_after_first_download": False,
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_download_test.py b/tests/local_onionshare_share_mode_download_test.py
new file mode 100644
index 00000000..ff182740
--- /dev/null
+++ b/tests/local_onionshare_share_mode_download_test.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModeTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_large_download_test.py b/tests/local_onionshare_share_mode_large_download_test.py
new file mode 100644
index 00000000..46e6df28
--- /dev/null
+++ b/tests/local_onionshare_share_mode_large_download_test.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModeLargeDownloadTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_large_file_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_slug_persistent_test.py b/tests/local_onionshare_share_mode_slug_persistent_test.py
new file mode 100644
index 00000000..a1cc6972
--- /dev/null
+++ b/tests/local_onionshare_share_mode_slug_persistent_test.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModePersistentSlugTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": False,
+ "slug": "",
+ "save_private_key": True,
+ "close_after_first_download": False,
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_persistent_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_timer_test.py b/tests/local_onionshare_share_mode_timer_test.py
new file mode 100644
index 00000000..41a6268d
--- /dev/null
+++ b/tests/local_onionshare_share_mode_timer_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModeTimerTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": False,
+ "shutdown_timeout": True,
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_timer_tests(False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_timer_too_short_test.py b/tests/local_onionshare_share_mode_timer_too_short_test.py
new file mode 100644
index 00000000..41c30883
--- /dev/null
+++ b/tests/local_onionshare_share_mode_timer_too_short_test.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+import unittest
+from PyQt5 import QtCore, QtTest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModeTimerTooShortTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": False,
+ "shutdown_timeout": True,
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_setup_tests()
+ # Set a low timeout
+ self.set_timeout(self.gui.share_mode, 2)
+ QtTest.QTest.qWait(3000)
+ QtCore.QTimer.singleShot(4000, self.accept_dialog)
+ QtTest.QTest.mouseClick(self.gui.share_mode.server_status.server_button, QtCore.Qt.LeftButton)
+ self.assertEqual(self.gui.share_mode.server_status.status, 0)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/local_onionshare_share_mode_unreadable_file_test.py b/tests/local_onionshare_share_mode_unreadable_file_test.py
new file mode 100644
index 00000000..38a0e847
--- /dev/null
+++ b/tests/local_onionshare_share_mode_unreadable_file_test.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+import unittest
+
+from .GuiShareTest import GuiShareTest
+
+class LocalShareModeUnReadableFileTest(unittest.TestCase, GuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ }
+ cls.gui = GuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ GuiShareTest.tear_down()
+
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_unreadable_file_tests()
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_790_cancel_on_second_share_test.py b/tests/onionshare_790_cancel_on_second_share_test.py
new file mode 100644
index 00000000..b144edf3
--- /dev/null
+++ b/tests/onionshare_790_cancel_on_second_share_test.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+# Tests #790 regression
+class ShareModeCancelSecondShareTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "close_after_first_download": True
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, False)
+ self.cancel_the_share(self.gui.share_mode)
+ self.server_is_stopped(self.gui.share_mode, False)
+ self.web_server_is_stopped()
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_receive_mode_upload_public_mode_test.py b/tests/onionshare_receive_mode_upload_public_mode_test.py
new file mode 100644
index 00000000..275e5953
--- /dev/null
+++ b/tests/onionshare_receive_mode_upload_public_mode_test.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiReceiveTest import TorGuiReceiveTest
+
+class ReceiveModeTest(unittest.TestCase, TorGuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": True,
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = TorGuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiReceiveTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_tests(True, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_receive_mode_upload_test.py b/tests/onionshare_receive_mode_upload_test.py
new file mode 100644
index 00000000..f9914659
--- /dev/null
+++ b/tests/onionshare_receive_mode_upload_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiReceiveTest import TorGuiReceiveTest
+
+class ReceiveModeTest(unittest.TestCase, TorGuiReceiveTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "receive_allow_receiver_shutdown": True
+ }
+ cls.gui = TorGuiReceiveTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiReceiveTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_receive_mode_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_cancel_share_test.py b/tests/onionshare_share_mode_cancel_share_test.py
new file mode 100644
index 00000000..5f4d6fb3
--- /dev/null
+++ b/tests/onionshare_share_mode_cancel_share_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeCancelTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_setup_tests()
+ self.cancel_the_share(self.gui.share_mode)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_download_public_mode_test.py b/tests/onionshare_share_mode_download_public_mode_test.py
new file mode 100644
index 00000000..672603ce
--- /dev/null
+++ b/tests/onionshare_share_mode_download_public_mode_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModePublicModeTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": True,
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(True, False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_download_stay_open_test.py b/tests/onionshare_share_mode_download_stay_open_test.py
new file mode 100644
index 00000000..e7e64083
--- /dev/null
+++ b/tests/onionshare_share_mode_download_stay_open_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeStayOpenTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "close_after_first_download": False,
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_download_test.py b/tests/onionshare_share_mode_download_test.py
new file mode 100644
index 00000000..7d414e5d
--- /dev/null
+++ b/tests/onionshare_share_mode_download_test.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_persistent_test.py b/tests/onionshare_share_mode_persistent_test.py
new file mode 100644
index 00000000..86b61a81
--- /dev/null
+++ b/tests/onionshare_share_mode_persistent_test.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModePersistentSlugTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "use_legacy_v2_onions": True,
+ "public_mode": False,
+ "slug": "",
+ "save_private_key": True,
+ "close_after_first_download": False,
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_persistent_tests(False, True)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_stealth_test.py b/tests/onionshare_share_mode_stealth_test.py
new file mode 100644
index 00000000..b16669e6
--- /dev/null
+++ b/tests/onionshare_share_mode_stealth_test.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeStealthTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "use_legacy_v2_onions": True,
+ "use_stealth": True,
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_setup_tests()
+ self.run_all_share_mode_started_tests(False)
+ self.hidserv_auth_string()
+ self.copy_have_hidserv_auth_button(self.gui.share_mode)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_timer_test.py b/tests/onionshare_share_mode_timer_test.py
new file mode 100644
index 00000000..a13d2d80
--- /dev/null
+++ b/tests/onionshare_share_mode_timer_test.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeTimerTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "public_mode": False,
+ "shutdown_timeout": True,
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_timer_tests(False)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_tor_connection_killed_test.py b/tests/onionshare_share_mode_tor_connection_killed_test.py
new file mode 100644
index 00000000..62513a12
--- /dev/null
+++ b/tests/onionshare_share_mode_tor_connection_killed_test.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeTorConnectionKilledTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_setup_tests()
+ self.run_all_share_mode_started_tests(False)
+ self.tor_killed_statusbar_message_shown(self.gui.share_mode)
+ self.server_is_stopped(self.gui.share_mode, False)
+ self.web_server_is_stopped()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/onionshare_share_mode_v2_onion_test.py b/tests/onionshare_share_mode_v2_onion_test.py
new file mode 100644
index 00000000..c932abf9
--- /dev/null
+++ b/tests/onionshare_share_mode_v2_onion_test.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+import pytest
+import unittest
+
+from .TorGuiShareTest import TorGuiShareTest
+
+class ShareModeV2OnionTest(unittest.TestCase, TorGuiShareTest):
+ @classmethod
+ def setUpClass(cls):
+ test_settings = {
+ "use_legacy_v2_onions": True,
+ }
+ cls.gui = TorGuiShareTest.set_up(test_settings)
+
+ @classmethod
+ def tearDownClass(cls):
+ TorGuiShareTest.tear_down()
+
+ @pytest.mark.tor
+ def test_gui(self):
+ self.run_all_common_setup_tests()
+ self.run_all_share_mode_tests(False, False)
+ self.have_v2_onion()
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/test_helpers.py b/tests/test_helpers.py
index b0e94a5c..321afbb7 100644
--- a/test/test_helpers.py
+++ b/tests/test_helpers.py
@@ -1,7 +1,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
diff --git a/test/test_onionshare.py b/tests/test_onionshare.py
index b9e50ba1..7592a777 100644
--- a/test/test_onionshare.py
+++ b/tests/test_onionshare.py
@@ -1,7 +1,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -22,6 +22,7 @@ import os
import pytest
from onionshare import OnionShare
+from onionshare.common import Common
class MyOnion:
@@ -37,7 +38,8 @@ class MyOnion:
@pytest.fixture
def onionshare_obj():
- return OnionShare(MyOnion())
+ common = Common()
+ return OnionShare(common, MyOnion())
class TestOnionShare:
@@ -47,7 +49,6 @@ class TestOnionShare:
assert onionshare_obj.stealth is None
assert onionshare_obj.cleanup_filenames == []
assert onionshare_obj.local_only is False
- assert onionshare_obj.stay_open is False
def test_set_stealth_true(self, onionshare_obj):
onionshare_obj.set_stealth(True)
diff --git a/test/test_onionshare_common.py b/tests/test_onionshare_common.py
index d3c78710..d70f2c0e 100644
--- a/test/test_onionshare_common.py
+++ b/tests/test_onionshare_common.py
@@ -1,7 +1,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -29,17 +29,16 @@ import zipfile
import pytest
-from onionshare import common
-
-DEFAULT_ZW_FILENAME_REGEX = re.compile(r'^onionshare_[a-z2-7]{6}.zip$')
LOG_MSG_REGEX = re.compile(r"""
^\[Jun\ 06\ 2013\ 11:05:00\]
\ TestModule\.<function\ TestLog\.test_output\.<locals>\.dummy_func
\ at\ 0x[a-f0-9]+>(:\ TEST_MSG)?$""", re.VERBOSE)
-RANDOM_STR_REGEX = re.compile(r'^[a-z2-7]+$')
SLUG_REGEX = re.compile(r'^([a-z]+)(-[a-z]+)?-([a-z]+)(-[a-z]+)?$')
+# TODO: Improve the Common tests to test it all as a single class
+
+
class TestBuildSlug:
@pytest.mark.parametrize('test_input,expected', (
# VALID, two lowercase words, separated by a hyphen
@@ -79,17 +78,17 @@ class TestBuildSlug:
assert bool(SLUG_REGEX.match(test_input)) == expected
- def test_build_slug_unique(self, sys_onionshare_dev_mode):
- assert common.build_slug() != common.build_slug()
+ def test_build_slug_unique(self, common_obj, sys_onionshare_dev_mode):
+ assert common_obj.build_slug() != common_obj.build_slug()
class TestDirSize:
- def test_temp_dir_size(self, temp_dir_1024_delete):
+ def test_temp_dir_size(self, common_obj, temp_dir_1024_delete):
""" dir_size() should return the total size (in bytes) of all files
in a particular directory.
"""
- assert common.dir_size(temp_dir_1024_delete) == 1024
+ assert common_obj.dir_size(temp_dir_1024_delete) == 1024
class TestEstimatedTimeRemaining:
@@ -103,16 +102,16 @@ class TestEstimatedTimeRemaining:
((971, 1009, 83), '1s')
))
def test_estimated_time_remaining(
- self, test_input, expected, time_time_100):
- assert common.estimated_time_remaining(*test_input) == expected
+ self, common_obj, test_input, expected, time_time_100):
+ assert common_obj.estimated_time_remaining(*test_input) == expected
@pytest.mark.parametrize('test_input', (
(10, 20, 100), # if `time_elapsed == 0`
(0, 37, 99) # if `download_rate == 0`
))
- def test_raises_zero_division_error(self, test_input, time_time_100):
+ def test_raises_zero_division_error(self, common_obj, test_input, time_time_100):
with pytest.raises(ZeroDivisionError):
- common.estimated_time_remaining(*test_input)
+ common_obj.estimated_time_remaining(*test_input)
class TestFormatSeconds:
@@ -131,16 +130,16 @@ class TestFormatSeconds:
(129674, '1d12h1m14s'),
(56404.12, '15h40m4s')
))
- def test_format_seconds(self, test_input, expected):
- assert common.format_seconds(test_input) == expected
+ def test_format_seconds(self, common_obj, test_input, expected):
+ assert common_obj.format_seconds(test_input) == expected
# TODO: test negative numbers?
@pytest.mark.parametrize('test_input', (
'string', lambda: None, [], {}, set()
))
- def test_invalid_input_types(self, test_input):
+ def test_invalid_input_types(self, common_obj, test_input):
with pytest.raises(TypeError):
- common.format_seconds(test_input)
+ common_obj.format_seconds(test_input)
class TestGetAvailablePort:
@@ -148,29 +147,29 @@ class TestGetAvailablePort:
(random.randint(1024, 1500),
random.randint(1800, 2048)) for _ in range(50)
))
- def test_returns_an_open_port(self, port_min, port_max):
+ def test_returns_an_open_port(self, common_obj, port_min, port_max):
""" get_available_port() should return an open port within the range """
- port = common.get_available_port(port_min, port_max)
+ port = common_obj.get_available_port(port_min, port_max)
assert port_min <= port <= port_max
with socket.socket() as tmpsock:
tmpsock.bind(('127.0.0.1', port))
class TestGetPlatform:
- def test_darwin(self, platform_darwin):
- assert common.get_platform() == 'Darwin'
+ def test_darwin(self, platform_darwin, common_obj):
+ assert common_obj.platform == 'Darwin'
- def test_linux(self, platform_linux):
- assert common.get_platform() == 'Linux'
+ def test_linux(self, platform_linux, common_obj):
+ assert common_obj.platform == 'Linux'
- def test_windows(self, platform_windows):
- assert common.get_platform() == 'Windows'
+ def test_windows(self, platform_windows, common_obj):
+ assert common_obj.platform == 'Windows'
# TODO: double-check these tests
class TestGetResourcePath:
- def test_onionshare_dev_mode(self, sys_onionshare_dev_mode):
+ def test_onionshare_dev_mode(self, common_obj, sys_onionshare_dev_mode):
prefix = os.path.join(
os.path.dirname(
os.path.dirname(
@@ -178,29 +177,29 @@ class TestGetResourcePath:
inspect.getfile(
inspect.currentframe())))), 'share')
assert (
- common.get_resource_path(os.path.join(prefix, 'test_filename')) ==
+ common_obj.get_resource_path(os.path.join(prefix, 'test_filename')) ==
os.path.join(prefix, 'test_filename'))
- def test_linux(self, platform_linux, sys_argv_sys_prefix):
+ def test_linux(self, common_obj, platform_linux, sys_argv_sys_prefix):
prefix = os.path.join(sys.prefix, 'share/onionshare')
assert (
- common.get_resource_path(os.path.join(prefix, 'test_filename')) ==
+ common_obj.get_resource_path(os.path.join(prefix, 'test_filename')) ==
os.path.join(prefix, 'test_filename'))
- def test_frozen_darwin(self, platform_darwin, sys_frozen, sys_meipass):
+ def test_frozen_darwin(self, common_obj, platform_darwin, sys_frozen, sys_meipass):
prefix = os.path.join(sys._MEIPASS, 'share')
assert (
- common.get_resource_path(os.path.join(prefix, 'test_filename')) ==
+ common_obj.get_resource_path(os.path.join(prefix, 'test_filename')) ==
os.path.join(prefix, 'test_filename'))
class TestGetTorPaths:
# @pytest.mark.skipif(sys.platform != 'Darwin', reason='requires MacOS') ?
- def test_get_tor_paths_darwin(self, platform_darwin, sys_frozen, sys_meipass):
+ def test_get_tor_paths_darwin(self, platform_darwin, common_obj, sys_frozen, sys_meipass):
base_path = os.path.dirname(
os.path.dirname(
os.path.dirname(
- common.get_resource_path(''))))
+ common_obj.get_resource_path(''))))
tor_path = os.path.join(
base_path, 'Resources', 'Tor', 'tor')
tor_geo_ip_file_path = os.path.join(
@@ -209,20 +208,20 @@ class TestGetTorPaths:
base_path, 'Resources', 'Tor', 'geoip6')
obfs4proxy_file_path = os.path.join(
base_path, 'Resources', 'Tor', 'obfs4proxy')
- assert (common.get_tor_paths() ==
+ assert (common_obj.get_tor_paths() ==
(tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path, obfs4proxy_file_path))
# @pytest.mark.skipif(sys.platform != 'Linux', reason='requires Linux') ?
- def test_get_tor_paths_linux(self, platform_linux):
- assert (common.get_tor_paths() ==
+ def test_get_tor_paths_linux(self, platform_linux, common_obj):
+ assert (common_obj.get_tor_paths() ==
('/usr/bin/tor', '/usr/share/tor/geoip', '/usr/share/tor/geoip6', '/usr/bin/obfs4proxy'))
# @pytest.mark.skipif(sys.platform != 'Windows', reason='requires Windows') ?
- def test_get_tor_paths_windows(self, platform_windows, sys_frozen):
+ def test_get_tor_paths_windows(self, platform_windows, common_obj, sys_frozen):
base_path = os.path.join(
os.path.dirname(
os.path.dirname(
- common.get_resource_path(''))), 'tor')
+ common_obj.get_resource_path(''))), 'tor')
tor_path = os.path.join(
os.path.join(base_path, 'Tor'), 'tor.exe')
obfs4proxy_file_path = os.path.join(
@@ -233,18 +232,10 @@ class TestGetTorPaths:
tor_geo_ipv6_file_path = os.path.join(
os.path.join(
os.path.join(base_path, 'Data'), 'Tor'), 'geoip6')
- assert (common.get_tor_paths() ==
+ assert (common_obj.get_tor_paths() ==
(tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path, obfs4proxy_file_path))
-class TestGetVersion:
- def test_get_version(self, sys_onionshare_dev_mode):
- with open(common.get_resource_path('version.txt')) as f:
- version = f.read().strip()
-
- assert version == common.get_version()
-
-
class TestHumanReadableFilesize:
@pytest.mark.parametrize('test_input,expected', (
(1024 ** 0, '1.0 B'),
@@ -257,8 +248,8 @@ class TestHumanReadableFilesize:
(1024 ** 7, '1.0 ZiB'),
(1024 ** 8, '1.0 YiB')
))
- def test_human_readable_filesize(self, test_input, expected):
- assert common.human_readable_filesize(test_input) == expected
+ def test_human_readable_filesize(self, common_obj, test_input, expected):
+ assert common_obj.human_readable_filesize(test_input) == expected
class TestLog:
@@ -273,82 +264,18 @@ class TestLog:
def test_log_msg_regex(self, test_input):
assert bool(LOG_MSG_REGEX.match(test_input))
- def test_output(self, set_debug_true, time_strftime):
+ def test_output(self, common_obj, time_strftime):
def dummy_func():
pass
+ common_obj.debug = True
+
# From: https://stackoverflow.com/questions/1218933
with io.StringIO() as buf, contextlib.redirect_stdout(buf):
- common.log('TestModule', dummy_func)
- common.log('TestModule', dummy_func, 'TEST_MSG')
+ common_obj.log('TestModule', dummy_func)
+ common_obj.log('TestModule', dummy_func, 'TEST_MSG')
output = buf.getvalue()
line_one, line_two, _ = output.split('\n')
assert LOG_MSG_REGEX.match(line_one)
assert LOG_MSG_REGEX.match(line_two)
-
-
-class TestSetDebug:
- def test_debug_true(self, set_debug_false):
- common.set_debug(True)
- assert common.debug is True
-
- def test_debug_false(self, set_debug_true):
- common.set_debug(False)
- assert common.debug is False
-
-
-class TestZipWriterDefault:
- @pytest.mark.parametrize('test_input', (
- 'onionshare_{}.zip'.format(''.join(
- random.choice('abcdefghijklmnopqrstuvwxyz234567') for _ in range(6)
- )) for _ in range(50)
- ))
- def test_default_zw_filename_regex(self, test_input):
- assert bool(DEFAULT_ZW_FILENAME_REGEX.match(test_input))
-
- def test_zw_filename(self, default_zw):
- zw_filename = os.path.basename(default_zw.zip_filename)
- assert bool(DEFAULT_ZW_FILENAME_REGEX.match(zw_filename))
-
- def test_zipfile_filename_matches_zipwriter_filename(self, default_zw):
- assert default_zw.z.filename == default_zw.zip_filename
-
- def test_zipfile_allow_zip64(self, default_zw):
- assert default_zw.z._allowZip64 is True
-
- def test_zipfile_mode(self, default_zw):
- assert default_zw.z.mode == 'w'
-
- def test_callback(self, default_zw):
- assert default_zw.processed_size_callback(None) is None
-
- def test_add_file(self, default_zw, temp_file_1024_delete):
- default_zw.add_file(temp_file_1024_delete)
- zipfile_info = default_zw.z.getinfo(
- os.path.basename(temp_file_1024_delete))
-
- assert zipfile_info.compress_type == zipfile.ZIP_DEFLATED
- assert zipfile_info.file_size == 1024
-
- def test_add_directory(self, temp_dir_1024_delete, default_zw):
- previous_size = default_zw._size # size before adding directory
- default_zw.add_dir(temp_dir_1024_delete)
- assert default_zw._size == previous_size + 1024
-
-
-class TestZipWriterCustom:
- @pytest.mark.parametrize('test_input', (
- common.random_string(
- random.randint(2, 50),
- random.choice((None, random.randint(2, 50)))
- ) for _ in range(50)
- ))
- def test_random_string_regex(self, test_input):
- assert bool(RANDOM_STR_REGEX.match(test_input))
-
- def test_custom_filename(self, custom_zw):
- assert bool(RANDOM_STR_REGEX.match(custom_zw.zip_filename))
-
- def test_custom_callback(self, custom_zw):
- assert custom_zw.processed_size_callback(None) == 'custom_callback'
diff --git a/test/test_onionshare_settings.py b/tests/test_onionshare_settings.py
index 212aceb8..bb619c4d 100644
--- a/test/test_onionshare_settings.py
+++ b/tests/test_onionshare_settings.py
@@ -1,7 +1,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -27,23 +27,20 @@ from onionshare import common, settings, strings
@pytest.fixture
-def custom_version(monkeypatch):
- monkeypatch.setattr(common, 'get_version', lambda: 'DUMMY_VERSION_1.2.3')
-
-
-@pytest.fixture
def os_path_expanduser(monkeypatch):
monkeypatch.setattr('os.path.expanduser', lambda path: path)
@pytest.fixture
-def settings_obj(custom_version, sys_onionshare_dev_mode, platform_linux):
- return settings.Settings()
+def settings_obj(sys_onionshare_dev_mode, platform_linux):
+ _common = common.Common()
+ _common.version = 'DUMMY_VERSION_1.2.3'
+ return settings.Settings(_common)
class TestSettings:
def test_init(self, settings_obj):
- assert settings_obj._settings == settings_obj.default_settings == {
+ expected_settings = {
'version': 'DUMMY_VERSION_1.2.3',
'connection_type': 'bundled',
'control_port_address': '127.0.0.1',
@@ -54,21 +51,27 @@ class TestSettings:
'auth_type': 'no_auth',
'auth_password': '',
'close_after_first_download': True,
- 'systray_notifications': True,
'shutdown_timeout': False,
'use_stealth': False,
'use_autoupdate': True,
'autoupdate_timestamp': None,
'no_bridges': True,
'tor_bridges_use_obfs4': False,
- 'tor_bridges_use_meek_lite_amazon': False,
'tor_bridges_use_meek_lite_azure': False,
'tor_bridges_use_custom_bridges': '',
+ 'use_legacy_v2_onions': False,
'save_private_key': False,
'private_key': '',
'slug': '',
- 'hidservauth_string': ''
+ 'hidservauth_string': '',
+ 'downloads_dir': os.path.expanduser('~/OnionShare'),
+ 'public_mode': False
}
+ for key in settings_obj._settings:
+ # Skip locale, it will not always default to the same thing
+ if key != 'locale':
+ assert settings_obj._settings[key] == settings_obj.default_settings[key]
+ assert settings_obj._settings[key] == expected_settings[key]
def test_fill_in_defaults(self, settings_obj):
del settings_obj._settings['version']
@@ -121,14 +124,12 @@ class TestSettings:
assert settings_obj.get('auth_type') == 'no_auth'
assert settings_obj.get('auth_password') == ''
assert settings_obj.get('close_after_first_download') is True
- assert settings_obj.get('systray_notifications') is True
assert settings_obj.get('use_stealth') is False
assert settings_obj.get('use_autoupdate') is True
assert settings_obj.get('autoupdate_timestamp') is None
assert settings_obj.get('autoupdate_timestamp') is None
assert settings_obj.get('no_bridges') is True
assert settings_obj.get('tor_bridges_use_obfs4') is False
- assert settings_obj.get('tor_bridges_use_meek_lite_amazon') is False
assert settings_obj.get('tor_bridges_use_meek_lite_azure') is False
assert settings_obj.get('tor_bridges_use_custom_bridges') == ''
@@ -153,30 +154,27 @@ class TestSettings:
def test_filename_darwin(
self,
- custom_version,
monkeypatch,
os_path_expanduser,
platform_darwin):
- obj = settings.Settings()
+ obj = settings.Settings(common.Common())
assert (obj.filename ==
'~/Library/Application Support/OnionShare/onionshare.json')
def test_filename_linux(
self,
- custom_version,
monkeypatch,
os_path_expanduser,
platform_linux):
- obj = settings.Settings()
+ obj = settings.Settings(common.Common())
assert obj.filename == '~/.config/onionshare/onionshare.json'
def test_filename_windows(
self,
- custom_version,
monkeypatch,
platform_windows):
monkeypatch.setenv('APPDATA', 'C:')
- obj = settings.Settings()
+ obj = settings.Settings(common.Common())
assert obj.filename == 'C:\\OnionShare\\onionshare.json'
def test_set_custom_bridge(self, settings_obj):
diff --git a/test/test_onionshare_strings.py b/tests/test_onionshare_strings.py
index 0e7a32ab..ea57e3a9 100644
--- a/test/test_onionshare_strings.py
+++ b/tests/test_onionshare_strings.py
@@ -2,7 +2,7 @@
"""
OnionShare | https://onionshare.org/
-Copyright (C) 2018 Micah Lee <micah@micahflee.com>
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
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
@@ -22,8 +22,8 @@ import types
import pytest
-from onionshare import common, strings
-
+from onionshare import strings
+from onionshare.settings import Settings
# # Stub get_resource_path so it finds the correct path while running tests
# def get_resource_path(filename):
@@ -32,40 +32,31 @@ from onionshare import common, strings
# return path
# common.get_resource_path = get_resource_path
-
-def test_starts_with_empty_strings():
- """ Creates an empty strings dict by default """
- assert strings.strings == {}
-
-
def test_underscore_is_function():
assert callable(strings._) and isinstance(strings._, types.FunctionType)
class TestLoadStrings:
def test_load_strings_defaults_to_english(
- self, locale_en, sys_onionshare_dev_mode):
+ self, common_obj, locale_en, sys_onionshare_dev_mode):
""" load_strings() loads English by default """
- strings.load_strings(common)
- assert strings._('wait_for_hs') == "Waiting for HS to be ready:"
+ common_obj.settings = Settings(common_obj)
+ strings.load_strings(common_obj)
+ assert strings._('preparing_files') == "Compressing files."
def test_load_strings_loads_other_languages(
- self, locale_fr, sys_onionshare_dev_mode):
+ self, common_obj, locale_fr, sys_onionshare_dev_mode):
""" load_strings() loads other languages in different locales """
- strings.load_strings(common, "fr")
- assert strings._('wait_for_hs') == "En attente du HS:"
-
- def test_load_partial_strings(
- self, locale_ru, sys_onionshare_dev_mode):
- strings.load_strings(common)
- assert strings._("give_this_url") == (
- "Отправьте эту ссылку тому человеку, "
- "которому вы хотите передать файл:")
- assert strings._('wait_for_hs') == "Waiting for HS to be ready:"
+ common_obj.settings = Settings(common_obj)
+ common_obj.settings.set('locale', 'fr')
+ strings.load_strings(common_obj)
+ assert strings._('preparing_files') == "Préparation des fichiers à partager."
def test_load_invalid_locale(
- self, locale_invalid, sys_onionshare_dev_mode):
+ self, common_obj, locale_invalid, sys_onionshare_dev_mode):
""" load_strings() raises a KeyError for an invalid locale """
with pytest.raises(KeyError):
- strings.load_strings(common, 'XX')
+ common_obj.settings = Settings(common_obj)
+ common_obj.settings.set('locale', 'XX')
+ strings.load_strings(common_obj)
diff --git a/tests/test_onionshare_web.py b/tests/test_onionshare_web.py
new file mode 100644
index 00000000..3f9540ae
--- /dev/null
+++ b/tests/test_onionshare_web.py
@@ -0,0 +1,226 @@
+"""
+OnionShare | https://onionshare.org/
+
+Copyright (C) 2014-2018 Micah Lee <micah@micahflee.com>
+
+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 <http://www.gnu.org/licenses/>.
+"""
+
+import contextlib
+import inspect
+import io
+import os
+import random
+import re
+import socket
+import sys
+import zipfile
+import tempfile
+
+import pytest
+
+from onionshare.common import Common
+from onionshare import strings
+from onionshare.web import Web
+from onionshare.settings import Settings
+
+DEFAULT_ZW_FILENAME_REGEX = re.compile(r'^onionshare_[a-z2-7]{6}.zip$')
+RANDOM_STR_REGEX = re.compile(r'^[a-z2-7]+$')
+
+
+def web_obj(common_obj, mode, num_files=0):
+ """ Creates a Web object, in either share mode or receive mode, ready for testing """
+ common_obj.load_settings()
+ strings.load_strings(common_obj)
+ web = Web(common_obj, False, mode)
+ web.generate_slug()
+ web.stay_open = True
+ web.running = True
+
+ web.app.testing = True
+
+ # Share mode
+ if mode == 'share':
+ # Add files
+ files = []
+ for i in range(num_files):
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
+ tmp_file.write(b'*' * 1024)
+ files.append(tmp_file.name)
+ web.share_mode.set_file_info(files)
+ # Receive mode
+ else:
+ pass
+
+ return web
+
+
+class TestWeb:
+ def test_share_mode(self, common_obj):
+ web = web_obj(common_obj, 'share', 3)
+ assert web.mode is 'share'
+ with web.app.test_client() as c:
+ # Load 404 pages
+ res = c.get('/')
+ res.get_data()
+ assert res.status_code == 404
+
+ res = c.get('/invalidslug'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 404
+
+ # Load download page
+ res = c.get('/{}'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 200
+
+ # Download
+ res = c.get('/{}/download'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 200
+ assert res.mimetype == 'application/zip'
+
+ def test_share_mode_close_after_first_download_on(self, common_obj, temp_file_1024):
+ web = web_obj(common_obj, 'share', 3)
+ web.stay_open = False
+
+ assert web.running == True
+
+ with web.app.test_client() as c:
+ # Download the first time
+ res = c.get('/{}/download'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 200
+ assert res.mimetype == 'application/zip'
+
+ assert web.running == False
+
+ def test_share_mode_close_after_first_download_off(self, common_obj, temp_file_1024):
+ web = web_obj(common_obj, 'share', 3)
+ web.stay_open = True
+
+ assert web.running == True
+
+ with web.app.test_client() as c:
+ # Download the first time
+ res = c.get('/{}/download'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 200
+ assert res.mimetype == 'application/zip'
+ assert web.running == True
+
+ def test_receive_mode(self, common_obj):
+ web = web_obj(common_obj, 'receive')
+ assert web.mode is 'receive'
+
+ with web.app.test_client() as c:
+ # Load 404 pages
+ res = c.get('/')
+ res.get_data()
+ assert res.status_code == 404
+
+ res = c.get('/invalidslug'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 404
+
+ # Load upload page
+ res = c.get('/{}'.format(web.slug))
+ res.get_data()
+ assert res.status_code == 200
+
+ def test_public_mode_on(self, common_obj):
+ web = web_obj(common_obj, 'receive')
+ common_obj.settings.set('public_mode', True)
+
+ with web.app.test_client() as c:
+ # Upload page should be accessible from /
+ res = c.get('/')
+ data1 = res.get_data()
+ assert res.status_code == 200
+
+ # /[slug] should be a 404
+ res = c.get('/{}'.format(web.slug))
+ data2 = res.get_data()
+ assert res.status_code == 404
+
+ def test_public_mode_off(self, common_obj):
+ web = web_obj(common_obj, 'receive')
+ common_obj.settings.set('public_mode', False)
+
+ with web.app.test_client() as c:
+ # / should be a 404
+ res = c.get('/')
+ data1 = res.get_data()
+ assert res.status_code == 404
+
+ # Upload page should be accessible from /[slug]
+ res = c.get('/{}'.format(web.slug))
+ data2 = res.get_data()
+ assert res.status_code == 200
+
+
+class TestZipWriterDefault:
+ @pytest.mark.parametrize('test_input', (
+ 'onionshare_{}.zip'.format(''.join(
+ random.choice('abcdefghijklmnopqrstuvwxyz234567') for _ in range(6)
+ )) for _ in range(50)
+ ))
+ def test_default_zw_filename_regex(self, test_input):
+ assert bool(DEFAULT_ZW_FILENAME_REGEX.match(test_input))
+
+ def test_zw_filename(self, default_zw):
+ zw_filename = os.path.basename(default_zw.zip_filename)
+ assert bool(DEFAULT_ZW_FILENAME_REGEX.match(zw_filename))
+
+ def test_zipfile_filename_matches_zipwriter_filename(self, default_zw):
+ assert default_zw.z.filename == default_zw.zip_filename
+
+ def test_zipfile_allow_zip64(self, default_zw):
+ assert default_zw.z._allowZip64 is True
+
+ def test_zipfile_mode(self, default_zw):
+ assert default_zw.z.mode == 'w'
+
+ def test_callback(self, default_zw):
+ assert default_zw.processed_size_callback(None) is None
+
+ def test_add_file(self, default_zw, temp_file_1024_delete):
+ default_zw.add_file(temp_file_1024_delete)
+ zipfile_info = default_zw.z.getinfo(
+ os.path.basename(temp_file_1024_delete))
+
+ assert zipfile_info.compress_type == zipfile.ZIP_DEFLATED
+ assert zipfile_info.file_size == 1024
+
+ def test_add_directory(self, temp_dir_1024_delete, default_zw):
+ previous_size = default_zw._size # size before adding directory
+ default_zw.add_dir(temp_dir_1024_delete)
+ assert default_zw._size == previous_size + 1024
+
+
+class TestZipWriterCustom:
+ @pytest.mark.parametrize('test_input', (
+ Common.random_string(
+ random.randint(2, 50),
+ random.choice((None, random.randint(2, 50)))
+ ) for _ in range(50)
+ ))
+ def test_random_string_regex(self, test_input):
+ assert bool(RANDOM_STR_REGEX.match(test_input))
+
+ def test_custom_filename(self, custom_zw):
+ assert bool(RANDOM_STR_REGEX.match(custom_zw.zip_filename))
+
+ def test_custom_callback(self, custom_zw):
+ assert custom_zw.processed_size_callback(None) == 'custom_callback'