diff --git a/.gitignore b/.gitignore index a11f6fad..104f54c1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ **.DS_Store src/build src/dist +src/.eggs src/.project src/.pydevproject src/.settings/ @@ -13,3 +14,6 @@ build/lib.* build/temp.* dist *.egg-info +docs/_*/* +docs/autodoc/ +pyan/ diff --git a/.travis.yml b/.travis.yml index 6534ee9f..6b0e4916 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,5 @@ addons: - build-essential - libcap-dev install: - - pip install -r requirements.txt - python setup.py install script: pybitmessage -t diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index a894f907..c820c50d 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,15 +1,33 @@ -## Code contributions to the Bitmessage project +## Repository contributions to the PyBitmessage project -- try to explain what the code is about -- try to follow [PEP0008](https://www.python.org/dev/peps/pep-0008/) -- make the pull request against the ["v0.6" branch](https://github.com/Bitmessage/PyBitmessage/tree/v0.6) -- PGP-sign the commits included in the pull request -- try to use a good editor that removes trailing whitespace, highlights potential python issues and uses unix line endings - You can get paid for merged commits if you register at [Tip4Commit](https://tip4commit.com/github/Bitmessage/PyBitmessage) -If for some reason you don't want to use github, you can submit the patch using Bitmessage to the "bitmessage" chan, or to one of the developers. +### Code + +- Try to refer to github issue tracker or other permanent sources of discussion about the issue. +- It is clear from the diff *what* you have done, it may be less clear *why* you have done it so explain why this change is necessary rather than what it does + +### Documentation + +- If there has been a change to the code, there's a good possibility there should be a corresponding change to the documentation +- If you can't run `fab build_docs` successfully, ask for someone to run it against your branch + +### Tests + +- If there has been a change to the code, there's a good possibility there should be a corresponding change to the tests +- If you can't run `fab tests` successfully, ask for someone to run it against your branch + ## Translations -For helping with translations, please use [Transifex](https://www.transifex.com/bitmessage-project/pybitmessage/). There is no need to submit pull requests for translations. -For translating technical terms it is recommended to consult the [Microsoft Language Portal](https://www.microsoft.com/Language/en-US/Default.aspx). +- For helping with translations, please use [Transifex](https://www.transifex.com/bitmessage-project/pybitmessage/). +- There is no need to submit pull requests for translations. +- For translating technical terms it is recommended to consult the [Microsoft Language Portal](https://www.microsoft.com/Language/en-US/Default.aspx). + +### Gitiquette + +- Make the pull request against the ["v0.6" branch](https://github.com/Bitmessage/PyBitmessage/tree/v0.6) +- PGP-sign the commits included in the pull request +- Use references to tickets, e.g. `addresses #123` or `fixes #234` in your commit messages +- Try to use a good editor that removes trailing whitespace, highlights potential python issues and uses unix line endings +- If for some reason you don't want to use github, you can submit the patch using Bitmessage to the "bitmessage" chan, or to one of the developers. diff --git a/checkdeps.py b/checkdeps.py old mode 100644 new mode 100755 index 73e5994d..f261c924 --- a/checkdeps.py +++ b/checkdeps.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python2 """ Check dependendies and give recommendations about how to satisfy them @@ -9,112 +10,24 @@ Limitations: EXTRAS_REQUIRE. This is fine because most developers do, too. """ +import os from distutils.errors import CompileError try: from setuptools.dist import Distribution from setuptools.extension import Extension from setuptools.command.build_ext import build_ext HAVE_SETUPTOOLS = True + # another import from setuptools is in setup.py + from setup import EXTRAS_REQUIRE except ImportError: HAVE_SETUPTOOLS = False + EXTRAS_REQUIRE = [] + from importlib import import_module -import os -import sys -from setup import EXTRAS_REQUIRE +from src.depends import detectOS, PACKAGES, PACKAGE_MANAGER -PROJECT_ROOT = os.path.abspath('..') -sys.path.insert(0, PROJECT_ROOT) - -# OS-specific dependencies for optional components listed in EXTRAS_REQUIRE -EXTRAS_REQUIRE_DEPS = { - # The values from setup.EXTRAS_REQUIRE - 'python_prctl': { - # The packages needed for this requirement, by OS - "OpenBSD": [""], - "FreeBSD": [""], - "Debian": ["libcap-dev"], - "Ubuntu": [""], - "Ubuntu 12": [""], - "openSUSE": [""], - "Fedora": [""], - "Guix": [""], - "Gentoo": [""], - }, -} - -PACKAGE_MANAGER = { - "OpenBSD": "pkg_add", - "FreeBSD": "pkg install", - "Debian": "apt-get install", - "Ubuntu": "apt-get install", - "Ubuntu 12": "apt-get install", - "openSUSE": "zypper install", - "Fedora": "dnf install", - "Guix": "guix package -i", - "Gentoo": "emerge" -} - -PACKAGES = { - "PyQt4": { - "OpenBSD": "py-qt4", - "FreeBSD": "py27-qt4", - "Debian": "python-qt4", - "Ubuntu": "python-qt4", - "Ubuntu 12": "python-qt4", - "openSUSE": "python-qt", - "Fedora": "PyQt4", - "Guix": "python2-pyqt@4.11.4", - "Gentoo": "dev-python/PyQt4", - 'optional': True, - 'description': "You only need PyQt if you want to use the GUI. " \ - "When only running as a daemon, this can be skipped.\n" \ - "However, you would have to install it manually " \ - "because setuptools does not support PyQt." - }, - "msgpack": { - "OpenBSD": "py-msgpack", - "FreeBSD": "py27-msgpack-python", - "Debian": "python-msgpack", - "Ubuntu": "python-msgpack", - "Ubuntu 12": "msgpack-python", - "openSUSE": "python-msgpack-python", - "Fedora": "python2-msgpack", - "Guix": "python2-msgpack", - "Gentoo": "dev-python/msgpack", - "optional": True, - "description": "python-msgpack is recommended for improved performance of message encoding/decoding" - }, - "pyopencl": { - "FreeBSD": "py27-pyopencl", - "Debian": "python-pyopencl", - "Ubuntu": "python-pyopencl", - "Ubuntu 12": "python-pyopencl", - "Fedora": "python2-pyopencl", - "openSUSE": "", - "OpenBSD": "", - "Guix": "", - "Gentoo": "dev-python/pyopencl", - "optional": True, - 'description': "If you install pyopencl, you will be able to use " \ - "GPU acceleration for proof of work. \n" \ - "You also need a compatible GPU and drivers." - }, - "setuptools": { - "OpenBSD": "py-setuptools", - "FreeBSD": "py27-setuptools", - "Debian": "python-setuptools", - "Ubuntu": "python-setuptools", - "Ubuntu 12": "python-setuptools", - "Fedora": "python2-setuptools", - "openSUSE": "python-setuptools", - "Guix": "python2-setuptools", - "Gentoo": "", - "optional": False, - } -} - COMPILING = { "Debian": "build-essential libssl-dev", "Ubuntu": "build-essential libssl-dev", @@ -123,46 +36,23 @@ COMPILING = { "optional": False, } -def detectOSRelease(): - with open("/etc/os-release", 'r') as osRelease: - version = None - for line in osRelease: - if line.startswith("NAME="): - line = line.lower() - if "fedora" in line: - detectOS.result = "Fedora" - elif "opensuse" in line: - detectOS.result = "openSUSE" - elif "ubuntu" in line: - detectOS.result = "Ubuntu" - elif "debian" in line: - detectOS.result = "Debian" - elif "gentoo" in line or "calculate" in line: - detectOS.result = "Gentoo" - else: - detectOS.result = None - if line.startswith("VERSION_ID="): - try: - version = float(line.split("=")[1].replace("\"", "")) - except ValueError: - pass - if detectOS.result == "Ubuntu" and version < 14: - detectOS.result = "Ubuntu 12" +# OS-specific dependencies for optional components listed in EXTRAS_REQUIRE +EXTRAS_REQUIRE_DEPS = { + # The values from setup.EXTRAS_REQUIRE + 'python_prctl': { + # The packages needed for this requirement, by OS + "OpenBSD": [""], + "FreeBSD": [""], + "Debian": ["libcap-dev python-prctl"], + "Ubuntu": ["libcap-dev python-prctl"], + "Ubuntu 12": ["libcap-dev python-prctl"], + "openSUSE": [""], + "Fedora": ["prctl"], + "Guix": [""], + "Gentoo": ["dev-python/python-prctl"], + }, +} -def detectOS(): - if detectOS.result is not None: - return detectOS.result - if sys.platform.startswith('openbsd'): - detectOS.result = "OpenBSD" - elif sys.platform.startswith('freebsd'): - detectOS.result = "FreeBSD" - elif sys.platform.startswith('win'): - detectOS.result = "Windows" - elif os.path.isfile("/etc/os-release"): - detectOSRelease() - elif os.path.isfile("/etc/config.scm"): - detectOS.result = "Guix" - return detectOS.result def detectPrereqs(missing=True): available = [] @@ -176,18 +66,21 @@ def detectPrereqs(missing=True): available.append(module) return available + def prereqToPackages(): if not detectPrereqs(): return - print "%s %s" % ( + print("%s %s" % ( PACKAGE_MANAGER[detectOS()], " ".join( - PACKAGES[x][detectOS()] for x in detectPrereqs())) + PACKAGES[x][detectOS()] for x in detectPrereqs()))) + def compilerToPackages(): if not detectOS() in COMPILING: return - print "%s %s" % ( - PACKAGE_MANAGER[detectOS.result], COMPILING[detectOS.result]) + print("%s %s" % ( + PACKAGE_MANAGER[detectOS.result], COMPILING[detectOS.result])) + def testCompiler(): if not HAVE_SETUPTOOLS: @@ -214,30 +107,30 @@ def testCompiler(): fullPath = os.path.join(cmd.build_lib, cmd.get_ext_filename("bitmsghash")) return os.path.isfile(fullPath) -detectOS.result = None -prereqs = detectPrereqs() +prereqs = detectPrereqs() compiler = testCompiler() if (not compiler or prereqs) and detectOS() in PACKAGE_MANAGER: - print "It looks like you're using %s. " \ - "It is highly recommended to use the package manager\n" \ - "to install the missing dependencies." % (detectOS.result) + print( + "It looks like you're using %s. " + "It is highly recommended to use the package manager\n" + "to install the missing dependencies." % detectOS.result) if not compiler: - print "Building the bitmsghash module failed.\n" \ - "You may be missing a C++ compiler and/or the OpenSSL headers." + print( + "Building the bitmsghash module failed.\n" + "You may be missing a C++ compiler and/or the OpenSSL headers.") if prereqs: - mandatory = list(x for x in prereqs if "optional" not in PACKAGES[x] or not PACKAGES[x]["optional"]) - optional = list(x for x in prereqs if "optional" in PACKAGES[x] and PACKAGES[x]["optional"]) - + mandatory = [x for x in prereqs if not PACKAGES[x].get("optional")] + optional = [x for x in prereqs if PACKAGES[x].get("optional")] if mandatory: - print "Missing mandatory dependencies: %s" % (" ".join(mandatory)) + print("Missing mandatory dependencies: %s" % " ".join(mandatory)) if optional: - print "Missing optional dependencies: %s" % (" ".join(optional)) + print("Missing optional dependencies: %s" % " ".join(optional)) for package in optional: - print PACKAGES[package].get('description') + print(PACKAGES[package].get('description')) # Install the system dependencies of optional extras_require components OPSYS = detectOS() @@ -259,12 +152,14 @@ for lhs, rhs in EXTRAS_REQUIRE.items(): if x in EXTRAS_REQUIRE_DEPS ]), ]) - print "Optional dependency `pip install .[{}]` would require `{}` to be run as root".format(lhs, rhs_cmd) + print( + "Optional dependency `pip install .[{}]` would require `{}`" + " to be run as root".format(lhs, rhs_cmd)) -if (not compiler or prereqs) and detectOS() in PACKAGE_MANAGER: - print "You can install the missing dependencies by running, as root:" +if (not compiler or prereqs) and OPSYS in PACKAGE_MANAGER: + print("You can install the missing dependencies by running, as root:") if not compiler: compilerToPackages() prereqToPackages() else: - print "All the dependencies satisfied, you can install PyBitmessage" + print("All the dependencies satisfied, you can install PyBitmessage") diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..3e91a7ea --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = PyBitmessage +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..a4dae7c7 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- +""" +Configuration file for the Sphinx documentation builder. + +This file does only contain a selection of the most common options. For a +full list see the documentation: +http://www.sphinx-doc.org/en/master/config + +-- Path setup -------------------------------------------------------------- + +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. +""" + +import os +import sys + +from sphinx.apidoc import main +from mock import Mock as MagicMock + +sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath('../src')) +sys.path.insert(0, os.path.abspath('../src/pyelliptic')) + +import version + + +# -- Project information ----------------------------------------------------- + +project = u'PyBitmessage' +copyright = u'2018, The Bitmessage Team' # pylint: disable=redefined-builtin +author = u'The Bitmessage Team' + +# The short X.Y version +version = unicode(version.softwareVersion) + +# The full version, including alpha/beta/rc tags +release = version + +# -- 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.doctest', # Currently disabled due to bad doctests + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', + 'sphinx.ext.coverage', + 'sphinx.ext.imgmath', + 'sphinx.ext.viewcode', + 'm2r', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = ['.rst', '.md'] + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path . +exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + + +# -- 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 = {} + +# 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'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + +# Deal with long lines in source view +html_theme_options = { + 'page_width': '1366px', +} + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'PyBitmessagedoc' + + +# -- 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': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'PyBitmessage.tex', u'PyBitmessage Documentation', + u'The Bitmessage Team', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'pybitmessage', u'PyBitmessage Documentation', + [author], 1) +] + + +# -- 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 = [ + (master_doc, 'PyBitmessage', u'PyBitmessage Documentation', + author, 'PyBitmessage', 'One line description of project.', + 'Miscellaneous'), +] + + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project +epub_author = author +epub_publisher = author +epub_copyright = copyright + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + + +# -- Extension configuration ------------------------------------------------- + +# -- Options for intersphinx extension --------------------------------------- + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} + +# -- Options for todo extension ---------------------------------------------- + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True diff --git a/docs/contribute.dir/develop.dir/documentation.rst b/docs/contribute.dir/develop.dir/documentation.rst new file mode 100644 index 00000000..e32acbb4 --- /dev/null +++ b/docs/contribute.dir/develop.dir/documentation.rst @@ -0,0 +1,18 @@ +Documentation +============= + +Sphinx is used to pull richly formatted comments out of code, merge them with hand-written documentation and render it +in HTML and other formats. + +To build the docs, simply run `$ fab -H localhost build_docs` once you have set up Fabric. + +Restructured Text (RsT) vs MarkDown (md) +---------------------------------------- + +There's much on the internet about this. Suffice to say RsT_ is preferred for Python documentation while md is preferred for web markup or for certain other languages. + +.. _Rst: [http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html]` style is preferred, + +`md` files can also be incorporated by using mdinclude directives in the indices. They are translated to RsT before rendering to the various formats. Headers are translated as a hard-coded level `(H1: =, H2: -, H3: ^, H4: ~, H5: ", H6: #`. This represents a small consideration for both styles. If markup is not translated to rst well enough, switch to rst. + + diff --git a/docs/contribute.dir/develop.dir/fabric.rst b/docs/contribute.dir/develop.dir/fabric.rst new file mode 100644 index 00000000..434ccf7b --- /dev/null +++ b/docs/contribute.dir/develop.dir/fabric.rst @@ -0,0 +1,2 @@ +.. mdinclude:: fabfile/README.md + diff --git a/docs/contribute.dir/develop.dir/opsec.rst b/docs/contribute.dir/develop.dir/opsec.rst new file mode 100644 index 00000000..87bf4f49 --- /dev/null +++ b/docs/contribute.dir/develop.dir/opsec.rst @@ -0,0 +1,38 @@ +Operational Security +==================== + +Bitmessage has many features that are designed to protect your anonymity during normal use. There are other things that you must or should do if you value your anonymity. + +Castles in the sand +------------------- + +You cannot build a strong castle on unstable foundations. If your operating system is not wholly owned by you then it is impossible to make guarantees about an application. + + * Carefully choose your operating system + * Ensure your operating system is up to date + * Ensure any dependencies and requirements are up to date + +Extrordinary claims require extrordinary evidence +------------------------------------------------- + +If we are to make bold claims about protecting your privacy we should demonstrate this by strong actions. + +- PGP signed commits +- looking to audit +- warrant canary + +Digital foootprint +------------------ + +Your internet use can reveal metadata you wouldn't expect. This can be connected with other information about you if you're not careful. + + * Use separate addresses for different puprose + * Don't make the same mistakes all the time + * Your language use is unique. The more you type, the more you fingerprint yourself. The words you know and use often vs the words you don't know or use often. + +Cleaning history +---------------- + + * Tell your browser not to store BitMessage addresses + * Microsoft Office seems to offer the ability to define sensitive informations types. If browsers don't already they may in the future. Consider adding `BM-\w{x..y}`. + diff --git a/docs/contribute.dir/develop.dir/overview.rst b/docs/contribute.dir/develop.dir/overview.rst new file mode 100644 index 00000000..e83d884b --- /dev/null +++ b/docs/contribute.dir/develop.dir/overview.rst @@ -0,0 +1,88 @@ +Developing +========== + +Devops tasks +------------ + +Bitmessage makes use of fabric_ to define tasks such as building documentation or running checks and tests on the code. If you can install + +.. _fabric: https://fabfile.org + +Code style and linters +---------------------- + +We aim to be PEP8 compliant but we recognise that we have a long way still to go. Currently we have style and lint exceptions specified at the most specific place we can. We are ignoring certain issues project-wide in order to avoid alert-blindess, avoid style and lint regressions and to allow continuous integration to hook into the output from the tools. While it is hoped that all new changes pass the checks, fixing some existing violations are mini-projects in themselves. Current thinking on ignorable violations is reflected in the options and comments in setup.cfg. Module and line-level lint warnings represent refactoring opportunities. + +Pull requests +------------- + +There is a template at PULL_REQUEST_TEMPLATE.md that appears in the pull-request description. Please replace this text with something appropriate to your changes based off the ideas in the template. + +Bike-shedding +------------- + +Beyond having well-documented, Pythonic code with static analysis tool checks, extensive test coverage and powerful devops tools, what else can we have? Without violating any linters there is room for making arbirary decisions solely for the sake of project consistency. These are the stuff of the pedant's PR comments. Rather than have such conversations in PR comments, we can lay out the result of discussion here. + +I'm putting up a strawman for each topic here, mostly based on my memory of reading related Stack Overflow articles etc. If contributors feel strongly (and we don't have anything better to do) then maybe we can convince each other to update this section. + +Trailing vs hanging braces + Data + Hanging closing brace is preferred, trailing commas always to help reduce churn in diffs + Function, class, method args + Inline until line-length, then style as per data + Nesting + Functions + Short: group hanging close parentheses + Long: one closing parentheses per line + +Single vs double quotes + Single quotes are preferred; less strain on the hands, eyes + + Double quotes are only better so as to contain single quotes, but we want to contain doubles as often + +Line continuation + Implicit parentheses continuation is preferred + +British vs American spelling + We should be consistent, it looks like we have American to British at approx 140 to 60 in the code. There's not enough occurrences that we couldn't be consistent one way or the other. It breaks my heart that British spelling could lose this one but I'm happy to 'z' things up for the sake of consistency. So I put forward British to be preferred. Either that strawman wins out, or I incite interest in ~bike-shedding~ guiding the direction of this crucial topic from others. + +Dependency graph +---------------- + +These images are not very useful right now but the aim is to tweak the settings of one or more of them to be informative, and/or divide them up into smaller grapghs. + +To re-build them, run `fab build_docs:dep_graphs=true`. Note that the dot graph takes a lot of time. + +.. figure:: ../../../../_static/deps-neato.png + :alt: neato graph of dependencies + :width: 100 pc + + :index:`Neato` graph of dependencies + +.. figure:: ../../../../_static/deps-sfdp.png + :alt: SFDP graph of dependencies + :width: 100 pc + + :index:`SFDP` graph of dependencies + +.. figure:: ../../../../_static/deps-dot.png + :alt: Dot graph of dependencies + :width: 100 pc + + :index:`Dot` graph of dependencies + +Key management +-------------- + +Nitro key +^^^^^^^^^ + +Regular contributors are enouraged to take further steps to protect their key and the Nitro Key (Start) is recommended by the BitMessage project for this purpose. + +Debian-quirks +~~~~~~~~~~~~~ + +Stretch makes use of the directory ~/.gnupg/private-keys-v1.d/ to store the private keys. This simplifies some steps of the Nitro Key instructions. See step 5 of Debian's subkeys_ wiki page + +.. _subkeys: https://wiki.debian.org/Subkeys + diff --git a/docs/contribute.dir/develop.dir/testing.rst b/docs/contribute.dir/develop.dir/testing.rst new file mode 100644 index 00000000..2947c7d6 --- /dev/null +++ b/docs/contribute.dir/develop.dir/testing.rst @@ -0,0 +1,4 @@ +Testing +======= + +Currently there is a Travis job somewhere which runs python setup.py test. This doesn't find any tests when run locally for some reason. diff --git a/docs/contribute.dir/develop.dir/todo.rst b/docs/contribute.dir/develop.dir/todo.rst new file mode 100644 index 00000000..34f71f42 --- /dev/null +++ b/docs/contribute.dir/develop.dir/todo.rst @@ -0,0 +1,4 @@ +TODO list +========= + +.. todolist:: diff --git a/docs/contribute.dir/develop.rst b/docs/contribute.dir/develop.rst new file mode 100644 index 00000000..e5563eb2 --- /dev/null +++ b/docs/contribute.dir/develop.rst @@ -0,0 +1,8 @@ +Developing +========== + +.. toctree:: + :maxdepth: 2 + :glob: + + develop.dir/* diff --git a/docs/contribute.dir/processes.rst b/docs/contribute.dir/processes.rst new file mode 100644 index 00000000..8f0385d4 --- /dev/null +++ b/docs/contribute.dir/processes.rst @@ -0,0 +1,28 @@ +Processes +========= + +In other to keep the Bitmessage project running the team run a number of systems and accounts that form the +development pipeline and continuous delivery process. We are always striving to improve the process. Towards +that end it is documented here. + + +Project website +--------------- + +The bitmessage website_ + +Github +------ + +Our official Github_ account is Bitmessage. Our issue tracker is here as well. + + +BitMessage +---------- + +We eat our own dog food! You can send us bug reports via the Bitmessage chan at xxx + + +.. _website: https://bitmessage.org +.. _Github: https://github.com/Bitmessage/PyBitmessage + diff --git a/docs/contribute.rst b/docs/contribute.rst new file mode 100644 index 00000000..7c79e22c --- /dev/null +++ b/docs/contribute.rst @@ -0,0 +1,25 @@ +Contributing +============ + +.. toctree:: + :maxdepth: 2 + :glob: + + contribute.dir/* + + +- Report_ +- Develop_(develop) +- Translate_ +- Donate_ +- Fork the code and open a PR_ on github +- Search the `issue tracker` on github or open a new issue +- Send bug report to the chan + +.. _Report: https://github.com/Bitmessage/PyBitmessage/issues +.. _Develop: https://github.com/Bitmessage/PyBitmessage +.. _Translate: https://www.transifex.com/bitmessage-project/pybitmessage/ +.. _Donate: https://tip4commit.com/github/Bitmessage/PyBitmessage +.. _PR: https://github.com/Bitmessage/PyBitmessage/pulls +.. _`issue tracker`: https://github.com/Bitmessage/PyBitmessage/issues + contributing/* diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..9dddfa28 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,15 @@ +.. mdinclude:: ../README.md + +.. toctree:: + :maxdepth: 2 + + overview + usage + contribute + +Indices and tables +------------------ + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 00000000..2548d34e --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=PyBitmessage + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 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 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 00000000..cf745121 --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,21 @@ +Usage +===== + +GUI +--- + +Bitmessage has a PyQT GUI_ + +CLI +--- + +Bitmessage has a CLI_ + +API +--- + +Bitmessage has an XML-RPC API_ + +.. _GUI: https://bitmessage.org/wiki/PyBitmessage_Help +.. _CLI: https://bitmessage.org/wiki/PyBitmessage_Help +.. _API: https://bitmessage.org/wiki/API_Reference diff --git a/fabfile/README.md b/fabfile/README.md index 3d4d41be..643aed8e 100644 --- a/fabfile/README.md +++ b/fabfile/README.md @@ -85,3 +85,17 @@ Host github HostName github.com IdentityFile ~/.ssh/id_rsa_github ``` + +# Ideas for further development + +## Smaller + + * Decorators and context managers are useful for accepting common params like verbosity, force or doing command-level help + * if `git status` or `git status --staged` produce results, prefer that to generate the file list + + +## Larger + + * Support documentation translations, aim for current transifex'ed languages + * Fabric 2 is finally out, go @bitprophet! Invoke/Fabric2 is a rewrite of Fabric supporting Python3. Probably makes + sense for us to stick to the battle-hardened 1.x branch, at least until we support Python3. diff --git a/fabfile/__init__.py b/fabfile/__init__.py index 67a68967..9aec62bb 100644 --- a/fabfile/__init__.py +++ b/fabfile/__init__.py @@ -17,7 +17,7 @@ For more help on a particular command from fabric.api import env -from fabfile.tasks import code_quality +from fabfile.tasks import code_quality, build_docs, push_docs, clean, test # Without this, `fab -l` would display the whole docstring as preamble @@ -26,6 +26,10 @@ __doc__ = "" # This list defines which tasks are made available to the user __all__ = [ "code_quality", + "test", + "build_docs", + "push_docs", + "clean", ] # Honour the user's ssh client configuration diff --git a/fabfile/lib.py b/fabfile/lib.py index e22af53a..7af40231 100644 --- a/fabfile/lib.py +++ b/fabfile/lib.py @@ -6,8 +6,10 @@ A library of functions and constants for tasks to make use of. import os import sys +import re +from functools import wraps -from fabric.api import run, hide +from fabric.api import run, hide, cd, env from fabric.context_managers import settings, shell_env from fabvenv import virtualenv @@ -18,6 +20,14 @@ VENV_ROOT = os.path.expanduser(os.path.join('~', '.virtualenvs', 'pybitmessage-d PYTHONPATH = os.path.join(PROJECT_ROOT, 'src',) +def coerce_list(value): + """Coerce a value into a list""" + if isinstance(value, str): + return value.split(',') + else: + sys.exit("Bad string value {}".format(value)) + + def coerce_bool(value): """Coerce a value into a boolean""" if isinstance(value, bool): @@ -51,6 +61,29 @@ def flatten(data): return result +def filelist_from_git(rev=None): + """Return a list of files based on git output""" + cmd = 'git diff --name-only' + if rev: + if rev in ['cached', 'staged']: + cmd += ' --{}'.format(rev) + elif rev == 'working': + pass + else: + cmd += ' -r {}'.format(rev) + + with cd(PROJECT_ROOT): + with hide('running', 'stdout'): + results = [] + ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') + clean = ansi_escape.sub('', run(cmd)) + clean = re.sub('\n', '', clean) + for line in clean.split('\r'): + if line.endswith(".py"): + results.append(os.path.abspath(line)) + return results + + def pycodestyle(path_to_file): """Run pycodestyle on a file""" with virtualenv(VENV_ROOT): @@ -148,3 +181,20 @@ def get_filtered_pylint_output(path_to_file): not i.startswith('Using config file'), ]) ] + + +def default_hosts(hosts): + """Decorator to apply default hosts to a task""" + + def real_decorator(func): + """Manipulate env""" + env.hosts = env.hosts or hosts + + @wraps(func) + def wrapper(*args, **kwargs): + """Original function called from here""" + return func(*args, **kwargs) + + return wrapper + + return real_decorator diff --git a/fabfile/tasks.py b/fabfile/tasks.py index 98ab2f0e..fb05937d 100644 --- a/fabfile/tasks.py +++ b/fabfile/tasks.py @@ -2,20 +2,26 @@ """ Fabric tasks for PyBitmessage devops operations. -# pylint: disable=not-context-manager +Note that where tasks declare params to be bools, they use coerce_bool() and so will accept any commandline (string) +representation of true or false that coerce_bool() understands. + """ import os import sys -from fabric.api import run, task, hide, cd +from fabric.api import run, task, hide, cd, settings, sudo +from fabric.contrib.project import rsync_project from fabvenv import virtualenv from fabfile.lib import ( - autopep8, PROJECT_ROOT, VENV_ROOT, coerce_bool, flatten, + autopep8, PROJECT_ROOT, VENV_ROOT, coerce_bool, flatten, filelist_from_git, default_hosts, get_filtered_pycodestyle_output, get_filtered_flake8_output, get_filtered_pylint_output, ) +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src'))) # noqa:E402 +from version import softwareVersion # pylint: disable=wrong-import-position + def get_tool_results(file_list): """Take a list of files and resuln the results of applying the tools""" @@ -28,9 +34,9 @@ def get_tool_results(file_list): result['pylint_violations'] = get_filtered_pylint_output(path_to_file) result['path_to_file'] = path_to_file result['total_violations'] = sum([ - len(result['pycodestyle_violations']), - len(result['flake8_violations']), - len(result['pylint_violations']), + len(result['pycodestyle_violations']), + len(result['flake8_violations']), + len(result['pylint_violations']), ]) results.append(result) return results @@ -39,7 +45,7 @@ def get_tool_results(file_list): def print_results(results, top, verbose, details): """Print an item with the appropriate verbosity / detail""" - if verbose: + if verbose and results: print ''.join( [ os.linesep, @@ -116,8 +122,46 @@ def generate_file_list(filename): return file_list +def create_dependency_graphs(): + """ + To better understand the relationship between methods, dependency graphs can be drawn between functions and + methods. + + Since the resulting images are large and could be out of date on the next commit, storing them in the repo is + pointless. Instead, it makes sense to build a dependency graph for a particular, documented version of the code. + + .. todo:: Consider saving a hash of the intermediate dotty file so unnecessary image generation can be avoided. + + """ + with virtualenv(VENV_ROOT): + with hide('running', 'stdout'): + + # .. todo:: consider a better place to put this, use a particular commit + with cd(PROJECT_ROOT): + with settings(warn_only=True): + if run('stat pyan').return_code: + run('git clone https://github.com/davidfraser/pyan.git') + with cd(os.path.join(PROJECT_ROOT, 'pyan')): + run('git checkout pre-python3') + + # .. todo:: Use better settings. This is MVP to make a diagram + with cd(PROJECT_ROOT): + file_list = run("find . -type f -name '*.py' ! -path './src/.eggs/*'").split('\r\n') + for cmd in [ + 'neato -Goverlap=false -Tpng > deps-neato.png', + 'sfdp -Goverlap=false -Tpng > deps-sfdp.png', + 'dot -Goverlap=false -Tpng > deps-dot.png', + ]: + pyan_cmd = './pyan/pyan.py {} --dot'.format(' '.join(file_list)) + sed_cmd = r"sed s'/http\-old/http_old/'g" # dot doesn't like dashes + run('|'.join([pyan_cmd, sed_cmd, cmd])) + + run('mv *.png docs/_build/html/_static/') + + @task -def code_quality(verbose=True, details=False, fix=False, filename=None, top=10): +@default_hosts(['localhost']) +def code_quality(verbose=True, details=False, fix=False, filename=None, top=10, rev=None): """ Check code quality. @@ -128,6 +172,8 @@ def code_quality(verbose=True, details=False, fix=False, filename=None, top=10): $ fab -H localhost code_quality + :param rev: If not None, act on files changed since this commit. 'cached/staged' and 'working' have special meaning + :type rev: str or None, default None :param top: Display / fix only the top N violating files, a value of 0 will display / fix all files :type top: int, default 10 :param verbose: Display a header and the counts, without this you just get the filenames in order @@ -136,23 +182,22 @@ def code_quality(verbose=True, details=False, fix=False, filename=None, top=10): :type details: bool, default False :param fix: Run autopep8 aggressively on the displayed file(s) :type fix: bool, default False - :param filename: Rather than analysing all files and displaying / fixing the top N, just analyse / display / fix - the specified file + :param filename: Don't test/fix the top N, just the specified file :type filename: string, valid path to a file, default all files in the project - :return: This fabric task has an exit status equal to the total number of violations and uses stdio but it does - not return anything if you manage to call it successfully from Python + :return: None, exit status equals total number of violations :rtype: None Intended to be temporary until we have improved code quality and have safeguards to maintain it in place. """ + # pylint: disable=too-many-arguments verbose = coerce_bool(verbose) details = coerce_bool(details) fix = coerce_bool(fix) top = int(top) or -1 - file_list = generate_file_list(filename) + file_list = generate_file_list(filename) if not rev else filelist_from_git(rev) results = get_tool_results(file_list) if fix: @@ -163,3 +208,111 @@ def code_quality(verbose=True, details=False, fix=False, filename=None, top=10): print_results(results, top, verbose, details) sys.exit(sum([item['total_violations'] for item in results])) + + +@task +@default_hosts(['localhost']) +def test(): + """Run tests on the code""" + + with cd(PROJECT_ROOT): + with virtualenv(VENV_ROOT): + + run('pip uninstall -y pybitmessage') + run('python setup.py install') + + run('pybitmessage -t') + run('python setup.py test') + + +@task +@default_hosts(['localhost']) +def build_docs(dep_graph=False, apidoc=True): + """ + Build the documentation locally. + + :param dep_graph: Build the dependency graphs + :type dep_graph: Bool, default False + :param apidoc: Build the automatically generated rst files from the source code + :type apidoc: Bool, default True + + Default usage: + + $ fab -H localhost build_docs + + Implementation: + + First, a dependency graph is generated and converted into an image that is referenced in the development page. + + Next, the sphinx-apidoc command is (usually) run which searches the code. As part of this it loads the modules and + if this has side-effects then they will be evident. Any documentation strings that make use of Python documentation + conventions (like parameter specification) or the Restructured Text (RsT) syntax will be extracted. + + Next, the `make html` command is run to generate HTML output. Other formats (epub, pdf) are available. + + .. todo:: support other languages + + """ + + apidoc = coerce_bool(apidoc) + + if coerce_bool(dep_graph): + create_dependency_graphs() + + with virtualenv(VENV_ROOT): + with hide('running'): + + apidoc_result = 0 + if apidoc: + run('mkdir -p {}'.format(os.path.join(PROJECT_ROOT, 'docs', 'autodoc'))) + with cd(os.path.join(PROJECT_ROOT, 'docs', 'autodoc')): + with settings(warn_only=True): + run('rm *.rst') + with cd(os.path.join(PROJECT_ROOT, 'docs')): + apidoc_result = run('sphinx-apidoc -o autodoc ..').return_code + + with cd(os.path.join(PROJECT_ROOT, 'docs')): + make_result = run('make html').return_code + return_code = apidoc_result + make_result + + sys.exit(return_code) + + +@task +@default_hosts(['localhost']) +def push_docs(path=None): + """ + Upload the generated docs to a public server. + + Default usage: + + $ fab -H localhost push_docs + + .. todo:: support other languages + .. todo:: integrate with configuration management data to get web root and webserver restart command + + """ + + # Making assumptions + WEB_ROOT = path if path is not None else os.path.join('var', 'www', 'html', 'pybitmessage', 'en', 'latest') + VERSION_ROOT = os.path.join(os.path.dirname(WEB_ROOT), softwareVersion) + + rsync_project( + remote_dir=VERSION_ROOT, + local_dir=os.path.join(PROJECT_ROOT, 'docs', '_build', 'html') + ) + result = run('ln -sf {0} {1}'.format(WEB_ROOT, VERSION_ROOT)) + if result.return_code: + print 'Linking the new release failed' + + # More assumptions + sudo('systemctl restart apache2') + + +@task +@default_hosts(['localhost']) +def clean(): + """Clean up files generated by fabric commands.""" + with hide('running', 'stdout'): + with cd(PROJECT_ROOT): + run(r"find . -name '*.pyc' -exec rm '{}' \;") diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/setup.py b/setup.py index 4a750680..1081b5aa 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,14 @@ EXTRAS_REQUIRE = { 'pyopencl': ['pyopencl'], 'prctl': ['python_prctl'], # Named threads 'qrcode': ['qrcode'], - 'sound;platform_system=="Windows"': ['winsound'] + 'sound;platform_system=="Windows"': ['winsound'], + 'docs': [ + 'sphinx', # fab build_docs + 'graphviz', # fab build_docs + 'curses', # src/depends.py + 'python2-pythondialog', # src/depends.py + 'm2r', # fab build_docs + ], } diff --git a/src/api_client.py b/src/api_client.py index 6dc0c7b0..dbad0f0b 100644 --- a/src/api_client.py +++ b/src/api_client.py @@ -5,66 +5,68 @@ import xmlrpclib import json import time -api = xmlrpclib.ServerProxy("http://bradley:password@localhost:8442/") +if __name__ == '__main__': -print 'Let\'s test the API first.' -inputstr1 = "hello" -inputstr2 = "world" -print api.helloWorld(inputstr1, inputstr2) -print api.add(2,3) + api = xmlrpclib.ServerProxy("http://bradley:password@localhost:8442/") -print 'Let\'s set the status bar message.' -print api.statusBar("new status bar message") + print 'Let\'s test the API first.' + inputstr1 = "hello" + inputstr2 = "world" + print api.helloWorld(inputstr1, inputstr2) + print api.add(2,3) -print 'Let\'s list our addresses:' -print api.listAddresses() + print 'Let\'s set the status bar message.' + print api.statusBar("new status bar message") -print 'Let\'s list our address again, but this time let\'s parse the json data into a Python data structure:' -jsonAddresses = json.loads(api.listAddresses()) -print jsonAddresses -print 'Now that we have our address data in a nice Python data structure, let\'s look at the first address (index 0) and print its label:' -print jsonAddresses['addresses'][0]['label'] + print 'Let\'s list our addresses:' + print api.listAddresses() -print 'Uncomment the next two lines to create a new random address with a slightly higher difficulty setting than normal.' -#addressLabel = 'new address label'.encode('base64') -#print api.createRandomAddress(addressLabel,False,1.05,1.1111) + print 'Let\'s list our address again, but this time let\'s parse the json data into a Python data structure:' + jsonAddresses = json.loads(api.listAddresses()) + print jsonAddresses + print 'Now that we have our address data in a nice Python data structure, let\'s look at the first address (index 0) and print its label:' + print jsonAddresses['addresses'][0]['label'] -print 'Uncomment these next four lines to create new deterministic addresses.' -#passphrase = 'asdfasdfqwser'.encode('base64') -#jsonDeterministicAddresses = api.createDeterministicAddresses(passphrase, 2, 4, 1, False) -#print jsonDeterministicAddresses -#print json.loads(jsonDeterministicAddresses) + print 'Uncomment the next two lines to create a new random address with a slightly higher difficulty setting than normal.' + #addressLabel = 'new address label'.encode('base64') + #print api.createRandomAddress(addressLabel,False,1.05,1.1111) -#print 'Uncomment this next line to print the first deterministic address that would be generated with the given passphrase. This will Not add it to the Bitmessage interface or the keys.dat file.' -#print api.getDeterministicAddress('asdfasdfqwser'.encode('base64'),4,1) + print 'Uncomment these next four lines to create new deterministic addresses.' + #passphrase = 'asdfasdfqwser'.encode('base64') + #jsonDeterministicAddresses = api.createDeterministicAddresses(passphrase, 2, 4, 1, False) + #print jsonDeterministicAddresses + #print json.loads(jsonDeterministicAddresses) -#print 'Uncomment this line to subscribe to an address. (You must use your own address, this one is invalid).' -#print api.addSubscription('2D94G5d8yp237GGqAheoecBYpdehdT3dha','test sub'.encode('base64')) + #print 'Uncomment this next line to print the first deterministic address that would be generated with the given passphrase. This will Not add it to the Bitmessage interface or the keys.dat file.' + #print api.getDeterministicAddress('asdfasdfqwser'.encode('base64'),4,1) -#print 'Uncomment this line to unsubscribe from an address.' -#print api.deleteSubscription('2D94G5d8yp237GGqAheoecBYpdehdT3dha') + #print 'Uncomment this line to subscribe to an address. (You must use your own address, this one is invalid).' + #print api.addSubscription('2D94G5d8yp237GGqAheoecBYpdehdT3dha','test sub'.encode('base64')) -print 'Let\'s now print all of our inbox messages:' -print api.getAllInboxMessages() -inboxMessages = json.loads(api.getAllInboxMessages()) -print inboxMessages + #print 'Uncomment this line to unsubscribe from an address.' + #print api.deleteSubscription('2D94G5d8yp237GGqAheoecBYpdehdT3dha') -print 'Uncomment this next line to decode the actual message data in the first message:' -#print inboxMessages['inboxMessages'][0]['message'].decode('base64') + print 'Let\'s now print all of our inbox messages:' + print api.getAllInboxMessages() + inboxMessages = json.loads(api.getAllInboxMessages()) + print inboxMessages -print 'Uncomment this next line in the code to delete a message' -#print api.trashMessage('584e5826947242a82cb883c8b39ac4a14959f14c228c0fbe6399f73e2cba5b59') + print 'Uncomment this next line to decode the actual message data in the first message:' + #print inboxMessages['inboxMessages'][0]['message'].decode('base64') -print 'Uncomment these lines to send a message. The example addresses are invalid; you will have to put your own in.' -#subject = 'subject!'.encode('base64') -#message = 'Hello, this is the message'.encode('base64') -#ackData = api.sendMessage('BM-Gtsm7PUabZecs3qTeXbNPmqx3xtHCSXF', 'BM-2DCutnUZG16WiW3mdAm66jJUSCUv88xLgS', subject,message) -#print 'The ackData is:', ackData -#while True: -# time.sleep(2) -# print 'Current status:', api.getStatus(ackData) + print 'Uncomment this next line in the code to delete a message' + #print api.trashMessage('584e5826947242a82cb883c8b39ac4a14959f14c228c0fbe6399f73e2cba5b59') -print 'Uncomment these lines to send a broadcast. The example address is invalid; you will have to put your own in.' -#subject = 'subject within broadcast'.encode('base64') -#message = 'Hello, this is the message within a broadcast.'.encode('base64') -#print api.sendBroadcast('BM-onf6V1RELPgeNN6xw9yhpAiNiRexSRD4e', subject,message) + print 'Uncomment these lines to send a message. The example addresses are invalid; you will have to put your own in.' + #subject = 'subject!'.encode('base64') + #message = 'Hello, this is the message'.encode('base64') + #ackData = api.sendMessage('BM-Gtsm7PUabZecs3qTeXbNPmqx3xtHCSXF', 'BM-2DCutnUZG16WiW3mdAm66jJUSCUv88xLgS', subject,message) + #print 'The ackData is:', ackData + #while True: + # time.sleep(2) + # print 'Current status:', api.getStatus(ackData) + + print 'Uncomment these lines to send a broadcast. The example address is invalid; you will have to put your own in.' + #subject = 'subject within broadcast'.encode('base64') + #message = 'Hello, this is the message within a broadcast.'.encode('base64') + #print api.sendBroadcast('BM-onf6V1RELPgeNN6xw9yhpAiNiRexSRD4e', subject,message) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 11726913..31a475dd 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -51,8 +51,6 @@ from class_singleCleaner import singleCleaner from class_objectProcessor import objectProcessor from class_singleWorker import singleWorker from class_addressGenerator import addressGenerator -from class_smtpDeliver import smtpDeliver -from class_smtpServer import smtpServer from bmconfigparser import BMConfigParser from inventory import Inventory @@ -245,6 +243,19 @@ class Main: state.enableGUI = False # run without a UI # is the application already running? If yes then exit. + if state.enableGUI and not state.curses and not depends.check_pyqt(): + sys.exit( + 'PyBitmessage requires PyQt unless you want' + ' to run it as a daemon and interact with it' + ' using the API. You can download PyQt from ' + 'http://www.riverbankcomputing.com/software/pyqt/download' + ' or by searching Google for \'PyQt Download\'.' + ' If you want to run in daemon mode, see ' + 'https://bitmessage.org/wiki/Daemon\n' + 'You can also run PyBitmessage with' + ' the new curses interface by providing' + ' \'-c\' as a commandline argument.' + ) shared.thisapp = singleinstance("", daemon) if daemon and not state.testmode: @@ -297,12 +308,14 @@ class Main: # SMTP delivery thread if daemon and BMConfigParser().safeGet( "bitmessagesettings", "smtpdeliver", '') != '': + from class_smtpDeliver import smtpDeliver smtpDeliveryThread = smtpDeliver() smtpDeliveryThread.start() # SMTP daemon thread if daemon and BMConfigParser().safeGetBoolean( "bitmessagesettings", "smtpd"): + from class_smtpServer import smtpServer smtpServerThread = smtpServer() smtpServerThread.start() @@ -381,26 +394,14 @@ class Main: BMConfigParser().remove_option('bitmessagesettings', 'dontconnect') elif daemon is False: if state.curses: - # if depends.check_curses(): + if not depends.check_curses(): + sys.exit() print('Running with curses') import bitmessagecurses bitmessagecurses.runwrapper() - elif depends.check_pyqt(): + else: import bitmessageqt bitmessageqt.run() - else: - sys.exit( - 'PyBitmessage requires PyQt unless you want' - ' to run it as a daemon and interact with it' - ' using the API. You can download PyQt from ' - 'http://www.riverbankcomputing.com/software/pyqt/download' - ' or by searching Google for \'PyQt Download\'.' - ' If you want to run in daemon mode, see ' - 'https://bitmessage.org/wiki/Daemon\n' - 'You can also run PyBitmessage with' - ' the new curses interface by providing' - ' \'-c\' as a commandline argument.' - ) if daemon: if state.testmode: diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 3f504972..208923fc 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -1,9 +1,5 @@ -# pylint: disable=too-many-lines,broad-except,too-many-instance-attributes,global-statement,too-few-public-methods -# pylint: disable=too-many-statements,too-many-branches,attribute-defined-outside-init,too-many-arguments,no-member -# pylint: disable=unused-argument,no-self-use,too-many-locals,unused-variable,too-many-nested-blocks -# pylint: disable=too-many-return-statements,protected-access,super-init-not-called,non-parent-init-called """ -Initialise the QT interface +PyQt based UI for bitmessage, the main module """ import hashlib @@ -15,64 +11,51 @@ import sys import textwrap import time from datetime import datetime, timedelta +from sqlite3 import register_adapter + +from PyQt4 import QtCore, QtGui +from PyQt4.QtNetwork import QLocalSocket, QLocalServer -import debug from debug import logger - - -try: - from PyQt4 import QtCore, QtGui - from PyQt4.QtNetwork import QLocalSocket, QLocalServer -except ImportError: - logmsg = ( - 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can' - ' download it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for ' - '\'PyQt Download\' (without quotes).' - ) - logger.critical(logmsg, exc_info=True) - sys.exit() - - -from sqlite3 import register_adapter # pylint: disable=wrong-import-order - +from tr import _translate +from addresses import decodeAddress, addBMIfNotPresent +import shared +from bitmessageui import Ui_MainWindow +from bmconfigparser import BMConfigParser import defaults +from namecoin import namecoinConnection +from messageview import MessageView +from migrationwizard import Ui_MigrationWizard +from foldertree import ( + AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget, + MessageList_AddressWidget, MessageList_SubjectWidget, + Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress) +from settings import Ui_settingsDialog +import settingsmixin +import support +import debug +from helper_ackPayload import genAckPayload +from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure import helper_search -import knownnodes import l10n import openclpow +from utils import str_broadcast_subscribers, avatarize +from account import ( + getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount, + GatewayAccount, MailchuckAccount, AccountColor) +import dialogs +from helper_generic import powQueueSize +from network.stats import pendingDownload, pendingUpload +from uisignaler import UISignaler +import knownnodes import paths +from proofofwork import getPowType import queues -import shared import shutdown import state -import upnp - -from bitmessageqt import sound, support, dialogs -from bitmessageqt.foldertree import ( - AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget, MessageList_AddressWidget, - MessageList_SubjectWidget, Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress, -) -from bitmessageqt.account import ( - getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount, GatewayAccount, MailchuckAccount, AccountColor, -) -from bitmessageqt.bitmessageui import Ui_MainWindow, settingsmixin -from bitmessageqt.messageview import MessageView -from bitmessageqt.migrationwizard import Ui_MigrationWizard -from bitmessageqt.settings import Ui_settingsDialog -from bitmessageqt.utils import str_broadcast_subscribers, avatarize -from bitmessageqt.uisignaler import UISignaler -from bitmessageqt.statusbar import BMStatusBar - -from addresses import decodeAddress, addBMIfNotPresent -from bmconfigparser import BMConfigParser -from namecoin import namecoinConnection -from helper_ackPayload import genAckPayload -from helper_generic import powQueueSize -from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure -from network.stats import pendingDownload, pendingUpload +from statusbar import BMStatusBar from network.asyncore_pollchoose import set_rates -from proofofwork import getPowType -from tr import _translate +import sound try: @@ -81,15 +64,8 @@ except ImportError: get_plugins = False -qmytranslator = None -qsystranslator = None - - def change_translation(newlocale): - """Change a translation to a new locale""" - global qmytranslator, qsystranslator - try: if not qmytranslator.isEmpty(): QtGui.QApplication.removeTranslator(qmytranslator) @@ -102,16 +78,15 @@ def change_translation(newlocale): pass qmytranslator = QtCore.QTranslator() - translationpath = os.path.join(paths.codePath(), 'translations', 'bitmessage_' + newlocale) + translationpath = os.path.join (paths.codePath(), 'translations', 'bitmessage_' + newlocale) qmytranslator.load(translationpath) QtGui.QApplication.installTranslator(qmytranslator) qsystranslator = QtCore.QTranslator() if paths.frozen: - translationpath = os.path.join(paths.codePath(), 'translations', 'qt_' + newlocale) + translationpath = os.path.join (paths.codePath(), 'translations', 'qt_' + newlocale) else: - translationpath = os.path.join(str(QtCore.QLibraryInfo.location( - QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale) + translationpath = os.path.join (str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale) qsystranslator.load(translationpath) QtGui.QApplication.installTranslator(qsystranslator) @@ -132,8 +107,7 @@ def change_translation(newlocale): logger.error("Failed to set locale to %s", lang, exc_info=True) -class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-methods - """TBC""" +class MyForm(settingsmixin.SMainWindow): # the last time that a message arrival sound was played lastSoundTime = datetime.now() - timedelta(days=1) @@ -145,8 +119,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth REPLY_TYPE_CHAN = 1 def init_file_menu(self): - """Initialise the file menu""" - QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL( "triggered()"), self.quit) QtCore.QObject.connect(self.ui.actionNetworkSwitch, QtCore.SIGNAL( @@ -161,10 +133,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth QtCore.SIGNAL( "triggered()"), self.click_actionRegenerateDeterministicAddresses) - QtCore.QObject.connect( - self.ui.pushButtonAddChan, - QtCore.SIGNAL("clicked()"), - self.click_actionJoinChan) # also used for creating chans. + QtCore.QObject.connect(self.ui.pushButtonAddChan, QtCore.SIGNAL( + "clicked()"), + self.click_actionJoinChan) # also used for creating chans. QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL( "clicked()"), self.click_NewAddressDialog) QtCore.QObject.connect(self.ui.pushButtonAddAddressBook, QtCore.SIGNAL( @@ -189,8 +160,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "triggered()"), self.click_actionHelp) def init_inbox_popup_menu(self, connectSignal=True): - """Popup menu for the Inbox tab""" - + # Popup menu for the Inbox tab self.ui.inboxContextMenuToolbar = QtGui.QToolBar() # Actions self.actionReply = self.ui.inboxContextMenuToolbar.addAction(_translate( @@ -227,28 +197,24 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.tableWidgetInbox.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.tableWidgetInbox, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuInbox) + self.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuInbox) self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.tableWidgetInboxSubscriptions, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuInbox) + self.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuInbox) self.ui.tableWidgetInboxChans.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.tableWidgetInboxChans, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuInbox) + self.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuInbox) def init_identities_popup_menu(self, connectSignal=True): - """Popup menu for the Your Identities tab""" - + # Popup menu for the Your Identities tab self.ui.addressContextMenuToolbarYourIdentities = QtGui.QToolBar() # Actions self.actionNewYourIdentities = self.ui.addressContextMenuToolbarYourIdentities.addAction(_translate( @@ -283,10 +249,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.treeWidgetYourIdentities.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.treeWidgetYourIdentities, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuYourIdentities) + self.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuYourIdentities) # load all gui.menu plugins with prefix 'address' self.menu_plugins = {'address': []} @@ -301,8 +266,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth )) def init_chan_popup_menu(self, connectSignal=True): - """Popup menu for the Channels tab""" - + # Popup menu for the Channels tab self.ui.addressContextMenuToolbar = QtGui.QToolBar() # Actions self.actionNew = self.ui.addressContextMenuToolbar.addAction(_translate( @@ -332,14 +296,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.treeWidgetChans.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.treeWidgetChans, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuChan) + self.connect(self.ui.treeWidgetChans, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuChan) def init_addressbook_popup_menu(self, connectSignal=True): - """Popup menu for the Address Book page""" - + # Popup menu for the Address Book page self.ui.addressBookContextMenuToolbar = QtGui.QToolBar() # Actions self.actionAddressBookSend = self.ui.addressBookContextMenuToolbar.addAction( @@ -371,14 +333,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.tableWidgetAddressBook.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.tableWidgetAddressBook, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuAddressBook) + self.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuAddressBook) def init_subscriptions_popup_menu(self, connectSignal=True): - """Popup menu for the Subscriptions page""" - + # Popup menu for the Subscriptions page self.ui.subscriptionsContextMenuToolbar = QtGui.QToolBar() # Actions self.actionsubscriptionsNew = self.ui.subscriptionsContextMenuToolbar.addAction( @@ -401,14 +361,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.treeWidgetSubscriptions.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: - self.connect( - self.ui.treeWidgetSubscriptions, - QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), - self.on_context_menuSubscriptions) + self.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL( + 'customContextMenuRequested(const QPoint&)'), + self.on_context_menuSubscriptions) def init_sent_popup_menu(self, connectSignal=True): - """Popup menu for the Sent page""" - + # Popup menu for the Sent page self.ui.sentContextMenuToolbar = QtGui.QToolBar() # Actions self.actionTrashSentMessage = self.ui.sentContextMenuToolbar.addAction( @@ -421,10 +379,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.actionForceSend = self.ui.sentContextMenuToolbar.addAction( _translate( "MainWindow", "Force send"), self.on_action_ForceSend) + # self.popMenuSent = QtGui.QMenu( self ) + # self.popMenuSent.addAction( self.actionSentClipboard ) + # self.popMenuSent.addAction( self.actionTrashSentMessage ) def rerenderTabTreeSubscriptions(self): - """TBC""" - treeWidget = self.ui.treeWidgetSubscriptions folders = Ui_FolderWidget.folderWeight.keys() folders.remove("new") @@ -434,16 +393,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth treeWidget.header().setSortIndicator( 0, QtCore.Qt.AscendingOrder) # init dictionary - + db = getSortedSubscriptions(True) for address in db: for folder in folders: - if folder not in db[address]: + if not folder in db[address]: db[address][folder] = {} - + if treeWidget.isSortingEnabled(): treeWidget.setSortingEnabled(False) + widgets = {} i = 0 while i < treeWidget.topLevelItemCount(): widget = treeWidget.topLevelItem(i) @@ -451,8 +411,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth toAddress = widget.address else: toAddress = None - - if toAddress not in db: + + if not toAddress in db: treeWidget.takeTopLevelItem(i) # no increment continue @@ -471,7 +431,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth j += 1 # add missing folders - if db[toAddress]: + if len(db[toAddress]) > 0: j = 0 for f, c in db[toAddress].iteritems(): try: @@ -482,14 +442,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth widget.setUnreadCount(unread) db.pop(toAddress, None) i += 1 - + i = 0 for toAddress in db: - widget = Ui_SubscriptionWidget( - treeWidget, i, toAddress, - db[toAddress]["inbox"]['count'], - db[toAddress]["inbox"]['label'], - db[toAddress]["inbox"]['enabled']) + widget = Ui_SubscriptionWidget(treeWidget, i, toAddress, db[toAddress]["inbox"]['count'], db[toAddress]["inbox"]['label'], db[toAddress]["inbox"]['enabled']) j = 0 unread = 0 for folder in folders: @@ -501,28 +457,23 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth j += 1 widget.setUnreadCount(unread) i += 1 - + treeWidget.setSortingEnabled(True) - def rerenderTabTreeMessages(self): - """TBC""" + def rerenderTabTreeMessages(self): self.rerenderTabTree('messages') def rerenderTabTreeChans(self): - """TBC""" - self.rerenderTabTree('chan') - + def rerenderTabTree(self, tab): - """TBC""" - if tab == 'messages': treeWidget = self.ui.treeWidgetYourIdentities elif tab == 'chan': treeWidget = self.ui.treeWidgetChans folders = Ui_FolderWidget.folderWeight.keys() - + # sort ascending when creating if treeWidget.topLevelItemCount() == 0: treeWidget.header().setSortIndicator( @@ -530,12 +481,14 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # init dictionary db = {} enabled = {} - + for toAddress in getSortedAccounts(): isEnabled = BMConfigParser().getboolean( toAddress, 'enabled') isChan = BMConfigParser().safeGetBoolean( toAddress, 'chan') + isMaillinglist = BMConfigParser().safeGetBoolean( + toAddress, 'mailinglist') if treeWidget == self.ui.treeWidgetYourIdentities: if isChan: @@ -547,13 +500,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth db[toAddress] = {} for folder in folders: db[toAddress][folder] = 0 - + enabled[toAddress] = isEnabled # get number of (unread) messages total = 0 - queryreturn = sqlQuery( - 'SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder') + queryreturn = sqlQuery('SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder') for row in queryreturn: toaddress, folder, cnt = row total += cnt @@ -566,10 +518,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth db[None]["sent"] = 0 db[None]["trash"] = 0 enabled[None] = True - + if treeWidget.isSortingEnabled(): treeWidget.setSortingEnabled(False) - + + widgets = {} i = 0 while i < treeWidget.topLevelItemCount(): widget = treeWidget.topLevelItem(i) @@ -577,8 +530,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth toAddress = widget.address else: toAddress = None - - if toAddress not in db: + + if not toAddress in db: treeWidget.takeTopLevelItem(i) # no increment continue @@ -598,7 +551,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth j += 1 # add missing folders - if db[toAddress]: + if len(db[toAddress]) > 0: j = 0 for f, c in db[toAddress].iteritems(): if toAddress is not None and tab == 'messages' and folder == "new": @@ -610,7 +563,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth widget.setUnreadCount(unread) db.pop(toAddress, None) i += 1 - + i = 0 for toAddress in db: widget = Ui_AddressWidget(treeWidget, i, toAddress, db[toAddress]["inbox"], enabled[toAddress]) @@ -625,12 +578,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth j += 1 widget.setUnreadCount(unread) i += 1 - + treeWidget.setSortingEnabled(True) def __init__(self, parent=None): - """TBC""" - QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) @@ -638,14 +589,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # Ask the user if we may delete their old version 1 addresses if they # have any. for addressInKeysFile in getSortedAccounts(): - status, addressVersionNumber, streamNumber, addressHash = decodeAddress( + status, addressVersionNumber, streamNumber, hash = decodeAddress( addressInKeysFile) if addressVersionNumber == 1: displayMsg = _translate( - "MainWindow", - 'One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer ' - 'supported. May we delete it now?' - ).arg(addressInKeysFile) + "MainWindow", "One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer supported. " + + "May we delete it now?").arg(addressInKeysFile) reply = QtGui.QMessageBox.question( self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: @@ -655,13 +604,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # Configure Bitmessage to start on startup (or remove the # configuration) based on the setting in the keys.dat file if 'win32' in sys.platform or 'win64' in sys.platform: - # Auto-startup for Windows RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat) - # In case the user moves the program and the registry entry is no longer - # valid, this will delete the old registry entry. - self.settings.remove("PyBitmessage") + self.settings.remove( + "PyBitmessage") # In case the user moves the program and the registry entry is no longer valid, this will delete the old registry entry. if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'): self.settings.setValue("PyBitmessage", sys.argv[0]) elif 'darwin' in sys.platform: @@ -673,13 +620,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # e.g. for editing labels self.recurDepth = 0 - + # switch back to this when replying self.replyFromTab = None # so that quit won't loop self.quitAccepted = False - + self.init_file_menu() self.init_inbox_popup_menu() self.init_identities_popup_menu() @@ -775,13 +722,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.unreadCount = 0 # Set the icon sizes for the identicons - identicon_size = 3 * 7 + identicon_size = 3*7 self.ui.tableWidgetInbox.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.treeWidgetChans.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.treeWidgetYourIdentities.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.treeWidgetSubscriptions.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.tableWidgetAddressBook.setIconSize(QtCore.QSize(identicon_size, identicon_size)) - + self.UISignalThread = UISignaler.get() QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) @@ -791,15 +738,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByToAddress) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByAckdata) - QtCore.QObject.connect( - self.UISignalThread, QtCore.SIGNAL( - "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), - self.displayNewInboxMessage) - QtCore.QObject.connect( - self.UISignalThread, QtCore.SIGNAL( - ("displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject," - "PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)")), - self.displayNewSentMessage) + QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( + "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewInboxMessage) + QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( + "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewSentMessage) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "setStatusIcon(PyQt_PyObject)"), self.setStatusIcon) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( @@ -840,16 +782,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.rerenderComboBoxSendFrom() self.rerenderComboBoxSendFromBroadcast() - + # Put the TTL slider in the correct spot TTL = BMConfigParser().getint('bitmessagesettings', 'ttl') - if TTL < 3600: # an hour + if TTL < 3600: # an hour TTL = 3600 - elif TTL > 28 * 24 * 60 * 60: # 28 days - TTL = 28 * 24 * 60 * 60 - self.ui.horizontalSliderTTL.setSliderPosition((TTL - 3600) ** (1 / 3.199)) + elif TTL > 28*24*60*60: # 28 days + TTL = 28*24*60*60 + self.ui.horizontalSliderTTL.setSliderPosition((TTL - 3600) ** (1/3.199)) self.updateHumanFriendlyTTLDescription(TTL) - + QtCore.QObject.connect(self.ui.horizontalSliderTTL, QtCore.SIGNAL( "valueChanged(int)"), self.updateTTL) @@ -861,24 +803,20 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # Hide the 'Fetch Namecoin ID' button if we can't. if BMConfigParser().safeGetBoolean( 'bitmessagesettings', 'dontconnect' - ) or self.namecoin.test()[0] == 'failed': + ) or self.namecoin.test()[0] == 'failed': logger.warning( 'There was a problem testing for a Namecoin daemon. Hiding the' ' Fetch Namecoin ID button') self.ui.pushButtonFetchNamecoinID.hide() def updateTTL(self, sliderPosition): - """TBC""" - TTL = int(sliderPosition ** 3.199 + 3600) self.updateHumanFriendlyTTLDescription(TTL) BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL)) BMConfigParser().save() - + def updateHumanFriendlyTTLDescription(self, TTL): - """TBC""" - - numberOfHours = int(round(TTL / (60 * 60))) + numberOfHours = int(round(TTL / (60*60))) font = QtGui.QFont() stylesheet = "" @@ -887,28 +825,19 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth _translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfHours) + ", " + _translate("MainWindow", "not recommended for chans", None, QtCore.QCoreApplication.CodecForTr) - ) + ) stylesheet = "QLabel { color : red; }" font.setBold(True) else: - numberOfDays = int(round(TTL / (24 * 60 * 60))) - self.ui.labelHumanFriendlyTTLDescription.setText( - _translate( - "MainWindow", - "%n day(s)", - None, - QtCore.QCoreApplication.CodecForTr, - numberOfDays)) + numberOfDays = int(round(TTL / (24*60*60))) + self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays)) font.setBold(False) self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet) self.ui.labelHumanFriendlyTTLDescription.setFont(font) + # Show or hide the application window after clicking an item within the + # tray icon or, on Windows, the try icon itself. def appIndicatorShowOrHideWindow(self): - """ - Show or hide the application window after clicking an item within the tray icon or, on Windows, - the try icon itself. - """ - if not self.actionShow.isChecked(): self.hide() else: @@ -918,18 +847,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.raise_() self.activateWindow() + # show the application window def appIndicatorShow(self): - """show the application window""" - if self.actionShow is None: return if not self.actionShow.isChecked(): self.actionShow.setChecked(True) self.appIndicatorShowOrHideWindow() + # unchecks the show item on the application indicator def appIndicatorHide(self): - """unchecks the show item on the application indicator""" - if self.actionShow is None: return if self.actionShow.isChecked(): @@ -937,16 +864,25 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.appIndicatorShowOrHideWindow() def appIndicatorSwitchQuietMode(self): - """TBC""" - BMConfigParser().set( 'bitmessagesettings', 'showtraynotifications', str(not self.actionQuiet.isChecked()) ) - def appIndicatorInbox(self, item=None): - """Show the program window and select inbox tab""" + # application indicator show or hide + """# application indicator show or hide + def appIndicatorShowBitmessage(self): + #if self.actionShow == None: + # return + print self.actionShow.isChecked() + if not self.actionShow.isChecked(): + self.hide() + #self.setWindowState(self.windowState() & QtCore.Qt.WindowMinimized) + else: + self.appIndicatorShowOrHideWindow()""" + # Show the program window and select inbox tab + def appIndicatorInbox(self, item=None): self.appIndicatorShow() # select inbox self.ui.tabWidget.setCurrentIndex( @@ -962,24 +898,22 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth else: self.ui.tableWidgetInbox.setCurrentCell(0, 0) + # Show the program window and select send tab def appIndicatorSend(self): - """Show the program window and select send tab""" self.appIndicatorShow() self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.indexOf(self.ui.send) ) + # Show the program window and select subscriptions tab def appIndicatorSubscribe(self): - """Show the program window and select subscriptions tab""" - self.appIndicatorShow() self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.indexOf(self.ui.subscriptions) ) + # Show the program window and select channels tab def appIndicatorChannel(self): - """Show the program window and select channels tab""" - self.appIndicatorShow() self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.indexOf(self.ui.chans) @@ -1025,12 +959,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth for col in (0, 1, 2): related.item(rrow, col).setUnread(not status) - def propagateUnreadCount(self, address=None, folder="inbox", widget=None, type_arg=1): - """TBC""" - + def propagateUnreadCount(self, address = None, folder = "inbox", widget = None, type = 1): widgets = [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] - queryReturn = sqlQuery( - "SELECT toaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder") + queryReturn = sqlQuery("SELECT toaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder") totalUnread = {} normalUnread = {} for row in queryReturn: @@ -1042,15 +973,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth totalUnread[row[1]] += row[2] else: totalUnread[row[1]] = row[2] - queryReturn = sqlQuery( - "SELECT fromaddress, folder, COUNT(msgid) AS cnt FROM inbox " - "WHERE read = 0 AND toaddress = ? GROUP BY fromaddress, folder", - str_broadcast_subscribers) + queryReturn = sqlQuery("SELECT fromaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 AND toaddress = ? GROUP BY fromaddress, folder", str_broadcast_subscribers) broadcastsUnread = {} for row in queryReturn: broadcastsUnread[row[0]] = {} broadcastsUnread[row[0]][row[1]] = row[2] - + for treeWidget in widgets: root = treeWidget.invisibleRootItem() for i in range(root.childCount()): @@ -1077,8 +1005,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth if addressItem.type == AccountMixin.ALL and folderName in totalUnread: newCount = totalUnread[folderName] elif addressItem.type == AccountMixin.SUBSCRIPTION: - if addressItem.address in broadcastsUnread and folderName in broadcastsUnread[ - addressItem.address]: + if addressItem.address in broadcastsUnread and folderName in broadcastsUnread[addressItem.address]: newCount = broadcastsUnread[addressItem.address][folderName] elif addressItem.address in normalUnread and folderName in normalUnread[addressItem.address]: newCount = normalUnread[addressItem.address][folderName] @@ -1086,20 +1013,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth folderItem.setUnreadCount(newCount) def addMessageListItem(self, tableWidget, items): - """TBC""" - sortingEnabled = tableWidget.isSortingEnabled() if sortingEnabled: tableWidget.setSortingEnabled(False) tableWidget.insertRow(0) - for i, _ in enumerate(items): + for i in range(len(items)): tableWidget.setItem(0, i, items[i]) if sortingEnabled: tableWidget.setSortingEnabled(True) def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime): - """TBC""" - acct = accountClass(fromAddress) if acct is None: acct = BMAccount(fromAddress) @@ -1138,19 +1061,14 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth statusText = _translate( "MainWindow", "Doing work necessary to send broadcast.") elif status == 'broadcastsent': - statusText = _translate( - "MainWindow", "Broadcast on %1").arg( - l10n.formatTimestamp(lastactiontime)) + statusText = _translate("MainWindow", "Broadcast on %1").arg( + l10n.formatTimestamp(lastactiontime)) elif status == 'toodifficult': - statusText = _translate( - "MainWindow", - "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg( - l10n.formatTimestamp(lastactiontime)) + statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg( + l10n.formatTimestamp(lastactiontime)) elif status == 'badkey': - statusText = _translate( - "MainWindow", - "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg( - l10n.formatTimestamp(lastactiontime)) + statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg( + l10n.formatTimestamp(lastactiontime)) elif status == 'forcepow': statusText = _translate( "MainWindow", "Forced difficulty override. Send should start soon.") @@ -1168,8 +1086,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth return acct def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read): - """TBC""" - font = QtGui.QFont() font.setBold(True) if toAddress == str_broadcast_subscribers: @@ -1181,9 +1097,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth if acct is None: acct = BMAccount(fromAddress) acct.parseMessage(toAddress, fromAddress, subject, "") - + items = [] - # to + #to MessageList_AddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read) # from MessageList_AddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read) @@ -1202,9 +1118,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.addMessageListItem(tableWidget, items) return acct + # Load Sent items from database def loadSent(self, tableWidget, account, where="", what=""): - """Load Sent items from database""" - if tableWidget == self.ui.tableWidgetInboxSubscriptions: tableWidget.setColumnHidden(0, True) tableWidget.setColumnHidden(1, False) @@ -1236,9 +1151,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None)) tableWidget.setUpdatesEnabled(True) - def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly=False): - """Load messages from database file""" - + # Load messages from database file + def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly = False): if folder == 'sent': self.loadSent(tableWidget, account, where, what) return @@ -1259,11 +1173,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth tableWidget.setRowCount(0) queryreturn = helper_search.search_sql(xAddress, account, folder, where, what, unreadOnly) - + for row in queryreturn: msgfolder, msgid, toAddress, fromAddress, subject, received, read = row - self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, - fromAddress, subject, received, read) + self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read) tableWidget.horizontalHeader().setSortIndicator( 3, QtCore.Qt.DescendingOrder) @@ -1272,10 +1185,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None)) tableWidget.setUpdatesEnabled(True) - def appIndicatorInit(self, this_app): - """create application indicator""" - - self.initTrayIcon("can-icon-24px-red.png", this_app) + # create application indicator + def appIndicatorInit(self, app): + self.initTrayIcon("can-icon-24px-red.png", app) traySignal = "activated(QSystemTrayIcon::ActivationReason)" QtCore.QObject.connect(self.tray, QtCore.SIGNAL( traySignal), self.__icon_activated) @@ -1297,7 +1209,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.actionShow.setChecked(not BMConfigParser().getboolean( 'bitmessagesettings', 'startintray')) self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow) - if sys.platform[0:3] != 'win': + if not sys.platform[0:3] == 'win': m.addAction(self.actionShow) # quiet mode @@ -1338,9 +1250,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.tray.setContextMenu(m) self.tray.show() + # returns the number of unread messages and subscriptions def getUnread(self): - """returns the number of unread messages and subscriptions""" - counters = [0, 0] queryreturn = sqlQuery(''' @@ -1355,15 +1266,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth return counters - def playSound(self, category, label): # pylint: disable=inconsistent-return-statements - """play a sound""" - + # play a sound + def playSound(self, category, label): # filename of the sound to be played soundFilename = None - def _choose_ext(basename): # pylint: disable=inconsistent-return-statements - """TBC""" - + def _choose_ext(basename): for ext in sound.extensions: if os.path.isfile(os.extsep.join([basename, ext])): return os.extsep + ext @@ -1385,23 +1293,24 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # elapsed time since the last sound was played dt = datetime.now() - self.lastSoundTime # suppress sounds which are more frequent than the threshold - if not dt.total_seconds() < self.maxSoundFrequencySec: + if dt.total_seconds() < self.maxSoundFrequencySec: + return - # the sound is for an address which exists in the address book - if category is sound.SOUND_KNOWN: - soundFilename = state.appdata + 'sounds/known' - # the sound is for an unknown address - elif category is sound.SOUND_UNKNOWN: - soundFilename = state.appdata + 'sounds/unknown' - # initial connection sound - elif category is sound.SOUND_CONNECTED: - soundFilename = state.appdata + 'sounds/connected' - # disconnected sound - elif category is sound.SOUND_DISCONNECTED: - soundFilename = state.appdata + 'sounds/disconnected' - # sound when the connection status becomes green - elif category is sound.SOUND_CONNECTION_GREEN: - soundFilename = state.appdata + 'sounds/green' + # the sound is for an address which exists in the address book + if category is sound.SOUND_KNOWN: + soundFilename = state.appdata + 'sounds/known' + # the sound is for an unknown address + elif category is sound.SOUND_UNKNOWN: + soundFilename = state.appdata + 'sounds/unknown' + # initial connection sound + elif category is sound.SOUND_CONNECTED: + soundFilename = state.appdata + 'sounds/connected' + # disconnected sound + elif category is sound.SOUND_DISCONNECTED: + soundFilename = state.appdata + 'sounds/disconnected' + # sound when the connection status becomes green + elif category is sound.SOUND_CONNECTION_GREEN: + soundFilename = state.appdata + 'sounds/green' if soundFilename is None: logger.warning("Probably wrong category number in playSound()") @@ -1425,14 +1334,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self._player(soundFilename) + # Adapters and converters for QT <-> sqlite def sqlInit(self): - """Adapters and converters for QT <-> sqlite""" - register_adapter(QtCore.QByteArray, str) + # Try init the distro specific appindicator, + # for example the Ubuntu MessagingMenu def indicatorInit(self): - """ Try init the distro specific appindicator, for example the Ubuntu MessagingMenu""" - def _noop_update(*args, **kwargs): pass @@ -1442,9 +1350,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth logger.warning("No indicator plugin found") self.indicatorUpdate = _noop_update + # initialise the message notifier def notifierInit(self): - """initialise the message notifier""" - def _simple_notify( title, subtitle, category, label=None, icon=None): self.tray.showMessage(title, subtitle, 1, 2000) @@ -1474,34 +1381,27 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth def notifierShow( self, title, subtitle, category, label=None, icon=None): - """TBC""" - self.playSound(category, label) self._notifier( unicode(title), unicode(subtitle), category, label, icon) + # tree def treeWidgetKeyPressEvent(self, event): - """tree""" - return self.handleKeyPress(event, self.getCurrentTreeWidget()) + # inbox / sent def tableWidgetKeyPressEvent(self, event): - """inbox / sent""" - return self.handleKeyPress(event, self.getCurrentMessagelist()) + # messageview def textEditKeyPressEvent(self, event): - """messageview""" - return self.handleKeyPress(event, self.getCurrentMessageTextedit()) - def handleKeyPress(self, event, focus=None): # pylint: disable=inconsistent-return-statements - """TBC""" - + def handleKeyPress(self, event, focus = None): messagelist = self.getCurrentMessagelist() folder = self.getCurrentFolder() if event.key() == QtCore.Qt.Key_Delete: - if isinstance(focus, (MessageView, QtGui.QTableWidget)): + if isinstance (focus, MessageView) or isinstance(focus, QtGui.QTableWidget): if folder == "sent": self.on_action_SentTrash() else: @@ -1537,116 +1437,60 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.lineEditTo.setFocus() event.ignore() elif event.key() == QtCore.Qt.Key_F: - searchline = self.getCurrentSearchLine(retObj=True) + searchline = self.getCurrentSearchLine(retObj = True) if searchline: searchline.setFocus() event.ignore() if not event.isAccepted(): return - if isinstance(focus, MessageView): + if isinstance (focus, MessageView): return MessageView.keyPressEvent(focus, event) - elif isinstance(focus, QtGui.QTableWidget): + elif isinstance (focus, QtGui.QTableWidget): return QtGui.QTableWidget.keyPressEvent(focus, event) - elif isinstance(focus, QtGui.QTreeWidget): + elif isinstance (focus, QtGui.QTreeWidget): return QtGui.QTreeWidget.keyPressEvent(focus, event) + # menu button 'manage keys' def click_actionManageKeys(self): - """menu button 'manage keys'""" - if 'darwin' in sys.platform or 'linux' in sys.platform: if state.appdata == '': # reply = QtGui.QMessageBox.information(self, 'keys.dat?','You # may manage your keys by editing the keys.dat file stored in # the same directory as this program. It is important that you # back up this file.', QMessageBox.Ok) - reply = QtGui.QMessageBox.information( - self, - 'keys.dat?', - _translate( - "MainWindow", - ("You may manage your keys by editing the keys.dat file stored in the same directory as this " - "program. It is important that you back up this file.")), - QtGui.QMessageBox.Ok) + reply = QtGui.QMessageBox.information(self, 'keys.dat?', _translate( + "MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file."), QtGui.QMessageBox.Ok) else: - QtGui.QMessageBox.information( - self, - 'keys.dat?', - _translate( - "MainWindow", - ("You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important " - "that you back up this file.")).arg( - state.appdata), - QtGui.QMessageBox.Ok) + QtGui.QMessageBox.information(self, 'keys.dat?', _translate( + "MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file.").arg(state.appdata), QtGui.QMessageBox.Ok) elif sys.platform == 'win32' or sys.platform == 'win64': if state.appdata == '': - reply = QtGui.QMessageBox.question( - self, - _translate( - "MainWindow", - "Open keys.dat?"), - _translate( - "MainWindow", - ("You may manage your keys by editing the keys.dat file stored in the same directory as this " - "program. It is important that you back up this file. Would you like to open the file now? " - "(Be sure to close Bitmessage before making any changes.)")), - QtGui.QMessageBox.Yes, - QtGui.QMessageBox.No) + reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( + "MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) else: - reply = QtGui.QMessageBox.question( - self, - _translate( - "MainWindow", - "Open keys.dat?"), - _translate( - "MainWindow", - ("You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important " - "that you back up this file. Would you like to open the file now? (Be sure to close " - "Bitmessage before making any changes.)")).arg( - state.appdata), - QtGui.QMessageBox.Yes, - QtGui.QMessageBox.No) + reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( + "MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)").arg(state.appdata), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: shared.openKeysFile() + # menu button 'delete all treshed messages' def click_actionDeleteAllTrashedMessages(self): - """menu button 'delete all treshed messages'""" - - if QtGui.QMessageBox.question( - self, - _translate( - "MainWindow", - "Delete trash?"), - _translate( - "MainWindow", - "Are you sure you want to delete all trashed messages?"), - QtGui.QMessageBox.Yes, - QtGui.QMessageBox.No) == QtGui.QMessageBox.No: + if QtGui.QMessageBox.question(self, _translate("MainWindow", "Delete trash?"), _translate("MainWindow", "Are you sure you want to delete all trashed messages?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.No: return sqlStoredProcedure('deleteandvacuume') self.rerenderTabTreeMessages() self.rerenderTabTreeSubscriptions() self.rerenderTabTreeChans() if self.getCurrentFolder(self.ui.treeWidgetYourIdentities) == "trash": - self.loadMessagelist( - self.ui.tableWidgetInbox, self.getCurrentAccount( - self.ui.treeWidgetYourIdentities), "trash") + self.loadMessagelist(self.ui.tableWidgetInbox, self.getCurrentAccount(self.ui.treeWidgetYourIdentities), "trash") elif self.getCurrentFolder(self.ui.treeWidgetSubscriptions) == "trash": - self.loadMessagelist( - self.ui.tableWidgetInboxSubscriptions, - self.getCurrentAccount( - self.ui.treeWidgetSubscriptions), - "trash") + self.loadMessagelist(self.ui.tableWidgetInboxSubscriptions, self.getCurrentAccount(self.ui.treeWidgetSubscriptions), "trash") elif self.getCurrentFolder(self.ui.treeWidgetChans) == "trash": - self.loadMessagelist( - self.ui.tableWidgetInboxChans, - self.getCurrentAccount( - self.ui.treeWidgetChans), - "trash") + self.loadMessagelist(self.ui.tableWidgetInboxChans, self.getCurrentAccount(self.ui.treeWidgetChans), "trash") + # menu button 'regenerate deterministic addresses' def click_actionRegenerateDeterministicAddresses(self): - """menu button 'regenerate deterministic addresses'""" - dialog = dialogs.RegenerateAddressesDialog(self) if dialog.exec_(): if dialog.lineEditPassphrase.text() == "": @@ -1693,14 +1537,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.tabWidget.indexOf(self.ui.chans) ) + # opens 'join chan' dialog def click_actionJoinChan(self): - """opens 'join chan' dialog""" - dialogs.NewChanDialog(self) def showConnectDialog(self): - """TBC""" - dialog = dialogs.ConnectDialog(self) if dialog.exec_(): if dialog.radioButtonConnectNow.isChecked(): @@ -1713,8 +1554,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self._firstrun = False def showMigrationWizard(self, level): - """TBC""" - self.migrationWizardInstance = Ui_MigrationWizard(["a"]) if self.migrationWizardInstance.exec_(): pass @@ -1722,8 +1561,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth pass def changeEvent(self, event): - """TBC""" - if event.type() == QtCore.QEvent.LanguageChange: self.ui.retranslateUi(self) self.init_inbox_popup_menu(False) @@ -1735,17 +1572,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.blackwhitelist.init_blacklist_popup_menu(False) if event.type() == QtCore.QEvent.WindowStateChange: if self.windowState() & QtCore.Qt.WindowMinimized: - if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray'): - if 'darwin' not in sys.platform: - QtCore.QTimer.singleShot(0, self.appIndicatorHide) + if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray') and not 'darwin' in sys.platform: + QtCore.QTimer.singleShot(0, self.appIndicatorHide) elif event.oldState() & QtCore.Qt.WindowMinimized: # The window state has just been changed to # Normal/Maximised/FullScreen pass + # QtGui.QWidget.changeEvent(self, event) def __icon_activated(self, reason): - """TBC""" - if reason == QtGui.QSystemTrayIcon.Trigger: self.actionShow.setChecked(not self.actionShow.isChecked()) self.appIndicatorShowOrHideWindow() @@ -1754,8 +1589,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth connected = False def setStatusIcon(self, color): - """Set the status icon""" - + # print 'setting status icon color' _notifications_enabled = not BMConfigParser().getboolean( 'bitmessagesettings', 'hidetrayconnectionnotifications') if color == 'red': @@ -1769,7 +1603,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth _translate("MainWindow", "Connection lost"), sound.SOUND_DISCONNECTED) if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and \ - BMConfigParser().get('bitmessagesettings', 'socksproxytype') == "none": + BMConfigParser().get('bitmessagesettings', 'socksproxytype') == "none": self.updateStatusBar( _translate( "MainWindow", @@ -1783,9 +1617,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Not Connected")) self.setTrayIconFile("can-icon-24px-red.png") if color == 'yellow': - if self.statusbar.currentMessage() == ('Warning: You are currently not connected. Bitmessage will do ' - 'the work necessary to send the message but it won\'t send until ' - 'you connect.'): + if self.statusbar.currentMessage() == 'Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.': self.statusbar.clearMessage() self.pushButtonStatusIcon.setIcon( QtGui.QIcon(":/newPrefix/images/yellowicon.png")) @@ -1803,9 +1635,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Connected")) self.setTrayIconFile("can-icon-24px-yellow.png") if color == 'green': - if self.statusbar.currentMessage() == ('Warning: You are currently not connected. Bitmessage will do the ' - 'work necessary to send the message but it won\'t send until you ' - 'connect.'): + if self.statusbar.currentMessage() == 'Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.': self.statusbar.clearMessage() self.pushButtonStatusIcon.setIcon( QtGui.QIcon(":/newPrefix/images/greenicon.png")) @@ -1822,23 +1652,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Connected")) self.setTrayIconFile("can-icon-24px-green.png") - def initTrayIcon(self, iconFileName, this_app): - """TBC""" - + def initTrayIcon(self, iconFileName, app): self.currentTrayIconFileName = iconFileName self.tray = QtGui.QSystemTrayIcon( - self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), this_app) + self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), app) def setTrayIconFile(self, iconFileName): - """TBC""" - self.currentTrayIconFileName = iconFileName self.drawTrayIcon(iconFileName, self.findInboxUnreadCount()) def calcTrayIcon(self, iconFileName, inboxUnreadCount): - """TBC""" - - pixmap = QtGui.QPixmap(":/newPrefix/images/" + iconFileName) + pixmap = QtGui.QPixmap(":/newPrefix/images/"+iconFileName) if inboxUnreadCount > 0: # choose font and calculate font parameters fontName = "Lucida" @@ -1850,7 +1674,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth rect = fontMetrics.boundingRect(txt) # margins that we add in the top-right corner marginX = 2 - marginY = 0 # it looks like -2 is also ok due to the error of metric + marginY = 0 # it looks like -2 is also ok due to the error of metric # if it renders too wide we need to change it to a plus symbol if rect.width() > 20: txt = "+" @@ -1864,18 +1688,14 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth painter.setPen( QtGui.QPen(QtGui.QColor(255, 0, 0), QtCore.Qt.SolidPattern)) painter.setFont(font) - painter.drawText(24 - rect.right() - marginX, -rect.top() + marginY, txt) + painter.drawText(24-rect.right()-marginX, -rect.top()+marginY, txt) painter.end() return QtGui.QIcon(pixmap) def drawTrayIcon(self, iconFileName, inboxUnreadCount): - """TBC""" - self.tray.setIcon(self.calcTrayIcon(iconFileName, inboxUnreadCount)) def changedInboxUnread(self, row=None): - """TBC""" - self.drawTrayIcon( self.currentTrayIconFileName, self.findInboxUnreadCount()) self.rerenderTabTreeMessages() @@ -1883,8 +1703,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.rerenderTabTreeChans() def findInboxUnreadCount(self, count=None): - """TBC""" - if count is None: queryreturn = sqlQuery('''SELECT count(*) from inbox WHERE folder='inbox' and read=0''') cnt = 0 @@ -1896,14 +1714,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth return self.unreadCount def updateSentItemStatusByToAddress(self, toAddress, textToDisplay): - """TBC""" - for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: treeWidget = self.widgetConvert(sent) if self.getCurrentFolder(treeWidget) != "sent": continue - if treeWidget in [self.ui.treeWidgetSubscriptions, - self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress: + if treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress: continue for i in range(sent.rowCount()): @@ -1912,7 +1727,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth sent.item(i, 3).setToolTip(textToDisplay) try: newlinePosition = textToDisplay.indexOf('\n') - except: # If no "_translate" appended to string before passing in, there's no qstring + except: # If someone misses adding a "_translate" to a string before passing it to this function, this function won't receive a qstring which will cause an exception. newlinePosition = 0 if newlinePosition > 1: sent.item(i, 3).setText( @@ -1921,9 +1736,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth sent.item(i, 3).setText(textToDisplay) def updateSentItemStatusByAckdata(self, ackdata, textToDisplay): - """TBC""" - - if isinstance(ackdata, str): + if type(ackdata) is str: ackdata = QtCore.QByteArray(ackdata) for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: treeWidget = self.widgetConvert(sent) @@ -1940,7 +1753,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth sent.item(i, 3).setToolTip(textToDisplay) try: newlinePosition = textToDisplay.indexOf('\n') - except: # If no "_translate" appended to string before passing in, there's no qstring + except: # If someone misses adding a "_translate" to a string before passing it to this function, this function won't receive a qstring which will cause an exception. newlinePosition = 0 if newlinePosition > 1: sent.item(i, 3).setText( @@ -1949,80 +1762,50 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth sent.item(i, 3).setText(textToDisplay) def removeInboxRowByMsgid(self, msgid): # msgid and inventoryHash are the same thing - """TBC""" - for inbox in ([ - self.ui.tableWidgetInbox, - self.ui.tableWidgetInboxSubscriptions, - self.ui.tableWidgetInboxChans]): + self.ui.tableWidgetInbox, + self.ui.tableWidgetInboxSubscriptions, + self.ui.tableWidgetInboxChans]): for i in range(inbox.rowCount()): if msgid == str(inbox.item(i, 3).data(QtCore.Qt.UserRole).toPyObject()): self.updateStatusBar( _translate("MainWindow", "Message trashed")) treeWidget = self.widgetConvert(inbox) - self.propagateUnreadCount( - inbox.item( - i, - 1 if inbox.item( - i, - 1).type == AccountMixin.SUBSCRIPTION else 0).data( - QtCore.Qt.UserRole), - self.getCurrentFolder(treeWidget), - treeWidget, - 0) + self.propagateUnreadCount(inbox.item(i, 1 if inbox.item(i, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder(treeWidget), treeWidget, 0) inbox.removeRow(i) break def newVersionAvailable(self, version): - """TBC""" - self.notifiedNewVersion = ".".join(str(n) for n in version) - self.updateStatusBar( - _translate( - "MainWindow", - "New version of PyBitmessage is available: %1. Download it" - " from https://github.com/Bitmessage/PyBitmessage/releases/latest" + self.updateStatusBar(_translate( + "MainWindow", + "New version of PyBitmessage is available: %1. Download it" + " from https://github.com/Bitmessage/PyBitmessage/releases/latest" ).arg(self.notifiedNewVersion) ) def displayAlert(self, title, text, exitAfterUserClicksOk): - """TBC""" - self.updateStatusBar(text) QtGui.QMessageBox.critical(self, title, text, QtGui.QMessageBox.Ok) if exitAfterUserClicksOk: - sys.exit(0) + os._exit(0) def rerenderMessagelistFromLabels(self): - """TBC""" - - for messagelist in ( - self.ui.tableWidgetInbox, - self.ui.tableWidgetInboxChans, - self.ui.tableWidgetInboxSubscriptions): + for messagelist in (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions): for i in range(messagelist.rowCount()): messagelist.item(i, 1).setLabel() def rerenderMessagelistToLabels(self): - """TBC""" - - for messagelist in ( - self.ui.tableWidgetInbox, - self.ui.tableWidgetInboxChans, - self.ui.tableWidgetInboxSubscriptions): + for messagelist in (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions): for i in range(messagelist.rowCount()): messagelist.item(i, 0).setLabel() def rerenderAddressBook(self): - """TBC""" - - def addRow(address, label, arg_type): - """TBC""" - + def addRow (address, label, type): self.ui.tableWidgetAddressBook.insertRow(0) - newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), arg_type) + newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), type) self.ui.tableWidgetAddressBook.setItem(0, 0, newItem) - newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), arg_type) + newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type) self.ui.tableWidgetAddressBook.setItem(0, 1, newItem) oldRows = {} @@ -2054,7 +1837,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth newRows[address] = [label, AccountMixin.NORMAL] completerList = [] - for address in sorted(oldRows, key=lambda x: oldRows[x][2], reverse=True): + for address in sorted(oldRows, key = lambda x: oldRows[x][2], reverse = True): if address in newRows: completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">") newRows.pop(address) @@ -2071,42 +1854,22 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.lineEditTo.completer().model().setStringList(completerList) def rerenderSubscriptions(self): - """TBC""" - self.rerenderTabTreeSubscriptions() def click_pushButtonTTL(self): - """TBC""" - QtGui.QMessageBox.information(self, 'Time To Live', _translate( - "MainWindow", - ("The TTL, or Time-To-Live is the length of time that the network will hold the message." - "The recipient must get it during this time. If your Bitmessage client does not hear an " - "acknowledgement, it will resend the message automatically. The longer the Time-To-Live, " - "the more work your computer must do to send the message. A Time-To-Live of four or five " - "days is often appropriate.")), QtGui.QMessageBox.Ok) + "MainWindow", """The TTL, or Time-To-Live is the length of time that the network will hold the message. + The recipient must get it during this time. If your Bitmessage client does not hear an acknowledgement, it + will resend the message automatically. The longer the Time-To-Live, the + more work your computer must do to send the message. A Time-To-Live of four or five days is often appropriate."""), QtGui.QMessageBox.Ok) def click_pushButtonClear(self): - """TBC""" - self.ui.lineEditSubject.setText("") self.ui.lineEditTo.setText("") self.ui.textEditMessage.setText("") self.ui.comboBoxSendFrom.setCurrentIndex(0) def click_pushButtonSend(self): - """ - TBC - - Regarding the line below `if len(message) > (2 ** 18 - 500):`: - - The whole network message must fit in 2^18 bytes. - Let's assume 500 bytes of overhead. If someone wants to get that - too an exact number you are welcome to but I think that it would - be a better use of time to support message continuation so that - users can send messages of any length. - """ - encoding = 3 if QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2 self.statusbar.clearMessage() @@ -2131,6 +1894,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth subject = str(self.ui.lineEditSubjectBroadcast.text().toUtf8()) message = str( self.ui.textEditMessageBroadcast.document().toPlainText().toUtf8()) + """ + The whole network message must fit in 2^18 bytes. + Let's assume 500 bytes of overhead. If someone wants to get that + too an exact number you are welcome to but I think that it would + be a better use of time to support message continuation so that + users can send messages of any length. + """ if len(message) > (2 ** 18 - 500): QtGui.QMessageBox.about( self, _translate("MainWindow", "Message too long"), @@ -2144,13 +1914,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth acct = accountClass(fromAddress) - if sendMessageToPeople: # To send a message to specific people (rather than broadcast) + if sendMessageToPeople: # To send a message to specific people (rather than broadcast) toAddressesList = [s.strip() for s in toAddresses.replace(',', ';').split(';')] - # remove duplicate addresses. If the user has one address with a BM- and - # the same address without the BM-, this will not catch it. They'll send - # the message to the person twice. - toAddressesList = list(set(toAddressesList)) + toAddressesList = list(set( + toAddressesList)) # remove duplicate addresses. If the user has one address with a BM- and the same address without the BM-, this will not catch it. They'll send the message to the person twice. for toAddress in toAddressesList: if toAddress != '': # label plus address @@ -2163,30 +1931,25 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth subject = acct.subject toAddress = acct.toAddress else: - if QtGui.QMessageBox.question( - self, "Sending an email?", - _translate( - "MainWindow", - ("You are trying to send an email instead of a bitmessage. This requires " - "registering with a gateway. Attempt to register?")), - QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) != QtGui.QMessageBox.Yes: + if QtGui.QMessageBox.question(self, "Sending an email?", _translate("MainWindow", + "You are trying to send an email instead of a bitmessage. This requires registering with a gateway. Attempt to register?"), + QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) != QtGui.QMessageBox.Yes: continue email = acct.getLabel() - if email[-14:] != "@mailchuck.com": # attempt register + if email[-14:] != "@mailchuck.com": #attempt register # 12 character random email address - email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) - for _ in range(12)) + "@mailchuck.com" + email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com" acct = MailchuckAccount(fromAddress) acct.register(email) BMConfigParser().set(fromAddress, 'label', email) BMConfigParser().set(fromAddress, 'gateway', 'mailchuck') BMConfigParser().save() - self.updateStatusBar( - _translate( - "MainWindow", - ("Error: Your account wasn't registered at an email gateway. Sending registration" - " now as %1, please wait for the registration to be processed before retrying " - "sending.") + self.updateStatusBar(_translate( + "MainWindow", + "Error: Your account wasn't registered at" + " an email gateway. Sending registration" + " now as %1, please wait for the registration" + " to be processed before retrying sending." ).arg(email) ) return @@ -2204,19 +1967,19 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Error: Bitmessage addresses start with" " BM- Please check the recipient address %1" - ).arg(toAddress)) + ).arg(toAddress)) elif status == 'checksumfailed': self.updateStatusBar(_translate( "MainWindow", "Error: The recipient address %1 is not" " typed or copied correctly. Please check it." - ).arg(toAddress)) + ).arg(toAddress)) elif status == 'invalidcharacters': self.updateStatusBar(_translate( "MainWindow", "Error: The recipient address %1 contains" " invalid characters. Please check it." - ).arg(toAddress)) + ).arg(toAddress)) elif status == 'versiontoohigh': self.updateStatusBar(_translate( "MainWindow", @@ -2224,7 +1987,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth " %1 is too high. Either you need to upgrade" " your Bitmessage software or your" " acquaintance is being clever." - ).arg(toAddress)) + ).arg(toAddress)) elif status == 'ripetooshort': self.updateStatusBar(_translate( "MainWindow", @@ -2232,7 +1995,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth " address %1 is too short. There might be" " something wrong with the software of" " your acquaintance." - ).arg(toAddress)) + ).arg(toAddress)) elif status == 'ripetoolong': self.updateStatusBar(_translate( "MainWindow", @@ -2240,7 +2003,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth " address %1 is too long. There might be" " something wrong with the software of" " your acquaintance." - ).arg(toAddress)) + ).arg(toAddress)) elif status == 'varintmalformed': self.updateStatusBar(_translate( "MainWindow", @@ -2248,55 +2011,39 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth " address %1 is malformed. There might be" " something wrong with the software of" " your acquaintance." - ).arg(toAddress)) + ).arg(toAddress)) else: self.updateStatusBar(_translate( "MainWindow", "Error: Something is wrong with the" " recipient address %1." - ).arg(toAddress)) + ).arg(toAddress)) elif fromAddress == '': self.updateStatusBar(_translate( "MainWindow", - ("Error: You must specify a From address. If you don\'t have one, go to the" - " \'Your Identities\' tab."))) + "Error: You must specify a From address. If you" + " don\'t have one, go to the" + " \'Your Identities\' tab.") + ) else: toAddress = addBMIfNotPresent(toAddress) if addressVersionNumber > 4 or addressVersionNumber <= 1: - QtGui.QMessageBox.about( - self, - _translate( - "MainWindow", - "Address version number"), - _translate( - "MainWindow", - ("Concerning the address %1, Bitmessage cannot understand address version " - "numbers of %2. Perhaps upgrade Bitmessage to the latest version.") - ).arg(toAddress).arg( - str(addressVersionNumber))) + QtGui.QMessageBox.about(self, _translate("MainWindow", "Address version number"), _translate( + "MainWindow", "Concerning the address %1, Bitmessage cannot understand address version numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(addressVersionNumber))) continue if streamNumber > 1 or streamNumber == 0: - QtGui.QMessageBox.about( - self, - _translate( - "MainWindow", - "Stream number"), - _translate( - "MainWindow", - ("Concerning the address %1, Bitmessage cannot handle stream numbers of %2. " - "Perhaps upgrade Bitmessage to the latest version.") - ).arg(toAddress).arg( - str(streamNumber))) + QtGui.QMessageBox.about(self, _translate("MainWindow", "Stream number"), _translate( + "MainWindow", "Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(streamNumber))) continue self.statusbar.clearMessage() if shared.statusIconColor == 'red': - self.updateStatusBar( - _translate( - "MainWindow", - ("Warning: You are currently not connected. Bitmessage will do the work necessary" - " to send the message but it won\'t send until you connect.") - ) + self.updateStatusBar(_translate( + "MainWindow", + "Warning: You are currently not connected." + " Bitmessage will do the work necessary to" + " send the message but it won\'t send until" + " you connect.") ) stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') @@ -2311,15 +2058,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth subject, message, ackdata, - int(time.time()), # sentTime (this will never change) - int(time.time()), # lastActionTime - 0, # sleepTill time. This will get set when the POW gets done. + int(time.time()), # sentTime (this will never change) + int(time.time()), # lastActionTime + 0, # sleepTill time. This will get set when the POW gets done. 'msgqueued', - 0, # retryNumber - 'sent', # folder - encoding, # encodingtype + 0, # retryNumber + 'sent', # folder + encoding, # encodingtype BMConfigParser().getint('bitmessagesettings', 'ttl') - ) + ) toLabel = '' queryreturn = sqlQuery('''select label from addressbook where address=?''', @@ -2361,28 +2108,27 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth ackdata = genAckPayload(streamNumber, 0) toAddress = str_broadcast_subscribers ripe = '' - t = ( - '', # msgid. We don't know what this will be until the POW is done. - toAddress, - ripe, - fromAddress, - subject, - message, - ackdata, - int(time.time()), # sentTime (this will never change) - int(time.time()), # lastActionTime - 0, # sleepTill time. This will get set when the POW gets done. - 'broadcastqueued', - 0, # retryNumber - 'sent', # folder - encoding, # encoding type - BMConfigParser().getint('bitmessagesettings', 'ttl') - ) + t = ('', # msgid. We don't know what this will be until the POW is done. + toAddress, + ripe, + fromAddress, + subject, + message, + ackdata, + int(time.time()), # sentTime (this will never change) + int(time.time()), # lastActionTime + 0, # sleepTill time. This will get set when the POW gets done. + 'broadcastqueued', + 0, # retryNumber + 'sent', # folder + encoding, # encoding type + BMConfigParser().getint('bitmessagesettings', 'ttl') + ) sqlExecute( '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t) toLabel = str_broadcast_subscribers - + self.displayNewSentMessage( toAddress, toLabel, fromAddress, subject, message, ackdata) @@ -2399,8 +2145,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Broadcast queued.")) def click_pushButtonLoadFromAddressBook(self): - """TBC""" - self.ui.tabWidget.setCurrentIndex(5) for i in range(4): time.sleep(0.1) @@ -2413,8 +2157,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth )) def click_pushButtonFetchNamecoinID(self): - """TBC""" - nc = namecoinConnection() identities = str(self.ui.lineEditTo.text().toUtf8()).split(";") err, addr = nc.query(identities[-1].strip()) @@ -2428,8 +2170,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Fetched address from namecoin identity.")) def setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(self, address): - """If this is a chan then don't let people broadcast because no one should subscribe to chan addresses.""" - + # If this is a chan then don't let people broadcast because no one + # should subscribe to chan addresses. self.ui.tabWidgetSend.setCurrentIndex( self.ui.tabWidgetSend.indexOf( self.ui.sendBroadcast @@ -2438,20 +2180,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth )) def rerenderComboBoxSendFrom(self): - """TBC""" - self.ui.comboBoxSendFrom.clear() for addressInKeysFile in getSortedAccounts(): - - # I realize that this is poor programming practice but I don't care. It's easier for others to read. - isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled') + isEnabled = BMConfigParser().getboolean( + addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist') if isEnabled and not isMaillinglist: label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() if label == "": label = addressInKeysFile self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) - +# self.ui.comboBoxSendFrom.model().sort(1, Qt.AscendingOrder) for i in range(self.ui.comboBoxSendFrom.count()): address = str(self.ui.comboBoxSendFrom.itemData( i, QtCore.Qt.UserRole).toString()) @@ -2459,26 +2198,22 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth i, AccountColor(address).accountColor(), QtCore.Qt.ForegroundRole) self.ui.comboBoxSendFrom.insertItem(0, '', '') - if self.ui.comboBoxSendFrom.count() == 2: + if(self.ui.comboBoxSendFrom.count() == 2): self.ui.comboBoxSendFrom.setCurrentIndex(1) else: self.ui.comboBoxSendFrom.setCurrentIndex(0) def rerenderComboBoxSendFromBroadcast(self): - """TBC""" - self.ui.comboBoxSendFromBroadcast.clear() for addressInKeysFile in getSortedAccounts(): - - # I realize that this is poor programming practice but I don't care. It's easier for others to read. - isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled') + isEnabled = BMConfigParser().getboolean( + addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan') if isEnabled and not isChan: label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() if label == "": label = addressInKeysFile self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) - for i in range(self.ui.comboBoxSendFromBroadcast.count()): address = str(self.ui.comboBoxSendFromBroadcast.itemData( i, QtCore.Qt.UserRole).toString()) @@ -2486,19 +2221,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth i, AccountColor(address).accountColor(), QtCore.Qt.ForegroundRole) self.ui.comboBoxSendFromBroadcast.insertItem(0, '', '') - if self.ui.comboBoxSendFromBroadcast.count() == 2: + if(self.ui.comboBoxSendFromBroadcast.count() == 2): self.ui.comboBoxSendFromBroadcast.setCurrentIndex(1) else: self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0) + # This function is called by the processmsg function when that function + # receives a message to an address that is acting as a + # pseudo-mailing-list. The message will be broadcast out. This function + # puts the message on the 'Sent' tab. def displayNewSentMessage(self, toAddress, toLabel, fromAddress, subject, message, ackdata): - """ - This function is called by the processmsg function when that function - receives a message to an address that is acting as a - pseudo-mailing-list. The message will be broadcast out. This function - puts the message on the 'Sent' tab. - """ - acct = accountClass(fromAddress) acct.parseMessage(toAddress, fromAddress, subject, message) tab = -1 @@ -2509,33 +2241,18 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth treeWidget = self.widgetConvert(sent) if self.getCurrentFolder(treeWidget) != "sent": continue - if ( - treeWidget == self.ui.treeWidgetYourIdentities and - self.getCurrentAccount(treeWidget) not in (fromAddress, None, False) - ): + if treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) not in (fromAddress, None, False): continue - elif ( - treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and - self.getCurrentAccount(treeWidget) != toAddress - ): + elif treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress: continue - elif not helper_search.check_match( - toAddress, - fromAddress, - subject, - message, - self.getCurrentSearchOption(tab), - self.getCurrentSearchLine(tab), - ): + elif not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)): continue - + self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time()) self.getAccountTextedit(acct).setPlainText(unicode(message, 'utf-8', 'replace')) sent.setCurrentCell(0, 0) def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message): - """TBC""" - if toAddress == str_broadcast_subscribers: acct = accountClass(fromAddress) else: @@ -2543,54 +2260,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth inbox = self.getAccountMessagelist(acct) ret = None tab = -1 - for treeWidget in [ - self.ui.treeWidgetYourIdentities, - self.ui.treeWidgetSubscriptions, - self.ui.treeWidgetChans, - ]: + for treeWidget in [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans]: tab += 1 if tab == 1: tab = 2 tableWidget = self.widgetConvert(treeWidget) - if not helper_search.check_match( - toAddress, - fromAddress, - subject, - message, - self.getCurrentSearchOption(tab), - self.getCurrentSearchLine(tab), - ): + if not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)): continue - if ( - tableWidget == inbox and - self.getCurrentAccount(treeWidget) == acct.address and - self.getCurrentFolder(treeWidget) in ["inbox", None] - ): - ret = self.addMessageListItemInbox( - inbox, - "inbox", - inventoryHash, - toAddress, - fromAddress, - subject, - time.time(), - 0, - ) - elif ( - treeWidget == self.ui.treeWidgetYourIdentities and - self.getCurrentAccount(treeWidget) is None and - self.getCurrentFolder(treeWidget) in ["inbox", "new", None] - ): - ret = self.addMessageListItemInbox( - tableWidget, - "inbox", - inventoryHash, - toAddress, - fromAddress, - subject, - time.time(), - 0, - ) + if tableWidget == inbox and self.getCurrentAccount(treeWidget) == acct.address and self.getCurrentFolder(treeWidget) in ["inbox", None]: + ret = self.addMessageListItemInbox(inbox, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) + elif treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) is None and self.getCurrentFolder(treeWidget) in ["inbox", "new", None]: + ret = self.addMessageListItemInbox(tableWidget, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) if ret is None: acct.parseMessage(toAddress, fromAddress, subject, "") else: @@ -2604,26 +2284,18 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth unicode(acct.fromLabel, 'utf-8')), sound.SOUND_UNKNOWN ) - # pylint: disable=undefined-loop-variable - if ( - self.getCurrentAccount() is not None and ( - self.getCurrentFolder(treeWidget) not in ("inbox", None) or - self.getCurrentAccount(treeWidget) != acct.address - ) - ): + if self.getCurrentAccount() is not None and ((self.getCurrentFolder(treeWidget) != "inbox" and self.getCurrentFolder(treeWidget) is not None) or self.getCurrentAccount(treeWidget) != acct.address): # Ubuntu should notify of new message irespective of # whether it's in current message list or not self.indicatorUpdate(True, to_label=acct.toLabel) # cannot find item to pass here ): - if hasattr(acct, "feedback") and acct.feedback != GatewayAccount.ALL_OK: + if hasattr(acct, "feedback") \ + and acct.feedback != GatewayAccount.ALL_OK: if acct.feedback == GatewayAccount.REGISTRATION_DENIED: dialogs.EmailGatewayDialog( self, BMConfigParser(), acct).exec_() - # pylint: enable=undefined-loop-variable def click_pushButtonAddAddressBook(self, dialog=None): - """TBC""" - if not dialog: dialog = dialogs.AddAddressDialog(self) dialog.exec_() @@ -2647,8 +2319,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.addEntryToAddressBook(address, label) def addEntryToAddressBook(self, address, label): - """TBC""" - if shared.isAddressInMyAddressBook(address): return sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', label, address) @@ -2657,8 +2327,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.rerenderAddressBook() def addSubscription(self, address, label): - """TBC""" - # This should be handled outside of this function, for error displaying # and such, but it must also be checked here. if shared.isAddressInMySubscriptionsList(address): @@ -2674,8 +2342,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.rerenderTabTreeSubscriptions() def click_pushButtonAddSubscription(self): - """TBC""" - dialog = dialogs.NewSubscriptionDialog(self) dialog.exec_() try: @@ -2706,28 +2372,18 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth )) def click_pushButtonStatusIcon(self): - """TBC""" - dialogs.IconGlossaryDialog(self, config=BMConfigParser()).exec_() def click_actionHelp(self): - """TBC""" - dialogs.HelpDialog(self).exec_() def click_actionSupport(self): - """TBC""" - support.createSupportMessage(self) def click_actionAbout(self): - """TBC""" - dialogs.AboutDialog(self).exec_() def click_actionSettings(self): - """TBC""" - self.settingsDialogInstance = settingsDialog(self) if self._firstrun: self.settingsDialogInstance.ui.tabWidgetSettings.setCurrentIndex(1) @@ -2753,51 +2409,32 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.settingsDialogInstance.ui.checkBoxUseIdenticons.isChecked())) BMConfigParser().set('bitmessagesettings', 'replybelow', str( self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked())) - - lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData( - self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString()) + + lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData(self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString()) BMConfigParser().set('bitmessagesettings', 'userlocale', lang) change_translation(l10n.getTranslationLanguage()) - - if int(BMConfigParser().get('bitmessagesettings', 'port')) != int( - self.settingsDialogInstance.ui.lineEditTCPPort.text()): + + if int(BMConfigParser().get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()): if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'): QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( "MainWindow", "You must restart Bitmessage for the port number change to take effect.")) BMConfigParser().set('bitmessagesettings', 'port', str( self.settingsDialogInstance.ui.lineEditTCPPort.text())) - if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean( - 'bitmessagesettings', 'upnp' - ): - - BMConfigParser().set( - 'bitmessagesettings', 'upnp', - str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked())) + if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'): + BMConfigParser().set('bitmessagesettings', 'upnp', str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked())) if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked(): + import upnp upnpThread = upnp.uPnPThread() upnpThread.start() - - if ( - BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and - self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS' - ): + #print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText()', self.settingsDialogInstance.ui.comboBoxProxyType.currentText() + #print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText())[0:5]', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] + if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS': if shared.statusIconColor != 'red': - QtGui.QMessageBox.about( - self, - _translate( - "MainWindow", - "Restart"), - _translate( - "MainWindow", - ("Bitmessage will use your proxy from now on but you may want to manually restart " - "Bitmessage now to close existing connections (if any)."))) - - if ( - BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and - self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS' - ): + QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( + "MainWindow", "Bitmessage will use your proxy from now on but you may want to manually restart Bitmessage now to close existing connections (if any).")) + if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS': self.statusbar.clearMessage() - state.resetNetworkProtocolAvailability() # just in case we changed something in the network connectivity + state.resetNetworkProtocolAvailability() # just in case we changed something in the network connectivity if self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS': BMConfigParser().set('bitmessagesettings', 'socksproxytype', str( self.settingsDialogInstance.ui.comboBoxProxyType.currentText())) @@ -2826,13 +2463,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth "MainWindow", "Your maximum download and upload rate must be numbers. Ignoring what you typed.")) else: set_rates(BMConfigParser().safeGetInt("bitmessagesettings", "maxdownloadrate"), - BMConfigParser().safeGetInt("bitmessagesettings", "maxuploadrate")) + BMConfigParser().safeGetInt("bitmessagesettings", "maxuploadrate")) BMConfigParser().set('bitmessagesettings', 'maxoutboundconnections', str( int(float(self.settingsDialogInstance.ui.lineEditMaxOutboundConnections.text())))) BMConfigParser().set('bitmessagesettings', 'namecoinrpctype', - self.settingsDialogInstance.getNamecoinType()) + self.settingsDialogInstance.getNamecoinType()) BMConfigParser().set('bitmessagesettings', 'namecoinrpchost', str( self.settingsDialogInstance.ui.lineEditNamecoinHost.text())) BMConfigParser().set('bitmessagesettings', 'namecoinrpcport', str( @@ -2841,79 +2478,46 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.settingsDialogInstance.ui.lineEditNamecoinUser.text())) BMConfigParser().set('bitmessagesettings', 'namecoinrpcpassword', str( self.settingsDialogInstance.ui.lineEditNamecoinPassword.text())) - + # Demanded difficulty tab if float(self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) >= 1: BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float( - self.settingsDialogInstance.ui.lineEditTotalDifficulty.text() - ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) + self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) if float(self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) >= 1: BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float( - self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text() - ) * defaults.networkDefaultPayloadLengthExtraBytes))) + self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes))) - if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8( - ) != BMConfigParser().safeGet("bitmessagesettings", "opencl"): - BMConfigParser().set( - 'bitmessagesettings', 'opencl', - str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText())) + if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != BMConfigParser().safeGet("bitmessagesettings", "opencl"): + BMConfigParser().set('bitmessagesettings', 'opencl', str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText())) queues.workerQueue.put(('resetPoW', '')) acceptableDifficultyChanged = False - - if ( - float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or - float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0 - ): - if BMConfigParser().get( - 'bitmessagesettings', - 'maxacceptablenoncetrialsperbyte', - ) != str( - int( - float( - self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text() - ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte - ) - ): + + if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0: + if BMConfigParser().get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float( + self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)): # the user changed the max acceptable total difficulty acceptableDifficultyChanged = True BMConfigParser().set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float( - self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text() - ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) - - if ( - float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 or - float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0 - ): - if BMConfigParser().get( - 'bitmessagesettings', - 'maxacceptablepayloadlengthextrabytes', - ) != str( - int( - float( - self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text() - ) * defaults.networkDefaultPayloadLengthExtraBytes - ) - ): + self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) + if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0: + if BMConfigParser().get('bitmessagesettings','maxacceptablepayloadlengthextrabytes') != str(int(float( + self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes)): # the user changed the max acceptable small message difficulty acceptableDifficultyChanged = True BMConfigParser().set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float( - self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text() - ) * defaults.networkDefaultPayloadLengthExtraBytes))) + self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes))) if acceptableDifficultyChanged: - # It might now be possible to send msgs which were previously marked as toodifficult. + # It might now be possible to send msgs which were previously marked as toodifficult. # Let us change them to 'msgqueued'. The singleWorker will try to send them and will again # mark them as toodifficult if the receiver's required difficulty is still higher than # we are willing to do. sqlExecute('''UPDATE sent SET status='msgqueued' WHERE status='toodifficult' ''') queues.workerQueue.put(('sendmessage', '')) - - # start:UI setting to stop trying to send messages after X days/months + + #start:UI setting to stop trying to send messages after X days/months # I'm open to changing this UI to something else if someone has a better idea. - if ( - self.settingsDialogInstance.ui.lineEditDays.text() == '' and - self.settingsDialogInstance.ui.lineEditMonths.text() == '' - ): # We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank + if ((self.settingsDialogInstance.ui.lineEditDays.text()=='') and (self.settingsDialogInstance.ui.lineEditMonths.text()=='')):#We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '') shared.maximumLengthOfTimeToBotherResendingMessages = float('inf') @@ -2932,39 +2536,24 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth if lineEditMonthsIsValidFloat and not lineEditDaysIsValidFloat: self.settingsDialogInstance.ui.lineEditDays.setText("0") if lineEditDaysIsValidFloat or lineEditMonthsIsValidFloat: - if ( - float(self.settingsDialogInstance.ui.lineEditDays.text()) >= 0 and - float(self.settingsDialogInstance.ui.lineEditMonths.text()) >= 0 - ): - shared.maximumLengthOfTimeToBotherResendingMessages = sum( - float(str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60, - float(str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 * 365) / 12, - ) - # If the time period is less than 5 hours, we give zero values to all - # fields. No message will be sent again. - if shared.maximumLengthOfTimeToBotherResendingMessages < 432000: - QtGui.QMessageBox.about( - self, - _translate( - "MainWindow", - "Will not resend ever"), - _translate( - "MainWindow", - ("Note that the time limit you entered is less than the amount of time Bitmessage " - "waits for the first resend attempt therefore your messages will never be resent."))) + if (float(self.settingsDialogInstance.ui.lineEditDays.text()) >=0 and float(self.settingsDialogInstance.ui.lineEditMonths.text()) >=0): + shared.maximumLengthOfTimeToBotherResendingMessages = (float(str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60) + (float(str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 *365)/12) + if shared.maximumLengthOfTimeToBotherResendingMessages < 432000: # If the time period is less than 5 hours, we give zero values to all fields. No message will be sent again. + QtGui.QMessageBox.about(self, _translate("MainWindow", "Will not resend ever"), _translate( + "MainWindow", "Note that the time limit you entered is less than the amount of time Bitmessage waits for the first resend attempt therefore your messages will never be resent.")) BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '0') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '0') shared.maximumLengthOfTimeToBotherResendingMessages = 0 else: BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', str(float( - self.settingsDialogInstance.ui.lineEditDays.text()))) + self.settingsDialogInstance.ui.lineEditDays.text()))) BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', str(float( - self.settingsDialogInstance.ui.lineEditMonths.text()))) + self.settingsDialogInstance.ui.lineEditMonths.text()))) BMConfigParser().save() if 'win32' in sys.platform or 'win64' in sys.platform: - # Auto-startup for Windows + # Auto-startup for Windows RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat) if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'): @@ -2978,56 +2567,46 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # startup for linux pass - # If we are NOT using portable mode now but the user selected that we should... - if state.appdata != paths.lookupExeFolder(): - if self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): + if state.appdata != paths.lookupExeFolder() and self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): # If we are NOT using portable mode now but the user selected that we should... + # Write the keys.dat file to disk in the new location + sqlStoredProcedure('movemessagstoprog') + with open(paths.lookupExeFolder() + 'keys.dat', 'wb') as configfile: + BMConfigParser().write(configfile) + # Write the knownnodes.dat file to disk in the new location + knownnodes.saveKnownNodes(paths.lookupExeFolder()) + os.remove(state.appdata + 'keys.dat') + os.remove(state.appdata + 'knownnodes.dat') + previousAppdataLocation = state.appdata + state.appdata = paths.lookupExeFolder() + debug.restartLoggingInUpdatedAppdataLocation() + try: + os.remove(previousAppdataLocation + 'debug.log') + os.remove(previousAppdataLocation + 'debug.log.1') + except: + pass - # Write the keys.dat file to disk in the new location - sqlStoredProcedure('movemessagstoprog') - with open(paths.lookupExeFolder() + 'keys.dat', 'wb') as configfile: - BMConfigParser().write(configfile) - # Write the knownnodes.dat file to disk in the new location - knownnodes.saveKnownNodes(paths.lookupExeFolder()) - os.remove(state.appdata + 'keys.dat') - os.remove(state.appdata + 'knownnodes.dat') - previousAppdataLocation = state.appdata - state.appdata = paths.lookupExeFolder() - debug.restartLoggingInUpdatedAppdataLocation() - try: - os.remove(previousAppdataLocation + 'debug.log') - os.remove(previousAppdataLocation + 'debug.log.1') - except: - pass - - # If we ARE using portable mode now but the user selected that we shouldn't... - if state.appdata == paths.lookupExeFolder(): - if not self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): - - state.appdata = paths.lookupAppdataFolder() - if not os.path.exists(state.appdata): - os.makedirs(state.appdata) - sqlStoredProcedure('movemessagstoappdata') - # Write the keys.dat file to disk in the new location - BMConfigParser().save() - # Write the knownnodes.dat file to disk in the new location - knownnodes.saveKnownNodes(state.appdata) - os.remove(paths.lookupExeFolder() + 'keys.dat') - os.remove(paths.lookupExeFolder() + 'knownnodes.dat') - debug.restartLoggingInUpdatedAppdataLocation() - try: - os.remove(paths.lookupExeFolder() + 'debug.log') - os.remove(paths.lookupExeFolder() + 'debug.log.1') - except: - pass + if state.appdata == paths.lookupExeFolder() and not self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): # If we ARE using portable mode now but the user selected that we shouldn't... + state.appdata = paths.lookupAppdataFolder() + if not os.path.exists(state.appdata): + os.makedirs(state.appdata) + sqlStoredProcedure('movemessagstoappdata') + # Write the keys.dat file to disk in the new location + BMConfigParser().save() + # Write the knownnodes.dat file to disk in the new location + knownnodes.saveKnownNodes(state.appdata) + os.remove(paths.lookupExeFolder() + 'keys.dat') + os.remove(paths.lookupExeFolder() + 'knownnodes.dat') + debug.restartLoggingInUpdatedAppdataLocation() + try: + os.remove(paths.lookupExeFolder() + 'debug.log') + os.remove(paths.lookupExeFolder() + 'debug.log.1') + except: + pass def on_action_SpecialAddressBehaviorDialog(self): - """TBC""" - dialogs.SpecialAddressBehaviorDialog(self, BMConfigParser()) def on_action_EmailGatewayDialog(self): - """TBC""" - dialog = dialogs.EmailGatewayDialog(self, config=BMConfigParser()) # For Modal dialogs dialog.exec_() @@ -3058,8 +2637,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.ui.textEditMessage.setFocus() def on_action_MarkAllRead(self): - """TBC""" - if QtGui.QMessageBox.question( self, "Marking all messages as read?", _translate( @@ -3096,16 +2673,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth if markread > 0: self.propagateUnreadCount() - # addressAtCurrentRow, self.getCurrentFolder(), None, 0) + # addressAtCurrentRow, self.getCurrentFolder(), None, 0) def click_NewAddressDialog(self): - """TBC""" - dialogs.NewAddressDialog(self) def network_switch(self): - """TBC""" - dontconnect_option = not BMConfigParser().safeGetBoolean( 'bitmessagesettings', 'dontconnect') BMConfigParser().set( @@ -3117,8 +2690,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth dontconnect_option or self.namecoin.test()[0] == 'failed' ) + # Quit selected from menu or application indicator def quit(self): - """Quit selected from menu or application indicator""" + '''quit_msg = "Are you sure you want to exit Bitmessage?" + reply = QtGui.QMessageBox.question(self, 'Message', + quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) + + if reply is QtGui.QMessageBox.No: + return + ''' if self.quitAccepted: return @@ -3133,50 +2713,20 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth # C PoW currently doesn't support interrupting and OpenCL is untested if getPowType() == "python" and (powQueueSize() > 0 or pendingUpload() > 0): - reply = QtGui.QMessageBox.question( - self, - _translate( - "MainWindow", - "Proof of work pending"), - _translate( - "MainWindow", - "%n object(s) pending proof of work", - None, - QtCore.QCoreApplication.CodecForTr, - powQueueSize()) + - ", " + - _translate( - "MainWindow", - "%n object(s) waiting to be distributed", - None, - QtCore.QCoreApplication.CodecForTr, - pendingUpload()) + - "\n\n" + - _translate( - "MainWindow", - "Wait until these tasks finish?"), - QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel, - QtGui.QMessageBox.Cancel) + reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Proof of work pending"), + _translate("MainWindow", "%n object(s) pending proof of work", None, QtCore.QCoreApplication.CodecForTr, powQueueSize()) + ", " + + _translate("MainWindow", "%n object(s) waiting to be distributed", None, QtCore.QCoreApplication.CodecForTr, pendingUpload()) + "\n\n" + + _translate("MainWindow", "Wait until these tasks finish?"), + QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.No: waitForPow = False elif reply == QtGui.QMessageBox.Cancel: return if pendingDownload() > 0: - reply = QtGui.QMessageBox.question( - self, - _translate( - "MainWindow", - "Synchronisation pending"), - _translate( - "MainWindow", - ("Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit " - "now, it may cause delivery delays. Wait until the synchronisation finishes?"), - None, - QtCore.QCoreApplication.CodecForTr, - pendingDownload()), - QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel, - QtGui.QMessageBox.Cancel) + reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Synchronisation pending"), + _translate("MainWindow", "Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit now, it may cause delivery delays. Wait until the synchronisation finishes?", None, QtCore.QCoreApplication.CodecForTr, pendingDownload()), + QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: waitForSync = True elif reply == QtGui.QMessageBox.Cancel: @@ -3184,17 +2734,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth if shared.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean( 'bitmessagesettings', 'dontconnect'): - reply = QtGui.QMessageBox.question( - self, - _translate( - "MainWindow", - "Not connected"), - _translate( - "MainWindow", - ("Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. " - "Wait until connected and the synchronisation finishes?")), - QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel, - QtGui.QMessageBox.Cancel) + reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Not connected"), + _translate("MainWindow", "Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. Wait until connected and the synchronisation finishes?"), + QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: waitForConnection = True waitForSync = True @@ -3215,9 +2757,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth QtCore.QEventLoop.AllEvents, 1000 ) - # this probably will not work correctly, because there is a delay between - # the status icon turning red and inventory exchange, but it's better than - # nothing. + # this probably will not work correctly, because there is a delay between the status icon turning red and inventory exchange, but it's better than nothing. if waitForSync: self.updateStatusBar(_translate( "MainWindow", "Waiting for finishing synchronisation...")) @@ -3237,11 +2777,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth if curWorkerQueue > maxWorkerQueue: maxWorkerQueue = curWorkerQueue if curWorkerQueue > 0: - self.updateStatusBar( - _translate( - "MainWindow", - "Waiting for PoW to finish... %1%", - ).arg(50 * (maxWorkerQueue - curWorkerQueue) / maxWorkerQueue) + self.updateStatusBar(_translate( + "MainWindow", "Waiting for PoW to finish... %1%" + ).arg(50 * (maxWorkerQueue - curWorkerQueue) + / maxWorkerQueue) ) time.sleep(0.5) QtCore.QCoreApplication.processEvents( @@ -3265,13 +2804,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.updateStatusBar(_translate( "MainWindow", "Waiting for objects to be sent... %1%").arg(50)) maxPendingUpload = max(1, pendingUpload()) - + while pendingUpload() > 1: - self.updateStatusBar( - _translate( - "MainWindow", - "Waiting for objects to be sent... %1%" - ).arg(int(50 + 20 * (pendingUpload() / maxPendingUpload))) + self.updateStatusBar(_translate( + "MainWindow", + "Waiting for objects to be sent... %1%" + ).arg(int(50 + 20 * (pendingUpload()/maxPendingUpload))) ) time.sleep(0.5) QtCore.QCoreApplication.processEvents( @@ -3314,11 +2852,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth shared.thisapp.cleanup() logger.info("Shutdown complete") super(MyForm, myapp).close() - sys.exit(0) + # return + os._exit(0) + # window close event def closeEvent(self, event): - """window close event""" - self.appIndicatorHide() trayonclose = False @@ -3339,8 +2877,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth self.quit() def on_action_InboxMessageForceHtml(self): - """TBC""" - msgid = self.getCurrentMessageId() textEdit = self.getCurrentMessageTextedit() if not msgid: @@ -3359,54 +2895,60 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth lines[i]) elif lines[i] == '------------------------------------------------------': lines[i] = '
Bitmessage can utilize a different Bitcoin-based program called Namecoin to make addresses human-friendly. For example, instead of having to tell your friend your long Bitmessage address, you can simply tell him to send a message to test.
(Getting your own Bitmessage address into Namecoin is still rather difficult).
Bitmessage can use either namecoind directly or a running nmcontrol instance.
", None)) + self.label_16.setText(_translate( + "settingsDialog", + "Bitmessage can utilize a different Bitcoin-based program called Namecoin to make" + " addresses human-friendly. For example, instead of having to tell your friend your long Bitmessage" + " address, you can simply tell him to send a message to test." + "
(Getting your own Bitmessage address into Namecoin is still rather difficult).
" + "Bitmessage can use either namecoind directly or a running nmcontrol instance.
", + None)) self.label_17.setText(_translate("settingsDialog", "Host:", None)) self.label_18.setText(_translate("settingsDialog", "Port:", None)) self.labelNamecoinUser.setText(_translate("settingsDialog", "Username:", None)) @@ -505,12 +605,26 @@ class Ui_settingsDialog(object): self.label_21.setText(_translate("settingsDialog", "Connect to:", None)) self.radioButtonNamecoinNamecoind.setText(_translate("settingsDialog", "Namecoind", None)) self.radioButtonNamecoinNmcontrol.setText(_translate("settingsDialog", "NMControl", None)) - self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabNamecoin), _translate("settingsDialog", "Namecoin integration", None)) - self.label_7.setText(_translate("settingsDialog", "By default, if you send a message to someone and he is offline for more than two days, Bitmessage will send the message again after an additional two days. This will be continued with exponential backoff forever; messages will be resent after 5, 10, 20 days ect. until the receiver acknowledges them. Here you may change that behavior by having Bitmessage give up after a certain number of days or months.
Leave these input fields blank for the default behavior.
", None)) + self.tabWidgetSettings.setTabText( + self.tabWidgetSettings.indexOf( + self.tabNamecoin), + _translate( + "settingsDialog", "Namecoin integration", None)) + self.label_7.setText(_translate( + "settingsDialog", + "By default, if you send a message to someone and he is offline for more than two" + " days, Bitmessage will send the message again after an additional two days. This will be continued with" + " exponential backoff forever; messages will be resent after 5, 10, 20 days ect. until the receiver" + " acknowledges them. Here you may change that behavior by having Bitmessage give up after a certain" + " number of days or months.
Leave these input fields blank for the default behavior." + "
", + None)) self.label_19.setText(_translate("settingsDialog", "Give up after", None)) self.label_20.setText(_translate("settingsDialog", "and", None)) self.label_22.setText(_translate("settingsDialog", "days", None)) self.label_23.setText(_translate("settingsDialog", "months.", None)) - self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabResendsExpire), _translate("settingsDialog", "Resends Expire", None)) - -import bitmessage_icons_rc + self.tabWidgetSettings.setTabText( + self.tabWidgetSettings.indexOf( + self.tabResendsExpire), + _translate( + "settingsDialog", "Resends Expire", None)) diff --git a/src/debug.py b/src/debug.py index e5501967..746f0fcd 100644 --- a/src/debug.py +++ b/src/debug.py @@ -4,23 +4,26 @@ Logging and debuging facility ============================= Levels: - DEBUG Detailed information, typically of interest only when - diagnosing problems. - INFO Confirmation that things are working as expected. - WARNING An indication that something unexpected happened, or indicative - of some problem in the near future (e.g. ‘disk space low’). - The software is still working as expected. - ERROR Due to a more serious problem, the software has not been able - to perform some function. - CRITICAL A serious error, indicating that the program itself may be - unable to continue running. + + DEBUG + Detailed information, typically of interest only when diagnosing problems. + INFO + Confirmation that things are working as expected. + WARNING + An indication that something unexpected happened, or indicative of some problem in the + near future (e.g. ‘disk space low’). The software is still working as expected. + ERROR + Due to a more serious problem, the software has not been able to perform some function. + CRITICAL + A serious error, indicating that the program itself may be unable to continue running. There are three loggers: `console_only`, `file_only` and `both`. -Use: `from debug import logger` to import this facility into whatever module - you wish to log messages from. Logging is thread-safe so you don't have - to worry about locks, just import and log. +Use: `from debug import logger` to import this facility into whatever module you wish to log messages from. + Logging is thread-safe so you don't have to worry about locks, just import and log. + """ + import logging import logging.config import os @@ -56,9 +59,8 @@ def configureLogging(): ' logging config\n%s' % (os.path.join(state.appdata, 'logging.dat'), sys.exc_info())) else: - # no need to confuse the user if the logger config - # is missing entirely - print('Using default logger configuration') + # no need to confuse the user if the logger config is missing entirely + print "Using default logger configuration" sys.excepthook = log_uncaught_exceptions @@ -111,17 +113,20 @@ def configureLogging(): return True -# TODO (xj9): Get from a config file. -# logger = logging.getLogger('console_only') -if configureLogging(): - if '-c' in sys.argv: - logger = logging.getLogger('file_only') +if __name__ == "__main__": + + # TODO (xj9): Get from a config file. + #logger = logging.getLogger('console_only') + if configureLogging(): + if '-c' in sys.argv: + logger = logging.getLogger('file_only') + else: + logger = logging.getLogger('both') else: - logger = logging.getLogger('both') + logger = logging.getLogger('default') else: logger = logging.getLogger('default') - def restartLoggingInUpdatedAppdataLocation(): global logger for i in list(logger.handlers): @@ -135,3 +140,4 @@ def restartLoggingInUpdatedAppdataLocation(): logger = logging.getLogger('both') else: logger = logging.getLogger('default') + diff --git a/src/depends.py b/src/depends.py index 4c79322a..06150642 100755 --- a/src/depends.py +++ b/src/depends.py @@ -1,52 +1,196 @@ -#! python +""" +Utility functions to check the availability of dependencies +and suggest how it may be installed +""" import sys -import os -import pyelliptic.openssl # Only really old versions of Python don't have sys.hexversion. We don't # support them. The logging module was introduced in Python 2.3 if not hasattr(sys, 'hexversion') or sys.hexversion < 0x20300F0: - sys.stdout.write('Python version: ' + sys.version) - sys.stdout.write('PyBitmessage requires Python 2.7.3 or greater (but not Python 3)') - sys.exit() + sys.exit( + 'Python version: %s\n' + 'PyBitmessage requires Python 2.7.4 or greater (but not Python 3)' + % sys.version + ) + +import logging +import os +from importlib import import_module # We can now use logging so set up a simple configuration -import logging formatter = logging.Formatter( '%(levelname)s: %(message)s' ) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) -logger = logging.getLogger(__name__) +logger = logging.getLogger('both') logger.addHandler(handler) logger.setLevel(logging.ERROR) +OS_RELEASE = { + "fedora": "Fedora", + "opensuse": "openSUSE", + "ubuntu": "Ubuntu", + "gentoo": "Gentoo", + "calculate": "Gentoo" +} + +PACKAGE_MANAGER = { + "OpenBSD": "pkg_add", + "FreeBSD": "pkg install", + "Debian": "apt-get install", + "Ubuntu": "apt-get install", + "Ubuntu 12": "apt-get install", + "openSUSE": "zypper install", + "Fedora": "dnf install", + "Guix": "guix package -i", + "Gentoo": "emerge" +} + +PACKAGES = { + "PyQt4": { + "OpenBSD": "py-qt4", + "FreeBSD": "py27-qt4", + "Debian": "python-qt4", + "Ubuntu": "python-qt4", + "Ubuntu 12": "python-qt4", + "openSUSE": "python-qt", + "Fedora": "PyQt4", + "Guix": "python2-pyqt@4.11.4", + "Gentoo": "dev-python/PyQt4", + "optional": True, + "description": + "You only need PyQt if you want to use the GUI." + " When only running as a daemon, this can be skipped.\n" + "However, you would have to install it manually" + " because setuptools does not support PyQt." + }, + "msgpack": { + "OpenBSD": "py-msgpack", + "FreeBSD": "py27-msgpack-python", + "Debian": "python-msgpack", + "Ubuntu": "python-msgpack", + "Ubuntu 12": "msgpack-python", + "openSUSE": "python-msgpack-python", + "Fedora": "python2-msgpack", + "Guix": "python2-msgpack", + "Gentoo": "dev-python/msgpack", + "optional": True, + "description": + "python-msgpack is recommended for improved performance of" + " message encoding/decoding" + }, + "pyopencl": { + "FreeBSD": "py27-pyopencl", + "Debian": "python-pyopencl", + "Ubuntu": "python-pyopencl", + "Ubuntu 12": "python-pyopencl", + "Fedora": "python2-pyopencl", + "openSUSE": "", + "OpenBSD": "", + "Guix": "", + "Gentoo": "dev-python/pyopencl", + "optional": True, + "description": + "If you install pyopencl, you will be able to use" + " GPU acceleration for proof of work.\n" + "You also need a compatible GPU and drivers." + }, + "setuptools": { + "OpenBSD": "py-setuptools", + "FreeBSD": "py27-setuptools", + "Debian": "python-setuptools", + "Ubuntu": "python-setuptools", + "Ubuntu 12": "python-setuptools", + "Fedora": "python2-setuptools", + "openSUSE": "python-setuptools", + "Guix": "python2-setuptools", + "Gentoo": "dev-python/setuptools", + "optional": False, + } +} + + +def detectOS(): + if detectOS.result is not None: + return detectOS.result + if sys.platform.startswith('openbsd'): + detectOS.result = "OpenBSD" + elif sys.platform.startswith('freebsd'): + detectOS.result = "FreeBSD" + elif sys.platform.startswith('win'): + detectOS.result = "Windows" + elif os.path.isfile("/etc/os-release"): + detectOSRelease() + elif os.path.isfile("/etc/config.scm"): + detectOS.result = "Guix" + return detectOS.result + + +detectOS.result = None + + +def detectOSRelease(): + with open("/etc/os-release", 'r') as osRelease: + version = None + for line in osRelease: + if line.startswith("NAME="): + detectOS.result = OS_RELEASE.get( + line.split("=")[-1].strip().lower()) + elif line.startswith("VERSION_ID="): + try: + version = float(line.split("=")[1].replace("\"", "")) + except ValueError: + pass + if detectOS.result == "Ubuntu" and version < 14: + detectOS.result = "Ubuntu 12" + + +def try_import(module, log_extra=False): + try: + return import_module(module) + except ImportError: + module = module.split('.')[0] + logger.error('The %s module is not available.', module) + if log_extra: + logger.error(log_extra) + dist = detectOS() + logger.error( + 'On %s, try running "%s %s" as root.', + dist, PACKAGE_MANAGER[dist], PACKAGES[module][dist]) + return False + + # We need to check hashlib for RIPEMD-160, as it won't be available # if OpenSSL is not linked against or the linked OpenSSL has RIPEMD # disabled. - - def check_hashlib(): """Do hashlib check. The hashlib module check with version as if it included or not - in The Python Standard library , its a module containing an + in The Python Standard library, it's a module containing an interface to the most popular hashing algorithms. hashlib implements some of the algorithms, however if OpenSSL installed, hashlib is able to use this algorithms as well. """ if sys.hexversion < 0x020500F0: - logger.error('The hashlib module is not included in this version of Python.') + logger.error( + 'The hashlib module is not included in this version of Python.') return False import hashlib if '_hashlib' not in hashlib.__dict__: - logger.error('The RIPEMD-160 hash algorithm is not available. The hashlib module is not linked against OpenSSL.') + logger.error( + 'The RIPEMD-160 hash algorithm is not available.' + ' The hashlib module is not linked against OpenSSL.') return False try: hashlib.new('ripemd160') except ValueError: - logger.error('The RIPEMD-160 hash algorithm is not available. The hashlib module utilizes an OpenSSL library with RIPEMD disabled.') + logger.error( + 'The RIPEMD-160 hash algorithm is not available.' + ' The hashlib module utilizes an OpenSSL library with' + ' RIPEMD disabled.') return False return True @@ -58,35 +202,48 @@ def check_sqlite(): support in python version for specifieed platform. """ if sys.hexversion < 0x020500F0: - logger.error('The sqlite3 module is not included in this version of Python.') + logger.error( + 'The sqlite3 module is not included in this version of Python.') if sys.platform.startswith('freebsd'): - logger.error('On FreeBSD, try running "pkg install py27-sqlite3" as root.') - return False - try: - import sqlite3 - except ImportError: - logger.error('The sqlite3 module is not available') + logger.error( + 'On FreeBSD, try running "pkg install py27-sqlite3" as root.') return False - logger.info('sqlite3 Module Version: ' + sqlite3.version) - logger.info('SQLite Library Version: ' + sqlite3.sqlite_version) - #sqlite_version_number formula: https://sqlite.org/c3ref/c_source_id.html - sqlite_version_number = sqlite3.sqlite_version_info[0] * 1000000 + sqlite3.sqlite_version_info[1] * 1000 + sqlite3.sqlite_version_info[2] + sqlite3 = try_import('sqlite3') + if not sqlite3: + return False + + logger.info('sqlite3 Module Version: %s', sqlite3.version) + logger.info('SQLite Library Version: %s', sqlite3.sqlite_version) + # sqlite_version_number formula: https://sqlite.org/c3ref/c_source_id.html + sqlite_version_number = ( + sqlite3.sqlite_version_info[0] * 1000000 + + sqlite3.sqlite_version_info[1] * 1000 + + sqlite3.sqlite_version_info[2] + ) conn = None try: try: conn = sqlite3.connect(':memory:') if sqlite_version_number >= 3006018: - sqlite_source_id = conn.execute('SELECT sqlite_source_id();').fetchone()[0] - logger.info('SQLite Library Source ID: ' + sqlite_source_id) + sqlite_source_id = conn.execute( + 'SELECT sqlite_source_id();' + ).fetchone()[0] + logger.info('SQLite Library Source ID: %s', sqlite_source_id) if sqlite_version_number >= 3006023: - compile_options = ', '.join(map(lambda row: row[0], conn.execute('PRAGMA compile_options;'))) - logger.info('SQLite Library Compile Options: ' + compile_options) - #There is no specific version requirement as yet, so we just use the - #first version that was included with Python. + compile_options = ', '.join(map( + lambda row: row[0], + conn.execute('PRAGMA compile_options;') + )) + logger.info( + 'SQLite Library Compile Options: %s', compile_options) + # There is no specific version requirement as yet, so we just + # use the first version that was included with Python. if sqlite_version_number < 3000008: - logger.error('This version of SQLite is too old. PyBitmessage requires SQLite 3.0.8 or later') + logger.error( + 'This version of SQLite is too old.' + ' PyBitmessage requires SQLite 3.0.8 or later') return False return True except sqlite3.Error: @@ -96,19 +253,20 @@ def check_sqlite(): if conn: conn.close() + def check_openssl(): """Do openssl dependency check. Here we are checking for openssl with its all dependent libraries and version checking. """ - try: - import ctypes - except ImportError: - logger.error('Unable to check OpenSSL. The ctypes module is not available.') + + ctypes = try_import('ctypes') + if not ctypes: + logger.error('Unable to check OpenSSL.') return False - #We need to emulate the way PyElliptic searches for OpenSSL. + # We need to emulate the way PyElliptic searches for OpenSSL. if sys.platform == 'win32': paths = ['libeay32.dll'] if getattr(sys, 'frozen', False): @@ -138,135 +296,128 @@ def check_openssl(): cflags_regex = re.compile(r'(?:OPENSSL_NO_)(AES|EC|ECDH|ECDSA)(?!\w)') + import pyelliptic.openssl + for path in paths: - logger.info('Checking OpenSSL at ' + path) + logger.info('Checking OpenSSL at %s', path) try: library = ctypes.CDLL(path) except OSError: continue - logger.info('OpenSSL Name: ' + library._name) - openssl_version, openssl_hexversion, openssl_cflags = pyelliptic.openssl.get_version(library) + logger.info('OpenSSL Name: %s', library._name) + try: + openssl_version, openssl_hexversion, openssl_cflags = \ + pyelliptic.openssl.get_version(library) + except AttributeError: # sphinx chokes + return True if not openssl_version: logger.error('Cannot determine version of this OpenSSL library.') return False - logger.info('OpenSSL Version: ' + openssl_version) - logger.info('OpenSSL Compile Options: ' + openssl_cflags) - #PyElliptic uses EVP_CIPHER_CTX_new and EVP_CIPHER_CTX_free which were - #introduced in 0.9.8b. + logger.info('OpenSSL Version: %s', openssl_version) + logger.info('OpenSSL Compile Options: %s', openssl_cflags) + # PyElliptic uses EVP_CIPHER_CTX_new and EVP_CIPHER_CTX_free which were + # introduced in 0.9.8b. if openssl_hexversion < 0x90802F: - logger.error('This OpenSSL library is too old. PyBitmessage requires OpenSSL 0.9.8b or later with AES, Elliptic Curves (EC), ECDH, and ECDSA enabled.') + logger.error( + 'This OpenSSL library is too old. PyBitmessage requires' + ' OpenSSL 0.9.8b or later with AES, Elliptic Curves (EC),' + ' ECDH, and ECDSA enabled.') return False matches = cflags_regex.findall(openssl_cflags) if len(matches) > 0: - logger.error('This OpenSSL library is missing the following required features: ' + ', '.join(matches) + '. PyBitmessage requires OpenSSL 0.9.8b or later with AES, Elliptic Curves (EC), ECDH, and ECDSA enabled.') + logger.error( + 'This OpenSSL library is missing the following required' + ' features: %s. PyBitmessage requires OpenSSL 0.9.8b' + ' or later with AES, Elliptic Curves (EC), ECDH,' + ' and ECDSA enabled.', ', '.join(matches)) return False return True return False -#TODO: The minimum versions of pythondialog and dialog need to be determined + +# TODO: The minimum versions of pythondialog and dialog need to be determined def check_curses(): """Do curses dependency check. - Here we are checking for curses if available or not with check + Here we are checking for curses if available or not with check as interface requires the pythondialog\ package and the dialog utility. """ if sys.hexversion < 0x20600F0: - logger.error('The curses interface requires the pythondialog package and the dialog utility.') + logger.error( + 'The curses interface requires the pythondialog package and' + ' the dialog utility.') return False + curses = try_import('curses') + if not curses: + logger.error('The curses interface can not be used.') + return False + + logger.info('curses Module Version: %s', curses.version) + + dialog = try_import('dialog') + if not dialog: + logger.error('The curses interface can not be used.') + return False + + import subprocess + try: - import curses - except ImportError: - logger.error('The curses interface can not be used. The curses module is not available.') + subprocess.check_call('which dialog') + except subprocess.CalledProcessError: + logger.error( + 'Curses requires the `dialog` command to be installed as well as' + ' the python library.') return False - logger.info('curses Module Version: ' + curses.version) - try: - import dialog - except ImportError: - logger.error('The curses interface can not be used. The pythondialog package is not available.') - return False - logger.info('pythondialog Package Version: ' + dialog.__version__) + + logger.info('pythondialog Package Version: %s', dialog.__version__) dialog_util_version = dialog.Dialog().cached_backend_version - #The pythondialog author does not like Python2 str, so we have to use - #unicode for just the version otherwise we get the repr form which includes - #the module and class names along with the actual version. - logger.info('dialog Utility Version' + unicode(dialog_util_version)) + # The pythondialog author does not like Python2 str, so we have to use + # unicode for just the version otherwise we get the repr form which + # includes the module and class names along with the actual version. + logger.info('dialog Utility Version %s', unicode(dialog_util_version)) return True + def check_pyqt(): """Do pyqt dependency check. Here we are checking for PyQt4 with its version, as for it require - PyQt 4.7 or later. + PyQt 4.8 or later. """ - try: - import PyQt4.QtCore - except ImportError: - logger.error('The PyQt4 package is not available. PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.') - if sys.platform.startswith('openbsd'): - logger.error('On OpenBSD, try running "pkg_add py-qt4" as root.') - elif sys.platform.startswith('freebsd'): - logger.error('On FreeBSD, try running "pkg install py27-qt4" as root.') - elif os.path.isfile("/etc/os-release"): - with open("/etc/os-release", 'rt') as osRelease: - for line in osRelease: - if line.startswith("NAME="): - if "fedora" in line.lower(): - logger.error('On Fedora, try running "dnf install PyQt4" as root.') - elif "opensuse" in line.lower(): - logger.error('On openSUSE, try running "zypper install python-qt" as root.') - elif "ubuntu" in line.lower(): - logger.error('On Ubuntu, try running "apt-get install python-qt4" as root.') - elif "debian" in line.lower(): - logger.error('On Debian, try running "apt-get install python-qt4" as root.') - else: - logger.error('If your package manager does not have this package, try running "pip install PyQt4".') + QtCore = try_import( + 'PyQt4.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.') + + if not QtCore: return False - logger.info('PyQt Version: ' + PyQt4.QtCore.PYQT_VERSION_STR) - logger.info('Qt Version: ' + PyQt4.QtCore.QT_VERSION_STR) + + logger.info('PyQt Version: %s', QtCore.PYQT_VERSION_STR) + logger.info('Qt Version: %s', QtCore.QT_VERSION_STR) passed = True - if PyQt4.QtCore.PYQT_VERSION < 0x40800: - logger.error('This version of PyQt is too old. PyBitmessage requries PyQt 4.8 or later.') + if QtCore.PYQT_VERSION < 0x40800: + logger.error( + 'This version of PyQt is too old. PyBitmessage requries' + ' PyQt 4.8 or later.') passed = False - if PyQt4.QtCore.QT_VERSION < 0x40700: - logger.error('This version of Qt is too old. PyBitmessage requries Qt 4.7 or later.') + if QtCore.QT_VERSION < 0x40700: + logger.error( + 'This version of Qt is too old. PyBitmessage requries' + ' Qt 4.7 or later.') passed = False return passed + def check_msgpack(): """Do sgpack module check. - simply checking if msgpack package with all its dependency + simply checking if msgpack package with all its dependency is available or not as recommended for messages coding. """ - try: - import msgpack - except ImportError: - logger.error( - 'The msgpack package is not available.' - 'It is highly recommended for messages coding.') - if sys.platform.startswith('openbsd'): - logger.error('On OpenBSD, try running "pkg_add py-msgpack" as root.') - elif sys.platform.startswith('freebsd'): - logger.error('On FreeBSD, try running "pkg install py27-msgpack-python" as root.') - elif os.path.isfile("/etc/os-release"): - with open("/etc/os-release", 'rt') as osRelease: - for line in osRelease: - if line.startswith("NAME="): - if "fedora" in line.lower(): - logger.error('On Fedora, try running "dnf install python2-msgpack" as root.') - elif "opensuse" in line.lower(): - logger.error('On openSUSE, try running "zypper install python-msgpack-python" as root.') - elif "ubuntu" in line.lower(): - logger.error('On Ubuntu, try running "apt-get install python-msgpack" as root.') - elif "debian" in line.lower(): - logger.error('On Debian, try running "apt-get install python-msgpack" as root.') - else: - logger.error('If your package manager does not have this package, try running "pip install msgpack-python".') + return try_import( + 'msgpack', 'It is highly recommended for messages coding.') is not False - return True -def check_dependencies(verbose = False, optional = False): +def check_dependencies(verbose=False, optional=False): """Do dependency check. It identifies project dependencies and checks if there are @@ -279,33 +430,36 @@ def check_dependencies(verbose = False, optional = False): has_all_dependencies = True - #Python 2.7.3 is the required minimum. Python 3+ is not supported, but it is - #still useful to provide information about our other requirements. + # Python 2.7.4 is the required minimum. + # (https://bitmessage.org/forum/index.php?topic=4081.0) + # Python 3+ is not supported, but it is still useful to provide + # information about our other requirements. logger.info('Python version: %s', sys.version) - if sys.hexversion < 0x20703F0: - logger.error('PyBitmessage requires Python 2.7.3 or greater (but not Python 3+)') + if sys.hexversion < 0x20704F0: + logger.error( + 'PyBitmessage requires Python 2.7.4 or greater' + ' (but not Python 3+)') has_all_dependencies = False if sys.hexversion >= 0x3000000: - logger.error('PyBitmessage does not support Python 3+. Python 2.7.3 or greater is required.') + logger.error( + 'PyBitmessage does not support Python 3+. Python 2.7.4' + ' or greater is required.') has_all_dependencies = False - check_functions = [check_hashlib, check_sqlite, check_openssl, check_msgpack] + check_functions = [check_hashlib, check_sqlite, check_openssl] if optional: - check_functions.extend([check_pyqt, check_curses]) + check_functions.extend([check_msgpack, check_pyqt, check_curses]) - #Unexpected exceptions are handled here + # Unexpected exceptions are handled here for check in check_functions: try: has_all_dependencies &= check() except: - logger.exception(check.__name__ + ' failed unexpectedly.') + logger.exception('%s failed unexpectedly.', check.__name__) has_all_dependencies = False - + if not has_all_dependencies: - logger.critical('PyBitmessage cannot start. One or more dependencies are unavailable.') - sys.exit() - -if __name__ == '__main__': - """Check Dependencies""" - check_dependencies(True, True) - + sys.exit( + 'PyBitmessage cannot start. One or more dependencies are' + ' unavailable.' + ) diff --git a/src/fallback/__init__.py b/src/fallback/__init__.py index e69de29b..9ac081b6 100644 --- a/src/fallback/__init__.py +++ b/src/fallback/__init__.py @@ -0,0 +1,3 @@ +""" +.. todo:: hello world +""" diff --git a/src/fallback/umsgpack/umsgpack.py b/src/fallback/umsgpack/umsgpack.py index cd7a2037..d196b7f8 100644 --- a/src/fallback/umsgpack/umsgpack.py +++ b/src/fallback/umsgpack/umsgpack.py @@ -205,7 +205,7 @@ load = None loads = None compatibility = False -""" +u""" Compatibility mode boolean. When compatibility mode is enabled, u-msgpack-python will serialize both diff --git a/src/message_data_reader.py b/src/message_data_reader.py index a0659807..de6ed6c0 100644 --- a/src/message_data_reader.py +++ b/src/message_data_reader.py @@ -1,22 +1,32 @@ -#This program can be used to print out everything in your Inbox or Sent folders and also take things out of the trash. -#Scroll down to the bottom to see the functions that you can uncomment. Save then run this file. -#The functions which only read the database file seem to function just fine even if you have Bitmessage running but you should definitly close it before running the functions that make changes (like taking items out of the trash). +# pylint: disable=too-many-locals +""" +This program can be used to print out everything in your Inbox or Sent folders and also take things out of the trash. +Scroll down to the bottom to see the functions that you can uncomment. Save then run this file. +The functions which only read the database file seem to function just +fine even if you have Bitmessage running but you should definitly close +it before running the functions that make changes (like taking items out +of the trash). +""" + +from __future__ import absolute_import import sqlite3 +from binascii import hexlify from time import strftime, localtime -import sys + import paths import queues -import state -from binascii import hexlify + appdata = paths.lookupAppdataFolder() -conn = sqlite3.connect( appdata + 'messages.dat' ) +conn = sqlite3.connect(appdata + 'messages.dat') conn.text_factory = str cur = conn.cursor() + def readInbox(): + """Print each row from inbox table""" print 'Printing everything in inbox table:' item = '''select * from inbox''' parameters = '' @@ -25,17 +35,24 @@ def readInbox(): for row in output: print row + def readSent(): + """Print each row from sent table""" print 'Printing everything in Sent table:' item = '''select * from sent where folder !='trash' ''' parameters = '' cur.execute(item, parameters) output = cur.fetchall() for row in output: - msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, sleeptill, status, retrynumber, folder, encodingtype, ttl = row - print hexlify(msgid), toaddress, 'toripe:', hexlify(toripe), 'fromaddress:', fromaddress, 'ENCODING TYPE:', encodingtype, 'SUBJECT:', repr(subject), 'MESSAGE:', repr(message), 'ACKDATA:', hexlify(ackdata), lastactiontime, status, retrynumber, folder + (msgid, toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, + sleeptill, status, retrynumber, folder, encodingtype, ttl) = row # pylint: disable=unused-variable + print(hexlify(msgid), toaddress, 'toripe:', hexlify(toripe), 'fromaddress:', fromaddress, 'ENCODING TYPE:', + encodingtype, 'SUBJECT:', repr(subject), 'MESSAGE:', repr(message), 'ACKDATA:', hexlify(ackdata), + lastactiontime, status, retrynumber, folder) + def readSubscriptions(): + """Print each row from subscriptions table""" print 'Printing everything in subscriptions table:' item = '''select * from subscriptions''' parameters = '' @@ -44,7 +61,9 @@ def readSubscriptions(): for row in output: print row + def readPubkeys(): + """Print each row from pubkeys table""" print 'Printing everything in pubkeys table:' item = '''select address, transmitdata, time, usedpersonally from pubkeys''' parameters = '' @@ -52,61 +71,66 @@ def readPubkeys(): output = cur.fetchall() for row in output: address, transmitdata, time, usedpersonally = row - print 'Address:', address, '\tTime first broadcast:', unicode(strftime('%a, %d %b %Y %I:%M %p',localtime(time)),'utf-8'), '\tUsed by me personally:', usedpersonally, '\tFull pubkey message:', hexlify(transmitdata) + print( + 'Address:', address, '\tTime first broadcast:', unicode( + strftime('%a, %d %b %Y %I:%M %p', localtime(time)), 'utf-8'), + '\tUsed by me personally:', usedpersonally, '\tFull pubkey message:', hexlify(transmitdata), + ) + def readInventory(): + """Print each row from inventory table""" print 'Printing everything in inventory table:' item = '''select hash, objecttype, streamnumber, payload, expirestime from inventory''' parameters = '' cur.execute(item, parameters) output = cur.fetchall() for row in output: - hash, objecttype, streamnumber, payload, expirestime = row - print 'Hash:', hexlify(hash), objecttype, streamnumber, '\t', hexlify(payload), '\t', unicode(strftime('%a, %d %b %Y %I:%M %p',localtime(expirestime)),'utf-8') + obj_hash, objecttype, streamnumber, payload, expirestime = row + print 'Hash:', hexlify(obj_hash), objecttype, streamnumber, '\t', hexlify(payload), '\t', unicode( + strftime('%a, %d %b %Y %I:%M %p', localtime(expirestime)), 'utf-8') def takeInboxMessagesOutOfTrash(): + """Update all inbox messages with folder=trash to have folder=inbox""" item = '''update inbox set folder='inbox' where folder='trash' ''' parameters = '' cur.execute(item, parameters) - output = cur.fetchall() + _ = cur.fetchall() conn.commit() print 'done' + def takeSentMessagesOutOfTrash(): + """Update all sent messages with folder=trash to have folder=sent""" item = '''update sent set folder='sent' where folder='trash' ''' parameters = '' cur.execute(item, parameters) - output = cur.fetchall() + _ = cur.fetchall() conn.commit() print 'done' + def markAllInboxMessagesAsUnread(): + """Update all messages in inbox to have read=0""" item = '''update inbox set read='0' ''' parameters = '' cur.execute(item, parameters) - output = cur.fetchall() + _ = cur.fetchall() conn.commit() queues.UISignalQueue.put(('changedInboxUnread', None)) print 'done' + def vacuum(): + """Perform a vacuum on the database""" item = '''VACUUM''' parameters = '' cur.execute(item, parameters) - output = cur.fetchall() + _ = cur.fetchall() conn.commit() print 'done' -#takeInboxMessagesOutOfTrash() -#takeSentMessagesOutOfTrash() -#markAllInboxMessagesAsUnread() -readInbox() -#readSent() -#readPubkeys() -#readSubscriptions() -#readInventory() -#vacuum() #will defragment and clean empty space from the messages.dat file. - - +if __name__ == '__main__': + readInbox() diff --git a/src/namecoin.py b/src/namecoin.py index 9b3c3c3e..7f081bc6 100644 --- a/src/namecoin.py +++ b/src/namecoin.py @@ -1,54 +1,64 @@ -# Copyright (C) 2013 by Daniel Kraft