diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..747b042 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,15 @@ +* amazon-dash version: +* Python version: +* Operating System: + +### Description + +Describe what you were trying to get done. +Tell us what happened, what went wrong, and what you expected to happen. + +### What I Did + +``` +Paste the command(s) you ran and the output. +If there was a crash, please include the traceback here. +``` diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..de02d20 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Development Lead +---------------- + +* Nekmo + +Contributors +------------ + +None yet. Why not be the first? diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..2b8510f --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,114 @@ +.. highlight:: shell + +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every +little bit helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/Nekmo/amazon-dash/issues + +If you are reporting a bug, please include: + +* Your operating system name and version. +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" +and "help wanted" is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "enhancement" +and "help wanted" is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +amazon-dash could always use more documentation, whether as part of the +official amazon-dash docs, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/Nekmo/amazon-dash/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `amazon-dash` for local development. + +1. Fork the `amazon-dash` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/amazon-dash.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: + + $ mkvirtualenv amazon-dash + $ cd amazon-dash/ + $ python setup.py develop + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: + + $ flake8 amazon-dash tests + $ python -m unittest discover + $ tox + + To get flake8 and tox, just pip install them into your virtualenv. + +6. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +7. Submit a pull request through the GitHub website. + + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the list in README.rst. +3. The pull request should work for Python 2.7, 3.4, 3.5 and 3.6. Check + https://travis-ci.org/Nekmo/amazon-dash/pull_requests + and make sure that the tests pass for all supported Python versions. + +Tips +---- + +To run a subset of tests:: + + $ python -m unittest tests.test_amazon_dash diff --git a/HISTORY.rst b/HISTORY.rst new file mode 100644 index 0000000..19e5206 --- /dev/null +++ b/HISTORY.rst @@ -0,0 +1,42 @@ +======= +History +======= + +v0.4.0 +------ + +- Native Home Assistant support. +- docs.nekmo.org documentation. +- Arch Linux package +- Check config file command +- Test execution command +- Install systemd service +- Install config file on ``/etc/amazon-dash.yml`` + + +v0.3.0 (2017-12-24) +------------------- + +- Unit testing. +- Travis CI. +- Config validation. +- Help messages. +- Request to URL. +- Distinguish Amazon devices in discovery mode. + + +v0.2.0 (2016-12-13) +------------------- + +- Securize config file. +- Systemd config file example. +- Refactor imports. +- Updated README. + +v0.1.0 (2016-11-16) +------------------- + +- Execute commands. +- Discovery mode. +- Setup.py +- README. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4f3706a --- /dev/null +++ b/Makefile @@ -0,0 +1,87 @@ +.PHONY: clean clean-test clean-pyc clean-build docs help +.DEFAULT_GOAL := help +define BROWSER_PYSCRIPT +import os, webbrowser, sys +try: + from urllib import pathname2url +except: + from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts + + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + +lint: ## check style with flake8 + flake8 nginx_sites tests + +test: ## run tests quickly with the default Python + + python setup.py test + +test-all: ## run tests on every Python version with tox + tox + +coverage: ## check code coverage quickly with the default Python + coverage run --source nginx_sites setup.py test + coverage report -m + coverage html + $(BROWSER) htmlcov/index.html + +docs: ## generate Sphinx HTML documentation, including API docs + rm -f docs/nginx_sites.rst + rm -f docs/modules.rst + sphinx-apidoc -o docs/ nginx_sites + $(MAKE) -C docs clean + $(MAKE) -C docs html + $(BROWSER) docs/_build/html/index.html + +servedocs: docs ## compile the docs watching for changes + watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . + +release: clean ## package and upload a release + python setup.py sdist upload + python setup.py bdist_wheel upload + +dist: clean ## builds source and wheel package + python setup.py sdist + python setup.py bdist_wheel + ls -l dist + +install: clean ## install the package to the active Python's site-packages + python setup.py install diff --git a/README.rst b/README.rst index 443e8ae..3f2dfa3 100644 --- a/README.rst +++ b/README.rst @@ -1,3 +1,5 @@ +.. highlight:: console + .. image:: https://raw.githubusercontent.com/Nekmo/amazon-dash/master/amazon-dash.png :width: 100% @@ -22,7 +24,7 @@ :alt: Code Climate .. image:: https://img.shields.io/codecov/c/github/Nekmo/amazon-dash/master.svg?style=flat-square - :target: https://codecov.io/github/Nekmo/djangocms-comments + :target: https://codecov.io/github/Nekmo/amazon-dash :alt: Test coverage .. image:: https://img.shields.io/requires/github/Nekmo/amazon-dash.svg?style=flat-square @@ -37,26 +39,30 @@ Hack your Amazon Dash to run what you want. Without welders. For the entire fami This program written in Python runs in daemon mode waiting for someone in the same network to press a configured Amazon Dash button. It is not necessary to know -programming to use this program. Amazon-Dash executes commands by command line -or calls a url. This program works well on a raspberry PI or on computers with -few resources. +programming to use this program. Amazon-Dash executes **commands by command line, +calls a url and more**. This program works well on a **Raspberry PI** or on computers +with few resources. + +1. **Install** Amazon Dash: -1. Install Amazon Dash: +.. code:: -.. code:: bash + $ sudo pip install amazon-dash # and after: + $ sudo python -m amazon_dash.install - sudo pip install amazon-dash +Also available on `AUR `_. See other installation methods +`in the documentation `_. -2. Use discovery mode to know the mac of your Dash (Run the program, and then press the button): +2. Use *discovery mode* **to know the mac of your Dash** (Run the program, and then press any button): -.. code:: bash +.. code:: - sudo amazon-dash discovery + $ sudo amazon-dash discovery -3. Create a config file (``amazon-dash.yml``): +3. Edit **config file** (``/etc/amazon-dash.yml``): .. code:: yaml @@ -69,89 +75,52 @@ few resources. name: Hero user: nekmo cmd: spotify - 44:65:0D:48:FA:88: - name: Pompadour - user: nekmo - cmd: /opt/open-door kitcken AC:63:BE:67:B2:F1: name: Kit Kat url: 'http://domain.com/path/to/webhook' method: post content-type: json body: '{"mac": "AC:63:BE:67:B2:F1", "action": "toggleLight"}' + 40:B4:CD:67:A2:E1: + name: Fairy + homeassistant: hassio.local + event: toggle_kitchen_light +The following execution methods are supported with your Amazon Dash button with this program: -4. Run the daemon: - -.. code:: bash - - sudo amazon-dash[ --config amazon-dash.yml] run - -By default, ``amazon-dash`` will use the ``amazon-dash.yml`` file in the current directory with -``sudo amazon-dash run``. However, you can set the path to the file (for example, ``/etc/amazon-dash.yml``) with -``--config`` parameter. Please note that ``--config`` must be before ``run``. +================================ ================================ ================================ +.. image:: https://goo.gl/bq5QSK .. image:: https://goo.gl/k4DJmf .. image:: https://goo.gl/Gqo8W3 +`System command`_ `Call url`_ `Homeassistant`_ +================================ ================================ ================================ -The default level logging is ``INFO`` but you can change it using the ``--warning``, ``--quiet``, ``--debug`` and -``--verbose`` options. To see on screen every time a button is pressed you need to set the ``--debug`` option. +For more information see +`the documentation of the configuration file `_. -By default it is forbidden to execute commands as root in your configuration file. This is a security measure to -avoid escalation privileges. If you are going to run amazon-dash as root it is highly recommended to define a -user by each cmd config device. You can disable this security measure using ``--root-allowed``. +4. Run the **daemon**: -Contents -======== -- `Avoid making a purchase by pressing the button <#avoid-making-a-purchase-by-pressing-the-button>`_. -- `Run at startup <#run-at-startup>`_ -- `Examples <#examples>`_ -- `Config file <#config-file>`_ -- `Changelog <#changelog>`_ -- `Troubleshooting <#troubleshooting>`_ -- `Why Root is required <#why-root-is-required>`_ -- `References <#references>`_ - - -Avoid making a purchase by pressing the button -============================================== -This program detects when your button connects to the network to execute actions, but does not prevent the ordering. - -There are 3 ways to avoid making a purchase when you press the button. +If you use a **Systemd** system *(Debian 8+, Fedora 15+, Ubuntu 15.04+, Arch Linux 2012+, OpenSUSE 12.1+, and more)* +execute:: + $ sudo systemctl start amazon-dash -Easy mode: Do not choose the product to buy when setting up ------------------------------------------------------------ -When you first set your button, you are asked which product you want to buy when you press the button. If you do not -choose an option, the button will work, but an order will not be created. +To run Amazon-dash at startup:: -However, in order to take advantage of the free balance ($5/€5/£5), it is necessary to choose a product. The solution -is after ordering, deactivate the button, reconfigure it, and not choosing the product the second time. + $ sudo systemctl enable amazon-dash -However, you will receive an alert in the Amazon application every time you press the button asking you to finish the -configuration. You can turn off notifications, delete the application, or use another Amazon account. +To run Amazon-dash manually look at `the documentation `_. -Using an advanced router ------------------------- -If you have an advanced router (DD-Wrt, Open-WRT, Tomato, RouterOS...), you can block Internet output from the buttons. -This is the preferred option. It is necessary to block the Internet output. Using DNS locks will not work. The button -uses its own DNS server IP, ignoring router DNS. +5. **Avoid making a purchase** by pressing the button -Raspberry PI solution ---------------------- -You can use the Raspberry PI as a router if you have 2 network cards. The method is similar to the previous one, but -being a Linux system you can use iptables. - - -Run at startup -============== -This example is for systems with **Systemd**. The files of the services are in this `link `_. -If your system is not supported, feel free to do a **pull request**. +This program detects when your button connects to the network to execute actions, but does not prevent the ordering. +The easiest way to avoid making a purchase is to reconfigure the button using the Amazon instructions +(by pressing the button for 5 seconds) but **skipping the last configuration step** *(do not choose which product you +want to associate with the button)*. If Amazon does not know what product you want, they can not charge anything on +your credit card. -1. Copy `amazon-dash.service` to `/etc/systemd/system/`. -2. Create your config file in `/etc/amazon-dash.yml`. -3. Enable your service with `sudo systemctl enable amazon-dash`. -4. Start your service with `sudo systemctl start amazon-dash`. +There are two more methods `in the documentation `_. Examples @@ -159,109 +128,10 @@ Examples Here are some examples of how to use your Amazon Dash button: * **Random Episode**: Play a random chapter of your favorite series, like *The Simpsons*, *Futurama*, *Friends*... https://github.com/Nekmo/random-episode +* **Gkeep**: Add tasks to Google Keep (buy milk, beer...). The notes can be associated with a place to run a reminder. + https://github.com/Nekmo/gkeep -Config file -=========== -The configuration file can be found anywhere but if the program runs in root mode, -it is necessary that only root can modify the file. This is a security measure to prevent -someone from executing commands as root using the program. - -To change the permissions:: - - sudo chmod 600 amazon-dash.yml - sudo chown root:root amazon-dash.yml - -The syntax of the configuration file is yaml. The configuration file has 2 main sections: - -* **settings** (optional): common options. -* **devices** (required): The amazon dash devices. - -The following options are available in **settings**: - -* **delay** (optional): On seconds. By default, 10 seconds. Minimum time that must pass between pulsations of the - Amazon Dash button. - -Each device is identified by the button **mac**. The mac can be obtained with the discovery command. -In the configuration of each button, there may be a way of execution. Only one execution method is allowed -for each device. The available exection methods are: - -* **cmd**: local command line command. Arguments can be placed after the command. -* **url**: Call a url. - -When the **cmd execution method** is used, the following options are available. - -* **user**: System user that will execute the command. This option can only be used if Amazon-Dash is running as root. -* **cwd**: Directory in which the command will be executed. - -When the **url execution method** is used, the following options are available. - -* **method**: HTTP method. By default GET. -* **content-type** (*): HTTP Content-Type Header. Only available if Body is defined. If body is defined, default is form. -* **body**: Request payload. Only if the method is POST/PUT/PATCH. In json or form mode, the content must be a valid json. It is recommended to use single quotes before and after content in json. - -(*) Content type aliases: `form = application/x-www-form-urlencoded`. `json = application/json`. `plain = text/plain`. - -An example of a configuration file can be found at the beginning of the documentation. - - -Changelog -========= - -v0.3.0 ------- - -- Unit testing. -- Travis CI. -- Config validation. -- Help messages. -- Request to URL. -- Distinguish Amazon devices in discovery mode. - - -v0.2.0 ------- - -- Securize config file. -- Systemd config file example. -- Refactor imports. -- Updated README. - -v0.1.0 ------- - -- Execute commands. -- Discovery mode. -- Setup.py -- README. - - -Troubleshooting -=============== - -Requirements and installation ------------------------------ -All dependencies are commonly used on a Linux system, but some may not be installed on your system. The dependencies -are: - -* Python 2.7 or 3.4+. -* Python-pip (pip). -* Tcpdump. -* Sudo - - -Why root is required -==================== -This program needs permission to open raw sockets on your system. You can set this permission using setcap, but you -must be very careful about who can run the program. Raw sockets permission could allow scaling permissions on the -system:: - - setcap cap_net_raw=eip ./scripts/amazon-dash - setcap cap_net_raw=eip /usr/bin/pythonX.X - setcap cap_net_raw=eip /usr/bin/tcpdump - -http://stackoverflow.com/questions/36215201/python-scapy-sniff-without-root - References ========== @@ -269,3 +139,8 @@ References * https://github.com/vancetran/amazon-dash-rpi/blob/master/habits.py * http://www.alphr.com/amazon/1001429/amazon-dash-button-hacks-5-ways-to-build-your-own-low-cost-connected-home/page/0/1 * https://community.smartthings.com/t/hack-the-amazon-dash-button-to-control-a-smartthings-switch/20427/14 + +.. _System command: http://docs.nekmo.org/amazon-dash/config_file.html#execute-cmd +.. _Call url: http://docs.nekmo.org/amazon-dash/config_file.html#call-url +.. _Homeassistant: http://docs.nekmo.org/amazon-dash/config_file.html#homeassistant-event + diff --git a/amazon-dash.png b/amazon-dash.png index b50cdbd..668de96 100644 Binary files a/amazon-dash.png and b/amazon-dash.png differ diff --git a/amazon_dash/_compat.py b/amazon_dash/_compat.py index aa40bec..4a83328 100644 --- a/amazon_dash/_compat.py +++ b/amazon_dash/_compat.py @@ -3,3 +3,9 @@ from json import JSONDecodeError except ImportError: JSONDecodeError = ValueError + + +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse diff --git a/amazon_dash/config.py b/amazon_dash/config.py index 6aba28e..9c0deba 100644 --- a/amazon_dash/config.py +++ b/amazon_dash/config.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os import stat from grp import getgrgid @@ -14,6 +15,7 @@ except ImportError: from yaml import Loader, Dumper +#: Json-schema validation SCHEMA = { "title": "Config", "type": "object", @@ -69,6 +71,12 @@ }, "body": { "type": "string" + }, + "homeassistant": { + "type": "string" + }, + "event": { + "type": "string" } }, } @@ -82,14 +90,34 @@ def get_file_owner(file): + """Get file owner id + + :param str file: Path to file + :return: user id + :rtype: int + """ return getpwuid(os.stat(file).st_uid)[0] def get_file_group(file): + """Get file group id + + :param file: Path to file + :return: group id + :rtype: int + """ return getgrgid(os.stat(file).st_uid)[0] def bitperm(s, perm, pos): + """Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value + + :param os.stat_result s: os.stat(file) object + :param str perm: R (Read) or W (Write) or X (eXecute) + :param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer) + :return: mask value + :rtype: int + """ perm = perm.upper() pos = pos.upper() assert perm in ['R', 'W', 'X'] @@ -98,22 +126,41 @@ def bitperm(s, perm, pos): def oth_w_perm(file): + """Returns True if others have write permission to the file + + :param str file: Path to file + :return: True if others have permits + :rtype: bool + """ return bitperm(os.stat(file), 'w', 'oth') def only_root_write(path): + """File is only writable by root + + :param str path: Path to file + :return: True if only root can write + :rtype: bool + """ s = os.stat(path) for ug, bp in [(s.st_uid, bitperm(s, 'w', 'usr')), (s.st_gid, bitperm(s, 'w', 'grp'))]: # User id (is not root) and bit permission if ug and bp: - return False + return False if bitperm(s, 'w', 'oth'): return False return True class Config(dict): + """Parse and validate yaml Amazon-dash file config. The instance behaves like a dictionary + """ def __init__(self, file, **kwargs): + """Set the config file and validate file permissions + + :param str file: path to file + :param kwargs: default values in dict + """ super(Config, self).__init__(**kwargs) if not os.path.lexists(file): raise ConfigFileNotFoundError(file) @@ -131,6 +178,10 @@ def __init__(self, file, **kwargs): self.read() def read(self): + """Parse and validate the config file. The read data is accessible as a dictionary in this instance + + :return: None + """ try: data = load(open(self.file), Loader) except (UnicodeDecodeError, YAMLError) as e: @@ -140,3 +191,14 @@ def read(self): except ValidationError as e: raise InvalidConfig(self.file, e) self.update(data) + + +def check_config(file, printfn=print): + """Command to check configuration file. Raises InvalidConfig on error + + :param str file: path to config file + :param printfn: print function for success message + :return: None + """ + Config(file).read() + printfn('The configuration file "{}" is correct'.format(file)) diff --git a/amazon_dash/discovery.py b/amazon_dash/discovery.py index 28bd07a..bd283f4 100644 --- a/amazon_dash/discovery.py +++ b/amazon_dash/discovery.py @@ -1,9 +1,5 @@ from amazon_dash.scan import scan_devices -# https://standards.ieee.org/develop/regauth/oui/oui.csv -# import csv -# print('\n'.join([':'.join([row[1][i:i+2] for i in range(0, len(row[1]), 2)]) -# for row in csv.reader(open('oui.csv')) if row[2] == 'Amazon Technologies Inc.'])) AMAZON_DEVICES = [ 'F0:D2:F1', '88:71:E5', @@ -34,7 +30,20 @@ 'B4:7C:9C', 'F0:81:73', ] +"""Amazon Dash Mac Devices. Source: https://standards.ieee.org/develop/regauth/oui/oui.csv + +Snippet for Re-generate this list: + +>>> import csv +>>> print('\n'.join([':'.join([row[1][i:i+2] for i in range(0, len(row[1]), 2)]) + for row in csv.reader(open('oui.csv')) if row[2] == 'Amazon Technologies Inc.'])) +""" + + BANNED_DEVICES = ['00:00:00:00:00:00'] +"""These mac addresses will not be considered valid results on discovery. +""" + HELP = """\ The discovery command lists the devices that are connected in your network. \ Each device will only be listed once. After executing this command wait approximately \ @@ -44,9 +53,17 @@ """ mac_id_list = [] +"""Mac addresses already known. Mac addresses only appear once. +""" def pkt_text(pkt): + """Return source mac address for this Scapy Packet + + :param scapy.packet.Packet pkt: Scapy Packet + :return: Mac address. Include (Amazon Device) for these devices + :rtype: str + """ if pkt.src.upper() in BANNED_DEVICES: body = '' elif pkt.src.upper()[:8] in AMAZON_DEVICES: @@ -57,6 +74,12 @@ def pkt_text(pkt): def discovery_print(pkt): + """Scandevice callback. Register src mac to avoid src repetition. + Print device on screen. + + :param scapy.packet.Packet pkt: Scapy Packet + :return: None + """ if pkt.src in mac_id_list: return mac_id_list.append(pkt.src) @@ -64,5 +87,9 @@ def discovery_print(pkt): def discover(): + """Print help and scan devices on screen. + + :return: None + """ print(HELP) scan_devices(discovery_print, lfilter=lambda d: d.src not in mac_id_list) diff --git a/amazon_dash/exceptions.py b/amazon_dash/exceptions.py index 0e6380a..1b4d406 100644 --- a/amazon_dash/exceptions.py +++ b/amazon_dash/exceptions.py @@ -7,21 +7,36 @@ class AmazonDashException(Exception): + """Amazon Dash base exception. All the exceptions that use this base are captured by the command line. + """ pass class SecurityException(AmazonDashException): + """A configuration fault has been found that puts the system at risk + """ pass class ConfigFileNotFoundError(AmazonDashException, FileNotFoundError): + """The configuration file was not found + """ def __init__(self, file): + """ + :param str file: Path to config path used + """ file = os.path.abspath(file) super(ConfigFileNotFoundError, self).__init__('The configuration file was not found on "{}"'.format(file)) class InvalidConfig(AmazonDashException): + """The configuration file has not passed the yaml validation or json-schema validation or exec. class validation + """ def __init__(self, file=None, extra_body=''): + """ + :param str file: Path to config file + :param extra_body: complementary message + """ body = 'The configuration file is invalid' if file: file = os.path.abspath(file) @@ -33,8 +48,16 @@ def __init__(self, file=None, extra_body=''): class SocketPermissionError(AmazonDashException): + """The program must be run as root or the user needs permissions to sniff the traffic + """ def __init__(self): msg = 'This program needs permission to open raw sockets on your system. ' \ 'The easy way to run this program is to use root. To use a normal user,' \ ' consult the documentation.' super(SocketPermissionError, self).__init__(msg) + + +class InvalidDevice(AmazonDashException): + """Used on test-device command. The mac address device is not in config file + """ + pass diff --git a/amazon_dash/execute.py b/amazon_dash/execute.py index afa5ab7..dfdbc9a 100644 --- a/amazon_dash/execute.py +++ b/amazon_dash/execute.py @@ -8,7 +8,7 @@ from requests import request, RequestException from amazon_dash._compat import JSONDecodeError from amazon_dash.exceptions import SecurityException, InvalidConfig - +from ._compat import urlparse EXECUTE_SHELL_PARAM = '-c' ROOT_USER = 'root' @@ -24,16 +24,36 @@ def get_shell(name): + """Absolute path to command + + :param str name: command + :return: command args + :rtype: list + """ if name.startswith('/'): return [name] return ['/usr/bin/env', name] def run_as_cmd(cmd, user, shell='bash'): + """Get the arguments to execute a command as a user + + :param str cmd: command to execute + :param user: User for use + :param shell: Bash, zsh, etc. + :return: arguments + :rtype: list + """ return ['sudo', '-s', '--set-home', '-u', user] + get_shell(shell) + [EXECUTE_SHELL_PARAM, cmd] def check_execution_success(cmd, cwd): + """Execute a command and show error on fail + + :param str cmd: command + :param str cwd: current working directory + :return: None + """ p = subprocess.Popen(cmd, cwd=cwd, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if p.returncode: @@ -41,33 +61,73 @@ def check_execution_success(cmd, cwd): def execute_cmd(cmd, cwd=None): + """Excecute command on thread + + :param cmd: Command to execute + :param cwd: current working directory + :return: None + """ l = threading.Thread(target=check_execution_success, args=(cmd, cwd)) l.daemon = True l.start() class Execute(object): + """Execute base class + + """ def __init__(self, name, data): + """ + + :param str name: name or mac address + :param data: data on device section + """ self.name = name self.data = data def validate(self): + """Check self.data. Raise InvalidConfig on error + + :return: None + """ raise NotImplementedError def execute(self, root_allowed=False): + """Execute using self.data + + :param bool root_allowed: Only used for ExecuteCmd + :return: + """ raise NotImplementedError class ExecuteCmd(Execute): + """Execute systemd command + """ + def __init__(self, name, data): + """ + + :param str name: name or mac address + :param data: data on device section + """ super(ExecuteCmd, self).__init__(name, data) self.user = data.get('user', getpass.getuser()) self.cwd = data.get('cwd') def validate(self): + """Check self.data. Raise InvalidConfig on error + + :return: None + """ return def execute(self, root_allowed=False): + """Execute using self.data + + :param bool root_allowed: Allow execute as root commands + :return: + """ if self.user == ROOT_USER and not root_allowed: raise SecurityException('For security, execute commands as root is not allowed. ' 'Use --root-allowed to allow executing commands as root. ' @@ -78,7 +138,14 @@ def execute(self, root_allowed=False): class ExecuteUrl(Execute): + """Call a url + """ + def validate(self): + """Check self.data. Raise InvalidConfig on error + + :return: None + """ if (self.data.get('content-type') or self.data.get('body')) and \ self.data.get('method', '').lower() not in CONTENT_TYPE_METHODS: raise InvalidConfig( @@ -97,6 +164,11 @@ def validate(self): ) def execute(self, root_allowed=False): + """Execute using self.data + + :param bool root_allowed: Only used for ExecuteCmd + :return: + """ kwargs = {} if self.data.get('content-type'): kwargs['headers'] = {'content-type': self.data['content-type']} @@ -109,3 +181,89 @@ def execute(self, root_allowed=False): return if resp.status_code >= 400: logger.warning('"{}" return code {}.'.format(self.data['url'], resp.status_code)) + + +class ExecuteUrlServiceBase(ExecuteUrl): + """Base class to create services execute classes + """ + default_url = None #: default url to call + default_content_type = 'application/json' #: default content type to send + default_method = 'GET' #: default HTTP method + default_body = None #: default body to send + + def __init__(self, name, data): + """ + + :param str name: name or mac address + :param data: data on device section + """ + super(ExecuteUrlServiceBase, self).__init__(name, data) + self.data['url'] = self.get_url() + self.data['content_type'] = self.get_content_type() + self.data['method'] = self.get_method() + self.data['body'] = self.get_body() + + def get_url(self): + """Get url to call. By default default_url + + :return: url + :rtype: str + """ + return self.default_url + + def get_method(self): + """Get HTTP method. By default default_method + + :return: HTTP method + :rtype: str + """ + return self.default_method + + def get_content_type(self): + """Get HTTP content type to send. By default default_content_type + + :return: HTTP content type + :rtype: str + """ + return self.default_content_type + + def get_body(self): + """Get body to send. By default default_body + + :return: body content + :rtype: str + """ + return self.default_body + + +class ExecuteHomeAssistant(ExecuteUrlServiceBase): + """Send Home Assistant event + + https://home-assistant.io/developers/rest_api/#post-apieventsltevent_type + """ + default_method = 'POST' + + def get_url(self): + """Home assistant url + + :return: url + :rtype: str + """ + url = self.data['homeassistant'] + parsed = urlparse(url) + if not parsed.scheme: + url = 'http://{}'.format(url) + if not url.split(':')[-1].isalnum(): + url += ':8123' + if not self.data.get('event'): + raise InvalidConfig(extra_body='Event option is required for HomeAsistant on {} device.'.format(self.name)) + url += '/api/events/{}'.format(self.data['event']) + return url + + def get_body(self): + """Return "data" value on self.data + + :return: data to send + :rtype: str + """ + return self.data.get('data') diff --git a/amazon_dash/install/__init__.py b/amazon_dash/install/__init__.py new file mode 100644 index 0000000..3a47b62 --- /dev/null +++ b/amazon_dash/install/__init__.py @@ -0,0 +1,148 @@ +import os +import shutil +import sys +from subprocess import check_output + +import click as click +from click_default_group import DefaultGroup +from amazon_dash.install.exceptions import InstallException, IsInstallableException, IsNecessaryException + +CONFIG_PATH = '/etc/amazon-dash.yml' +SYSTEMD_PATHS = [ + '/usr/lib/systemd/system', + '/lib/systemd/system', +] +__dir__ = os.path.dirname(os.path.abspath(__file__)) +CONFIG_EXAMPLE = os.path.join(__dir__, 'amazon-dash.yml') +SYSTEMD_SERVICE = os.path.join(__dir__, 'services', 'amazon-dash.service') + + +def get_pid(name): + return check_output(["pidof", name]) + + +def get_systemd_services_path(): + for path in SYSTEMD_PATHS: + if os.path.lexists(path): + return path + + +def catch(fn, exception_cls=None): + exception_cls = exception_cls or InstallException + + def wrap(*args, **kwargs): + try: + return fn(*args, **kwargs) + except exception_cls as e: + click.echo('{}'.format(e), err=True) + return wrap + + +def install_success(name): + click.echo('[OK] {} has been installed successfully'.format(name)) + return True + + +class InstallBase(object): + name = '' + + def is_installable(self): + raise NotImplementedError + + def is_necessary(self): + raise NotImplementedError + + def installation(self): + raise NotImplementedError + + def install(self): + self.is_installable() + self.is_necessary() + self.installation() + return True + + +class InstallConfig(InstallBase): + name = 'config' + + def is_installable(self): + directory = os.path.dirname(CONFIG_PATH) + if not os.path.lexists(directory): + raise IsInstallableException('{} does not exists'.format(directory)) + + def is_necessary(self): + if os.path.lexists(CONFIG_PATH): + raise IsNecessaryException('{} already exists'.format(CONFIG_PATH)) + + def installation(self): + shutil.copy(CONFIG_EXAMPLE, CONFIG_PATH) + os.chmod(CONFIG_PATH, 0o600) + os.chown(CONFIG_PATH, 0, 0) + + +class InstallSystemd(InstallBase): + name = 'systemd' + service_name = os.path.split(SYSTEMD_SERVICE)[-1] + + @property + def service_path(self): + path = get_systemd_services_path() + if not path: + return + return os.path.join(path, self.service_name) + + def is_installable(self): + if not get_pid('systemd') or not get_systemd_services_path(): + raise IsInstallableException('Systemd is not available') + + def is_necessary(self): + if os.path.lexists(self.service_path): + raise IsNecessaryException('Systemd service is already installed') + + def installation(self): + shutil.copy(SYSTEMD_SERVICE, self.service_path) + os.chmod(self.service_path, 0o600) + os.chown(self.service_path, 0, 0) + + +SERVICES = [ + InstallSystemd, +] + + +@click.group(cls=DefaultGroup, default='all', default_if_no_args=True) +@click.option('--root-required/--root-not-required', default=True) +def cli(root_required): + if os.getuid() and root_required: + click.echo('The installation must be done as root. Maybe you forgot sudo?', err=True) + sys.exit(1) + + +@catch +@cli.command() +def config(): + InstallConfig().install() and install_success('config') + + +@catch +@cli.command() +def systemd(): + InstallSystemd().install() and install_success('systemd service') + + +@cli.command() +def all(): + click.echo('Executing all install scripts for Amazon-Dash') + catch(InstallConfig().install)() and install_success('config') + has_service = False + for service in SERVICES: + try: + has_service = has_service or (service().install() and + install_success('{} service'.format(service.name))) + except IsInstallableException: + pass + except IsNecessaryException as e: + has_service = True + click.echo('{}'.format(e), err=True) + if not has_service: + click.echo('Warning: There is no service installed in the system. You must run Amazon-dash manually') diff --git a/amazon_dash/install/__main__.py b/amazon_dash/install/__main__.py new file mode 100644 index 0000000..e292fe6 --- /dev/null +++ b/amazon_dash/install/__main__.py @@ -0,0 +1,3 @@ +from amazon_dash.install import catch, cli + +catch(cli)() diff --git a/amazon_dash/install/amazon-dash.yml b/amazon_dash/install/amazon-dash.yml new file mode 100644 index 0000000..bcd9ce4 --- /dev/null +++ b/amazon_dash/install/amazon-dash.yml @@ -0,0 +1,33 @@ +# amazon-dash.yml +# --------------- +settings: + # On seconds. Minimum time that must pass between pulsations. + delay: 10 +devices: +## Example of how to execute a system command +# 0C:47:C9:98:4A:12: # You can know the mac of your device with the discovery command +# name: Kitcken button # You can put the name you want +# user: nekmo # System user. Necessary if it is executed as root +# cmd: spotify # Command to execute + +## Example of how to execute a url +# AC:63:BE:67:B2:F1: +# name: Kit Kat +# url: 'http://domain.com/path/to/webhook' # Url to execute +# method: post # HTTP method. By default GET +# content-type: json # Only available if Body is defined +# body: '{"mac": "AC:63:BE:67:B2:F1", "action": "toggleLight"}' # Request payload. Remember the quotes + +## Example of how to execute a Homeassistant event +# 40:B4:CD:67:A2:E1: +# name: Fairy +# homeassistant: hassio.local # Address to the hass server +# event: toggle_kitchen_light # Event name to send + + + +# Need help? See the documentation: +# http://docs.nekmo.org/amazon-dash/config_file.html + +# If you still need help open a issue: +# https://github.com/Nekmo/amazon-dash/issues diff --git a/amazon_dash/install/exceptions.py b/amazon_dash/install/exceptions.py new file mode 100644 index 0000000..2e9e829 --- /dev/null +++ b/amazon_dash/install/exceptions.py @@ -0,0 +1,17 @@ +class InstallException(Exception): + name = 'Install Error' + tpl = '[{name}] {body}' + + def __init__(self, body='No details'): + self.body = body + + def __str__(self): + return self.tpl.format(name=self.name, body=self.body) + + +class IsInstallableException(InstallException): + name = 'Unable to install' + + +class IsNecessaryException(InstallException): + name = 'Already installed' \ No newline at end of file diff --git a/services/amazon-dash.service b/amazon_dash/install/services/amazon-dash.service similarity index 64% rename from services/amazon-dash.service rename to amazon_dash/install/services/amazon-dash.service index fca17cc..0e2b486 100644 --- a/services/amazon-dash.service +++ b/amazon_dash/install/services/amazon-dash.service @@ -3,7 +3,7 @@ Description=Amazon Dash service [Service] User=root -ExecStart=/usr/bin/amazon-dash --config /etc/amazon-dash.yml run +ExecStart=/usr/bin/env amazon-dash --config /etc/amazon-dash.yml run Restart=always RestartSec=3 diff --git a/amazon_dash/listener.py b/amazon_dash/listener.py index 5333b73..d35fd57 100644 --- a/amazon_dash/listener.py +++ b/amazon_dash/listener.py @@ -3,23 +3,41 @@ from amazon_dash.config import Config -from amazon_dash.exceptions import InvalidConfig -from amazon_dash.execute import logger, ExecuteCmd, ExecuteUrl +from amazon_dash.exceptions import InvalidConfig, InvalidDevice +from amazon_dash.execute import logger, ExecuteCmd, ExecuteUrl, ExecuteHomeAssistant from amazon_dash.scan import scan_devices DEFAULT_DELAY = 10 +""" +On seconds. By default, 10 seconds. Minimum time that must pass between pulsations of the Amazon Dash button. +""" + EXECUTE_CLS = { 'cmd': ExecuteCmd, 'url': ExecuteUrl, + 'homeassistant': ExecuteHomeAssistant, } +""" +Execute classes registered. +""" last_execution = defaultdict(lambda: 0) +""" +Last time a device was executed. Value on unix time. +""" class Device(object): - execute_instance = None + """Set the execution method for the device + """ + execute_instance = None #: Execute cls instance def __init__(self, src, data=None): + """ + + :param str src: Mac address + :param data: device data + """ data = data or {} if isinstance(src, Device): src = src.src @@ -36,9 +54,19 @@ def __init__(self, src, data=None): @property def name(self): + """Name on self.data or mac address + + :return: name + :rtype: str + """ return self.data.get('name', self.src) def execute(self, root_allowed=False): + """Execute this device + + :param root_allowed: Only used for ExecuteCmd + :return: None + """ logger.debug('%s device executed (mac %s)', self.name, self.src) if not self.execute_instance: logger.warning('%s: There is not execution method in device conf.', self.name) @@ -47,15 +75,27 @@ def execute(self, root_allowed=False): class Listener(object): - root_allowed = False + """Start listener daemon for execute on button press + """ + + root_allowed = False #: Only used for ExecuteCmd def __init__(self, config_path): + """ + + :param str config_path: Path to config file + """ self.config = Config(config_path) self.settings = self.config.get('settings', {}) self.devices = {key.lower(): Device(key, value) for key, value in self.config['devices'].items()} assert len(self.devices) == len(self.config['devices']), "Duplicate(s) MAC(s) on devices config." def on_push(self, device): + """Press button. Check DEFAULT_DELAY. + + :param scapy.packet.Packet device: Scapy packet + :return: None + """ src = device.src.lower() if last_execution[src] + self.settings.get('delay', DEFAULT_DELAY) > time.time(): return @@ -63,10 +103,35 @@ def on_push(self, device): self.execute(device) def execute(self, device): + """Execute a device. Used if the time between executions is greater than DEFAULT_DELAY + + :param scapy.packet.Packet device: Scapy packet + :return: None + """ src = device.src.lower() device = self.devices[src] device.execute(root_allowed=self.root_allowed) def run(self, root_allowed=False): + """Start daemon mode + + :param bool root_allowed: Only used for ExecuteCmd + :return: loop + """ self.root_allowed = root_allowed scan_devices(self.on_push, lambda d: d.src.lower() in self.devices) + + +def test_device(device, file, root_allowed=False): + """Test the execution of a device without pressing the associated button + + :param str device: mac address + :param str file: config file + :param bool root_allowed: only used for ExecuteCmd + :return: None + """ + config = Config(file) + config.read() + if not device in config['devices']: + raise InvalidDevice('Device {} is not in config file.'.format(device)) + Device(device, config['devices'][device]).execute(root_allowed) diff --git a/amazon_dash/management.py b/amazon_dash/management.py index 7e5cd9c..74c1242 100644 --- a/amazon_dash/management.py +++ b/amazon_dash/management.py @@ -6,13 +6,20 @@ import sys +from amazon_dash.config import check_config from amazon_dash.exceptions import AmazonDashException -from amazon_dash.listener import Listener +from amazon_dash.listener import Listener, test_device CONFIG_FILE = 'amazon-dash.yml' def create_logger(name, level=logging.INFO): + """Create a Logger and set handler and formatter + + :param name: logger name + :param level: logging level + :return: None + """ # create logger logger = logging.getLogger(name) logger.setLevel(level) @@ -37,6 +44,9 @@ def set_default_subparser(self, name, args=None): args: if set is the argument list handed to parse_args() , tested with 2.7, 3.2, 3.3, 3.4 it works with 2.6 assuming argparse is installed + + :param str name: default command + :param list args: defaults args for default command """ subparser_found = False for arg in sys.argv[1:]: @@ -61,16 +71,24 @@ def set_default_subparser(self, name, args=None): def execute_args(args): + """Execute args.which command + + :param args: argparse args + :return: None + """ if not getattr(args, 'which', None) or args.which == 'run': Listener(args.config).run(root_allowed=args.root_allowed) + elif args.which == 'check-config': + check_config(args.config) + elif args.which == 'test-device': + test_device(args.device, args.config, args.root_allowed) elif args.which == 'discovery': from amazon_dash.discovery import discover discover() def execute_from_command_line(argv=None): - """ - A simple method that runs a ManagementUtility. + """A simple method that runs a ManagementUtility. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', default=CONFIG_FILE, help='Path to config file.') @@ -90,6 +108,14 @@ def execute_from_command_line(argv=None): parse_service = parser.sub.add_parser('discovery', help='Discover Amazon Dash device on network.') parse_service.set_defaults(which='discovery') + parse_service = parser.sub.add_parser('check-config', help='Validate the configuration file.') + parse_service.set_defaults(which='check-config') + + parse_service = parser.sub.add_parser('test-device', help='Test a configured device without press button.') + parse_service.set_defaults(which='test-device') + parse_service.add_argument('device', help='MAC address') + parse_service.add_argument('--root-allowed', action='store_true') + parse_oneshot = parser.sub.add_parser('run', help='Run server') parse_oneshot.set_defaults(which='run') parse_oneshot.add_argument('--root-allowed', action='store_true') diff --git a/amazon_dash/scan.py b/amazon_dash/scan.py index 5f053a2..6cfbd88 100644 --- a/amazon_dash/scan.py +++ b/amazon_dash/scan.py @@ -14,6 +14,12 @@ def scan_devices(fn, lfilter): + """Sniff packages + + :param fn: callback on packet + :param lfilter: filter packages + :return: loop + """ try: sniff(prn=fn, store=0, filter="udp", lfilter=lfilter) except PermissionError: diff --git a/amazon_dash/tests/_compat.py b/amazon_dash/tests/_compat.py index 49214bd..8388433 100644 --- a/amazon_dash/tests/_compat.py +++ b/amazon_dash/tests/_compat.py @@ -1,5 +1,5 @@ try: - from mock import patch, Mock + from mock import patch, Mock, mock_open except ImportError: - from unittest.mock import patch, Mock + from unittest.mock import patch, Mock, mock_open diff --git a/amazon_dash/tests/test_config.py b/amazon_dash/tests/test_config.py index f531165..83becfe 100644 --- a/amazon_dash/tests/test_config.py +++ b/amazon_dash/tests/test_config.py @@ -4,7 +4,7 @@ from pyfakefs.fake_filesystem_unittest import Patcher -from amazon_dash.config import Config, only_root_write, oth_w_perm +from amazon_dash.config import Config, only_root_write, oth_w_perm, check_config from amazon_dash.exceptions import SecurityException, InvalidConfig from amazon_dash.tests.base import FileMockBase @@ -124,3 +124,21 @@ def test_user_owner(self): os.chmod(self.file, 0o660) self.assertFalse(only_root_write(self.file)) + +class TestCheckConfig(unittest.TestCase): + def test_fail(self): + file = 'amazon-dash.yml' + with Patcher() as patcher: + patcher.fs.CreateFile(file, contents='invalid config') + os.chown(file, 0, 0) + os.chmod(file, 0o600) + with self.assertRaises(InvalidConfig): + check_config(file) + + def test_success(self): + file = 'amazon-dash.yml' + with Patcher() as patcher: + patcher.fs.CreateFile(file, contents=config_data) + os.chown(file, 0, 0) + os.chmod(file, 0o600) + check_config(file, lambda x: x) diff --git a/amazon_dash/tests/test_execute.py b/amazon_dash/tests/test_execute.py index ef711c7..c98d455 100644 --- a/amazon_dash/tests/test_execute.py +++ b/amazon_dash/tests/test_execute.py @@ -7,7 +7,8 @@ from amazon_dash.tests._compat import patch as mock_patch, Mock from amazon_dash.exceptions import SecurityException, InvalidConfig -from amazon_dash.execute import ExecuteCmd, ExecuteUrl, logger, execute_cmd, check_execution_success, get_shell +from amazon_dash.execute import ExecuteCmd, ExecuteUrl, logger, execute_cmd, check_execution_success, get_shell, \ + ExecuteHomeAssistant from amazon_dash.tests.base import ExecuteMockBase import requests_mock @@ -144,7 +145,48 @@ def test_execute_400(self): execute_url.execute() warning_mock.assert_called_once() - def tearDown(self): super(TestExecuteUrl, self).tearDown() self.session_mock.stop() + + +class TestExecuteHomeAssistant(unittest.TestCase): + path = '/api/events/test' + url = 'http://localhost:8123' + path + + def default_data(self, address='localhost', event='test'): + return { + 'homeassistant': address, + 'event': event, + } + + def test_no_event(self): + with self.assertRaises(InvalidConfig): + ExecuteHomeAssistant('key', self.default_data(event='')) + + def test_only_address(self): + assis = ExecuteHomeAssistant('key', self.default_data()) + self.assertIn('url', assis.data) + self.assertEqual(assis.data['url'], self.url) + + def test_include_address_protocol(self): + assis = ExecuteHomeAssistant('key', self.default_data('https://localhost')) + self.assertIn('url', assis.data) + self.assertEqual(assis.data['url'], 'https://localhost:8123' + self.path) + + def test_include_address_port(self): + assis = ExecuteHomeAssistant('key', self.default_data('localhost:7123')) + self.assertIn('url', assis.data) + self.assertEqual(assis.data['url'], 'http://localhost:7123' + self.path) + + def test_full_address(self): + assis = ExecuteHomeAssistant('key', self.default_data('https://localhost:7123')) + self.assertIn('url', assis.data) + self.assertEqual(assis.data['url'], 'https://localhost:7123' + self.path) + + def test_execute(self): + with requests_mock.mock() as m: + m.post(self.url, text='success') + assis = ExecuteHomeAssistant('key', self.default_data()) + assis.execute() + self.assertTrue(m.called_once) diff --git a/amazon_dash/tests/test_install.py b/amazon_dash/tests/test_install.py new file mode 100644 index 0000000..22bc289 --- /dev/null +++ b/amazon_dash/tests/test_install.py @@ -0,0 +1,95 @@ +import unittest +import os + +from click.testing import CliRunner + +from ._compat import patch + +from pyfakefs.fake_filesystem_unittest import Patcher + +from amazon_dash.install import InstallConfig, IsInstallableException, CONFIG_PATH, IsNecessaryException, \ + CONFIG_EXAMPLE, SYSTEMD_PATHS, InstallSystemd, SYSTEMD_SERVICE, cli + + +class TestInstallConfig(unittest.TestCase): + def test_is_installable(self): + with Patcher() as patcher: + with self.assertRaises(IsInstallableException): + InstallConfig().is_installable() + patcher.fs.CreateFile(CONFIG_PATH) + InstallConfig().is_installable() + + def test_is_necessary(self): + with Patcher() as patcher: + InstallConfig().is_necessary() + patcher.fs.CreateFile(CONFIG_PATH) + with self.assertRaises(IsNecessaryException): + InstallConfig().is_necessary() + + def test_installation(self): + with Patcher() as patcher: + os.makedirs(os.path.dirname(CONFIG_PATH)) + patcher.fs.CreateFile(CONFIG_EXAMPLE) + InstallConfig().installation() + stat = os.stat(CONFIG_PATH) + self.assertEqual(stat.st_mode, 0o100600) + self.assertEqual(stat.st_uid, 0) + self.assertEqual(stat.st_gid, 0) + + +class TestInstallSystemd(unittest.TestCase): + @patch('amazon_dash.install.get_pid', return_value=1000) + def test_is_installable(self, mock_check_output): + with Patcher() as patcher: + with self.assertRaises(IsInstallableException): + InstallSystemd().is_installable() + patcher.fs.CreateFile(SYSTEMD_PATHS[0]) + InstallSystemd().is_installable() + + def test_is_necessary(self): + with Patcher() as patcher: + os.makedirs(SYSTEMD_PATHS[0]) + InstallSystemd().is_necessary() + path = os.path.join(SYSTEMD_PATHS[0], os.path.split(SYSTEMD_SERVICE)[1]) + patcher.fs.CreateFile(path) + with self.assertRaises(IsNecessaryException): + InstallSystemd().is_necessary() + + def test_installation(self): + with Patcher() as patcher: + os.makedirs(SYSTEMD_PATHS[0]) + path = os.path.join(SYSTEMD_PATHS[0], os.path.split(SYSTEMD_SERVICE)[1]) + patcher.fs.CreateFile(SYSTEMD_SERVICE) + InstallSystemd().installation() + stat = os.stat(path) + self.assertEqual(stat.st_mode, 0o100600) + self.assertEqual(stat.st_uid, 0) + self.assertEqual(stat.st_gid, 0) + + +class TestClickAll(unittest.TestCase): + @patch('amazon_dash.install.get_pid', return_value=1000) + def test_no_services(self, mock_check_output): + with Patcher() as patcher: + patcher.fs.CreateFile(CONFIG_PATH) + runner = CliRunner() + result = runner.invoke(cli, ['--root-not-required', 'all']) + self.assertIn('You must run Amazon-dash manually', result.output) + + @patch('amazon_dash.install.get_pid', return_value=1000) + def test_is_not_necessary(self, mock_check_output): + with Patcher() as patcher: + patcher.fs.CreateFile(CONFIG_PATH) + path = os.path.join(SYSTEMD_PATHS[0], os.path.split(SYSTEMD_SERVICE)[1]) + patcher.fs.CreateFile(path) + runner = CliRunner() + result = runner.invoke(cli, ['--root-not-required', 'all']) + self.assertIn('Systemd service is already installed', result.output) + + +class TestCli(unittest.TestCase): + @patch('amazon_dash.install.get_pid', return_value=1000) + def test_root_required(self, mock_check_output): + runner = CliRunner() + result = runner.invoke(cli, []) + self.assertIn('Maybe you forgot sudo?', result.output) diff --git a/amazon_dash/tests/test_listener.py b/amazon_dash/tests/test_listener.py index faf4433..a97c225 100644 --- a/amazon_dash/tests/test_listener.py +++ b/amazon_dash/tests/test_listener.py @@ -3,8 +3,8 @@ import os from amazon_dash.tests._compat import patch -from amazon_dash.exceptions import InvalidConfig -from amazon_dash.listener import Listener, Device, last_execution, logger +from amazon_dash.exceptions import InvalidConfig, InvalidDevice +from amazon_dash.listener import Listener, Device, last_execution, logger, test_device from amazon_dash.tests.base import ConfigFileMockBase, ExecuteMockBase __dir__ = os.path.abspath(os.path.dirname(__file__)) @@ -66,3 +66,15 @@ def test_device_src(self): device = Device('key') device2 = Device(device) self.assertEqual(device.src, device2.src) + + +class TestTestListener(ExecuteMockBase, ConfigFileMockBase, unittest.TestCase): + contents = config_data + + def test_invalid_device(self): + with self.assertRaises(InvalidDevice): + test_device('00:11:22:33:44:55', self.file) + + def test_success(self): + test_device('44:65:0D:48:FA:88', self.file) + self.execute_mock_req.assert_called_once() diff --git a/common-requirements.txt b/common-requirements.txt index c846a06..ac6e859 100644 --- a/common-requirements.txt +++ b/common-requirements.txt @@ -1,3 +1,5 @@ PyYAML>=3.0 jsonschema -requests \ No newline at end of file +requests +click +click-default-group \ No newline at end of file diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 0000000..944d79f --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1,3 @@ +/amazon_dash.rst +/amazon_dash.*.rst +/modules.rst diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..f32bd1b --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,185 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXAPIDOC = sphinx-apidoc +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " watch Browser Sync watcher for build HTML files on real time" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXAPIDOC) -o . ../amazon_dash + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +watch: + gulp watch + @echo + @echo "Finished." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/amazon-dash.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/amazon-dash.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/amazon-dash" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/amazon-dash" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." \ No newline at end of file diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..8ec98ea --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,9 @@ +#welcome-to-amazon-dash-s-documentation table, #python-amazon-dash table { + border: 0; + box-shadow: none; +} + +#welcome-to-amazon-dash-s-documentation table td, #python-amazon-dash table td { + border: 0; + text-align: center; +} \ No newline at end of file diff --git a/docs/_static/logo.png b/docs/_static/logo.png new file mode 100644 index 0000000..a71797d Binary files /dev/null and b/docs/_static/logo.png differ diff --git a/docs/authors.rst b/docs/authors.rst new file mode 100644 index 0000000..e122f91 --- /dev/null +++ b/docs/authors.rst @@ -0,0 +1 @@ +.. include:: ../AUTHORS.rst diff --git a/docs/avoid_purchase.rst b/docs/avoid_purchase.rst new file mode 100644 index 0000000..0e57fab --- /dev/null +++ b/docs/avoid_purchase.rst @@ -0,0 +1,31 @@ + +Avoid making a purchase by pressing the button +============================================== +This program detects when your button connects to the network to execute actions, but does not prevent the ordering. + +There are 3 ways to avoid making a purchase when you press the button. + + +Easy mode: Do not choose the product to buy when setting up +----------------------------------------------------------- +When you first set your button, you are asked which product you want to buy when you press the button. If you do not +choose an option, the button will work, but an order will not be created. + +However, in order to take advantage of the free balance ($5/€5/£5), it is necessary to choose a product. The solution +is after ordering, reconfigure it (press the button again for 5 seconds), and not choosing the product the second time. + +However, you will receive an alert in the Amazon application every time you press the button asking you to finish the +configuration. You can turn off notifications, delete the application, or use another Amazon account. + + +Using an advanced router +------------------------ +If you have an advanced router (DD-Wrt, Open-WRT, Tomato, RouterOS...), you can block Internet output from the buttons. +This is the preferred option. It is necessary to block the Internet output. Using DNS locks will not work. The button +uses its own DNS server IP, ignoring router DNS. + + +Raspberry PI solution +--------------------- +You can use the Raspberry PI as a router if you have 2 network cards. The method is similar to the previous one, but +being a Linux system you can use iptables. diff --git a/docs/conf.py b/docs/conf.py new file mode 100755 index 0000000..33edf53 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# amazon_dash documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 9 22:26:36 2013. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +__dir__ = os.path.dirname(__file__) + +# If extensions (or modules to document with autodoc) are in another +# directory, add these directories to sys.path here. If the directory is +# relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# Get the project root dir, which is the parent dir of this +project_root = os.path.dirname(__dir__) + +# Insert the project root dir as the first element in the PYTHONPATH. +# This lets us ensure that the source package is imported, and that its +# version is used. +sys.path.insert(0, project_root) + +import amazon_dash + +# -- General configuration --------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'amazon-dash' +copyright = u"2018, Nekmo" + +# The version info for the project you're documenting, acts as replacement +# for |version| and |release|, also used in various other places throughout +# the built documents. +# +# The short X.Y version. +version = amazon_dash.__version__ +# The full version, including alpha/beta/rc tags. +release = amazon_dash.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to +# some non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built +# documents. +#keep_warnings = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a +# theme further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + 'logo': 'logo.png', + 'description': 'Hack your Amazon Dash to run what you want', + 'github_user': 'Nekmo', + 'github_repo': 'amazon-dash', + 'github_type': 'star', + 'github_banner': True, + 'travis_button': True, + 'codecov_button': True, + 'analytics_id': 'UA-62276079-1', + 'canonical_url': 'http://docs.nekmo.org/amazon-dash/' +} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +html_sidebars = { + '**': [ + 'about.html', + 'navigation.html', + 'relations.html', + 'searchbox.html', + 'donate.html', + ] +} + + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as +# html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the +# top of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon +# of the docs. This file should be a Windows icon file (.ico) being +# 16x16 or 32x32 pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) +# here, relative to this directory. They are copied after the builtin +# static files, so a file named "default.css" will overwrite the builtin +# "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names +# to template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. +# Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. +# Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages +# will contain a tag referring to it. The value of this option +# must be the base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'amazon_dashdoc' + + +# -- Options for LaTeX output ------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + #'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass +# [howto/manual]). +latex_documents = [ + ('index', 'amazon_dash.tex', + u'amazon-dash Documentation', + u'Nekmo', 'manual'), +] + +# The name of an image file (relative to this directory) to place at +# the top of the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings +# are parts, not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output ------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'amazon_dash', + u'amazon-dash Documentation', + [u'Nekmo'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ---------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'amazon_dash', + u'amazon-dash Documentation', + u'Nekmo', + 'amazon_dash', + 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False + + +def setup(app): + app.add_stylesheet('_static/custom.css') diff --git a/docs/config_file.rst b/docs/config_file.rst new file mode 100644 index 0000000..c34fefe --- /dev/null +++ b/docs/config_file.rst @@ -0,0 +1,65 @@ +=========== +Config file +=========== + +The configuration file can be found anywhere but if the program runs in root mode, +it is necessary that only root can modify the file. This is a security measure to prevent +someone from executing commands as root using the program. + +To change the permissions:: + + sudo chmod 600 amazon-dash.yml + sudo chown root:root amazon-dash.yml + + +Common options +-------------- +The syntax of the configuration file is yaml. The configuration file has 2 main sections: + +* **settings** (optional): common options. +* **devices** (required): The amazon dash devices. + +The following options are available in **settings**: + +* **delay** (optional): On seconds. By default, 10 seconds. Minimum time that must pass between pulsations of the + Amazon Dash button. + +Each device is identified by the button **mac**. The mac can be obtained with the discovery command. +In the configuration of each button, there may be a way of execution. Only one execution method is allowed +for each device. The available exection methods are: + +* **cmd**: local command line command. Arguments can be placed after the command. +* **url**: Call a url. +* **homeassistant**: send event to Homeassistant. This argument must be the address to the hass server (protocol and + port are optional. By default http and 8123, respectively). + +Execute cmd +----------- +When the **cmd execution method** is used, the following options are available. + +* **user**: System user that will execute the command. This option can only be used if Amazon-Dash is running as root. +* **cwd**: Directory in which the command will be executed. + +Call url +-------- +When the **url execution method** is used, the following options are available. + +* **method**: HTTP method. By default GET. +* **content-type** (*): HTTP Content-Type Header. Only available if Body is defined. If body is defined, default is form. +* **body**: Request payload. Only if the method is POST/PUT/PATCH. In json or form mode, the content must be a valid json. It is recommended to use single quotes before and after content in json. + +(*) Content type aliases: `form = application/x-www-form-urlencoded`. `json = application/json`. `plain = text/plain`. + +Homeassistant event +------------------- +When the **homeassistant execution method** is used, the following options are available. + +* **event** (required): Event name to send. +* **data**: Event data to send. Use json as string. + +Example +------- +The following example is available in /etc/amazon-dash.yml when installed: + +.. literalinclude:: ../amazon_dash/install/amazon-dash.yml + diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..e582053 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1 @@ +.. include:: ../CONTRIBUTING.rst diff --git a/docs/gulpfile.js b/docs/gulpfile.js new file mode 100644 index 0000000..a4c8316 --- /dev/null +++ b/docs/gulpfile.js @@ -0,0 +1,24 @@ +var gulp = require('gulp'); +var exec = require('child_process').exec; +var bs = require('browser-sync').create(); + +gulp.task('browser-sync', [], function() { + bs.init({ + server: { + baseDir: "./_build/html" + } + }); +}); + +gulp.task('make-html', function (cb) { + exec('make html', function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('watch', ['browser-sync'], function () { + gulp.watch("*.rst", ['make-html']); + gulp.watch("**/*.html").on('change', bs.reload); +}); diff --git a/docs/history.rst b/docs/history.rst new file mode 100644 index 0000000..2506499 --- /dev/null +++ b/docs/history.rst @@ -0,0 +1 @@ +.. include:: ../HISTORY.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..93dcc59 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,50 @@ +Welcome to amazon-dash's documentation! +======================================= +Amazon Dash buttons are sold by Amazon to purchase certain products from their store. The buttons are sold for +$5/€5/£5 but Amazon gives you the money to spend on products. This project allows you to reprogram these buttons +purchased *"almost free"* to do what you want. To use this project you need a linux computer (for example a Raspberry +PI). + +To **install** amazon-dash, run these commands in your terminal: + +.. code-block:: console + + $ pip install amazon_dash + $ sudo python -m amazon_dash.install + +Actions supported in this project for your Amazon Dash buttons: + +================================ ================================ ================================ +.. image:: https://goo.gl/bq5QSK .. image:: https://goo.gl/k4DJmf .. image:: https://goo.gl/Gqo8W3 +`System command`_ `Call url`_ `Homeassistant`_ +================================ ================================ ================================ + + +Contents +-------- + +.. toctree:: + :maxdepth: 2 + + readme + installation + usage + avoid_purchase + config_file + troubleshooting + modules + contributing + authors + history + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + +.. _System command: http://docs.nekmo.org/amazon-dash/config_file.html#execute-cmd +.. _Call url: http://docs.nekmo.org/amazon-dash/config_file.html#call-url +.. _Homeassistant: http://docs.nekmo.org/amazon-dash/config_file.html#homeassistant-event + diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..afd71ed --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,77 @@ +.. highlight:: console + +============ +Installation +============ + + +Stable release +-------------- + +To install amazon-dash, run these commands in your terminal: + +.. code-block:: console + + $ pip install amazon_dash + $ sudo python -m amazon_dash.install + +This is the preferred method to install amazon-dash, as it will always install the most recent stable release. + +If you don't have `pip`_ installed, this `Python installation guide`_ can guide +you through the process. + +.. _pip: https://pip.pypa.io +.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ + + +Other releases +-------------- +You can install other versions from Pypi using:: + + $ pip install amazon-dash== + $ sudo python -m amazon_dash.install + +For versions that are not in Pypi (it is a development version):: + + $ pip install git+https://github.com/Nekmo/amazon-dash.git@#egg=amazon-dash + $ sudo python -m amazon_dash.install + + +Distro packages +--------------- + +Arch Linux +`````````` +If you use Arch Linux or an Arch Linux derivative, you can install Amazon Dash from +`AUR `_. For example if you use yaourt:: + + $ yaourt -S amazon-dash-git + + +From sources +------------ + +The sources for amazon-dash can be downloaded from the `Github repo`_. + +You can either clone the public repository: + +.. code-block:: console + + $ git clone git://github.com/Nekmo/amazon-dash + +Or download the `tarball`_: + +.. code-block:: console + + $ curl -OL https://github.com/Nekmo/amazon-dash/tarball/master + +Once you have a copy of the source, you can install it with: + +.. code-block:: console + + $ python setup.py install + $ sudo python -m amazon_dash.install + + +.. _Github repo: https://github.com/Nekmo/amazon-dash +.. _tarball: https://github.com/Nekmo/amazon-dash/tarball/master diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..a588a0e --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\amazon_dash.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\amazon_dash.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/docs/package.json b/docs/package.json new file mode 100644 index 0000000..49ed789 --- /dev/null +++ b/docs/package.json @@ -0,0 +1,15 @@ +{ + "name": "docs", + "version": "1.0.0", + "description": ".. include:: ../README.rst", + "main": "gulpfile.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "browser-sync": "^2.23.6", + "gulp": "^3.9.1" + } +} diff --git a/docs/readme.rst b/docs/readme.rst new file mode 100644 index 0000000..72a3355 --- /dev/null +++ b/docs/readme.rst @@ -0,0 +1 @@ +.. include:: ../README.rst diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst new file mode 100644 index 0000000..ed3042f --- /dev/null +++ b/docs/troubleshooting.rst @@ -0,0 +1,25 @@ +Troubleshooting +=============== + +Requirements and installation +----------------------------- +All dependencies are commonly used on a Linux system, but some may not be installed on your system. The dependencies +are: + +* Python 2.7 or 3.4+. +* Python-pip (pip). +* Tcpdump. +* Sudo + + +Why root is required +-------------------- +This program needs permission to open raw sockets on your system. You can set this permission using setcap, but you +must be very careful about who can run the program. Raw sockets permission could allow scaling permissions on the +system:: + + setcap cap_net_raw=eip ./scripts/amazon-dash + setcap cap_net_raw=eip /usr/bin/pythonX.X + setcap cap_net_raw=eip /usr/bin/tcpdump + +http://stackoverflow.com/questions/36215201/python-scapy-sniff-without-root diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..525f1a9 --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,129 @@ +.. highlight:: console + +===== +Usage +===== +To see the available help run:: + + $ amazon-dash --help + +Example:: + + usage: amazon-dash [-h] [--config CONFIG] [--warning] [--quiet] [--debug] + [--verbose] + {discovery,check-config,test-device,run} ... + + Amazon Dash. + + positional arguments: + {discovery,check-config,test-device,run} + discovery Discover Amazon Dash device on network. + check-config Validate the configuration file. + test-device Test a configured device without press button. + run Run server + + optional arguments: + -h, --help show this help message and exit + --config CONFIG Path to config file. + --warning set logging to warning + --quiet set logging to ERROR + --debug set logging to DEBUG + --verbose set logging to COMM + + +To see the help of a command:: + + $ amazon-dash --help + +For example:: + + $ amazon-dash run --help + + + usage: amazon-dash run [-h] [--root-allowed] + + optional arguments: + -h, --help show this help message and exit + --root-allowed + + +Discovery mode +-------------- +Use *discovery mode* **to know the mac of your Dash** (Run the program, and then press the button):: + + $ sudo amazon-dash discovery + + +Daemon mode +----------- +In daemon mode, it waits for a button to be pressed to execute the associated command. The program will remain running +until the user closes it. Amazon-dash creates a *service* (daemon) file on your system to be able to run the program +easily. The file is copied to your system when you run ``python -m amazon_dash.install``. + + +Systemd +``````` +Most modern Linux systems use Systemd by default. Some exceptions are Slackware and Gentoo. To run amazon-dash using +Systemd:: + + $ sudo systemctl start amazon-dash + +To check if it has been executed correctly:: + + $ sudo systemctl status amazon-dash + +.. hint:: + Run ``$ sudo amazon-dash --config /etc/amazon-dash.yml check-config`` to verify that the configuration is correct + before running amazon-dash + +To restart amazon-dash after modifying the configuration file to apply the changes:: + + $ sudo systemctl restart amazon-dash + +To see the log:: + + $ sudo journalctl -r -u amazon-dash + +To run Amazon-dash at startup:: + + $ sudo systemctl enable amazon-dash + + + +Manually +```````` +If your system does not have Systemd or you want to run it manually:: + + sudo amazon-dash[ --config amazon-dash.yml] run[ --root-allowed] + + +By default, ``amazon-dash`` will use the ``amazon-dash.yml`` file in the current directory with +``sudo amazon-dash run``. However, you can set the path to the file (for example, ``/etc/amazon-dash.yml``) with +``--config`` parameter. Please note that ``--config`` must be before ``run``. + +The default level logging is ``INFO`` but you can change it using the ``--warning``, ``--quiet``, ``--debug`` and +``--verbose`` options. To see on screen every time a button is pressed you need to set the ``--debug`` option. + +By default it is forbidden to execute commands as root in your configuration file. This is a security measure to +avoid escalation privileges. If you are going to run amazon-dash as root it is highly recommended to define a +user by each cmd config device. You can disable this security measure using ``--root-allowed``. + + +Check config +------------ +If you have edited the configuration file you can check that the file is ok before starting the program:: + + $ sudo amazon-dash --config /etc/amazon-dash.yml check-config + + +Test device +----------- +Sometimes you may want to test the execution of a device without pressing the associated button. This is useful for +testing and debugging:: + + $ sudo amazon-dash --config test-device [ --root-allowed] + +For example:: + + $ sudo amazon-dash --config /etc/amazon-dash.yml test-device 00:11:22:33:44:55 + diff --git a/amazon-dash.xcf b/images/amazon-dash.xcf similarity index 92% rename from amazon-dash.xcf rename to images/amazon-dash.xcf index 9b8e059..6d4b16c 100644 Binary files a/amazon-dash.xcf and b/images/amazon-dash.xcf differ diff --git a/images/bash.png b/images/bash.png new file mode 100644 index 0000000..9d0f4be Binary files /dev/null and b/images/bash.png differ diff --git a/images/homeassistant.png b/images/homeassistant.png new file mode 100644 index 0000000..0ce4616 Binary files /dev/null and b/images/homeassistant.png differ diff --git a/images/http.png b/images/http.png new file mode 100644 index 0000000..32f80ac Binary files /dev/null and b/images/http.png differ diff --git a/images/logo.png b/images/logo.png new file mode 100644 index 0000000..a71797d Binary files /dev/null and b/images/logo.png differ diff --git a/images/logo.xcf b/images/logo.xcf new file mode 100644 index 0000000..ae1125c Binary files /dev/null and b/images/logo.xcf differ diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..53ab5a4 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +pyfakefs>=3.3 +requests-mock>=1.4.0 +Sphinx \ No newline at end of file diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..6ffd931 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,9 @@ + +[bdist_wheel] +universal = 1 + +[flake8] +exclude = docs + +[aliases] +# Define setup.py command aliases here diff --git a/travis_pypi_setup.py b/travis_pypi_setup.py new file mode 100644 index 0000000..5dcf320 --- /dev/null +++ b/travis_pypi_setup.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Update encrypted deploy password in Travis config file.""" + + +from __future__ import print_function +import base64 +import json +import os +from getpass import getpass +import yaml +from cryptography.hazmat.primitives.serialization import load_pem_public_key +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 + + +try: + from urllib import urlopen +except ImportError: + from urllib.request import urlopen + + +GITHUB_REPO = 'Nekmo/nginx_sites' +TRAVIS_CONFIG_FILE = os.path.join( + os.path.dirname(os.path.abspath(__file__)), '.travis.yml') + + +def load_key(pubkey): + """Load public RSA key. + + Work around keys with incorrect header/footer format. + + Read more about RSA encryption with cryptography: + https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ + """ + try: + return load_pem_public_key(pubkey.encode(), default_backend()) + except ValueError: + # workaround for https://github.com/travis-ci/travis-api/issues/196 + pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') + return load_pem_public_key(pubkey.encode(), default_backend()) + + +def encrypt(pubkey, password): + """Encrypt password using given RSA public key and encode it with base64. + + The encrypted password can only be decrypted by someone with the + private key (in this case, only Travis). + """ + key = load_key(pubkey) + encrypted_password = key.encrypt(password, PKCS1v15()) + return base64.b64encode(encrypted_password) + + +def fetch_public_key(repo): + """Download RSA public key Travis will use for this repo. + + Travis API docs: http://docs.travis-ci.com/api/#repository-keys + """ + keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) + data = json.loads(urlopen(keyurl).read().decode()) + if 'key' not in data: + errmsg = "Could not find public key for repo: {}.\n".format(repo) + errmsg += "Have you already added your GitHub repo to Travis?" + raise ValueError(errmsg) + return data['key'] + + +def prepend_line(filepath, line): + """Rewrite a file adding a line to its beginning.""" + with open(filepath) as f: + lines = f.readlines() + + lines.insert(0, line) + + with open(filepath, 'w') as f: + f.writelines(lines) + + +def load_yaml_config(filepath): + """Load yaml config file at the given path.""" + with open(filepath) as f: + return yaml.load(f) + + +def save_yaml_config(filepath, config): + """Save yaml config file at the given path.""" + with open(filepath, 'w') as f: + yaml.dump(config, f, default_flow_style=False) + + +def update_travis_deploy_password(encrypted_password): + """Put `encrypted_password` into the deploy section of .travis.yml.""" + config = load_yaml_config(TRAVIS_CONFIG_FILE) + + config['deploy']['password'] = dict(secure=encrypted_password) + + save_yaml_config(TRAVIS_CONFIG_FILE, config) + + line = ('# This file was autogenerated and will overwrite' + ' each time you run travis_pypi_setup.py\n') + prepend_line(TRAVIS_CONFIG_FILE, line) + + +def main(args): + """Add a PyPI password to .travis.yml so that Travis can deploy to PyPI. + + Fetch the Travis public key for the repo, and encrypt the PyPI password + with it before adding, so that only Travis can decrypt and use the PyPI + password. + """ + public_key = fetch_public_key(args.repo) + password = args.password or getpass('PyPI password: ') + update_travis_deploy_password(encrypt(public_key, password.encode())) + print("Wrote encrypted password to .travis.yml -- you're ready to deploy") + + +if '__main__' == __name__: + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--repo', default=GITHUB_REPO, + help='GitHub repo (default: %s)' % GITHUB_REPO) + parser.add_argument('--password', + help='PyPI password (will prompt if not provided)') + + args = parser.parse_args() + main(args)