Skip to content

Commit

Permalink
First release, remove not used lines from gitignore
Browse files Browse the repository at this point in the history
  • Loading branch information
shortcutme committed Jan 12, 2015
1 parent c0bfb3b commit d28e1cb
Show file tree
Hide file tree
Showing 85 changed files with 7,205 additions and 50 deletions.
52 changes: 2 additions & 50 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,5 @@
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/

# PyBuilder
target/
# Log files
*.log
2 changes: 2 additions & 0 deletions data/sites.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
1 change: 1 addition & 0 deletions log/empty.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Place for log files.
129 changes: 129 additions & 0 deletions src/Config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import argparse, sys, os, time
import ConfigParser

class Config(object):
def __init__(self):
self.version = "0.1"
self.parser = self.createArguments()
argv = sys.argv[:] # Copy command line arguments
argv = self.parseConfig(argv) # Add arguments from config file
self.parseCommandline(argv) # Parse argv
self.setAttributes()


def __str__(self):
return str(self.arguments).replace("Namespace", "Config") # Using argparse str output


# Create command line arguments
def createArguments(self):
# Platform specific
if sys.platform.startswith("win"):
upnpc = "tools\\upnpc\\upnpc-static.exe"
coffeescript = "type %s | tools\\coffee\\coffee.cmd"
else:
upnpc = None
coffeescript = None

# Create parser
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
subparsers = parser.add_subparsers(title="Action to perform", dest="action")

# Main
action = subparsers.add_parser("main", help='Start UiServer and FileServer (default)')

# SiteCreate
action = subparsers.add_parser("siteCreate", help='Create a new site')

# SiteSign
action = subparsers.add_parser("siteSign", help='Update and sign content.json: address [privatekey]')
action.add_argument('address', help='Site to sign')
action.add_argument('privatekey', help='Private key (default: ask on execute)', nargs='?')

# SitePublish
action = subparsers.add_parser("sitePublish", help='Publish site to other peers: address')
action.add_argument('address', help='Site to publish')

# SiteVerify
action = subparsers.add_parser("siteVerify", help='Verify site files using md5: address')
action.add_argument('address', help='Site to verify')


# Config parameters
parser.add_argument('--debug', help='Debug mode', action='store_true')

parser.add_argument('--ui_ip', help='Web interface bind address', default="127.0.0.1", metavar='host')
parser.add_argument('--ui_port', help='Web interface bind port', default=43110, metavar='port')
parser.add_argument('--ui_restrict', help='Restrict web access', default=False, metavar='ip')
parser.add_argument('--homepage', help='Web interface Homepage', default='1EU1tbG9oC1A8jz2ouVwGZyQ5asrNsE4Vr', metavar='address')

parser.add_argument('--fileserver_ip', help='FileServer bind address', default="*", metavar='host')
parser.add_argument('--fileserver_port',help='FileServer bind port', default=15441, metavar='port')

parser.add_argument('--ip_external', help='External ip (tested on start if None)', metavar='ip')
parser.add_argument('--upnpc', help='MiniUPnP binary for open port on router', default=upnpc, metavar='executable_path')

parser.add_argument('--coffeescript_compiler', help='Coffeescript compiler for developing', default=coffeescript, metavar='executable_path')

parser.add_argument('--version', action='version', version='ZeroNet %s' % self.version)

return parser


# Find arguments specificed for current action
def getActionArguments(self):
back = {}
arguments = self.parser._subparsers._group_actions[0].choices[self.action]._actions[1:] # First is --version
for argument in arguments:
back[argument.dest] = getattr(self, argument.dest)
return back



# Try to find action from sys.argv
def getAction(self, argv):
actions = [action.choices.keys() for action in self.parser._actions if action.dest == "action"][0] # Valid actions
found_action = False
for action in actions: # See if any in sys.argv
if action in argv:
found_action = action
break
return found_action


# Parse command line arguments
def parseCommandline(self, argv):
# Find out if action is specificed on start
action = self.getAction(argv)
if len(argv) == 1 or not action: # If no action specificed set the main action
argv.append("main")
if "zeronet.py" in argv[0]:
self.arguments = self.parser.parse_args(argv[1:])
else: # Silent errors if not started with zeronet.py
self.arguments = self.parser.parse_args(argv[1:])


# Parse config file
def parseConfig(self, argv):
if os.path.isfile("zeronet.conf"):
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read('zeronet.conf')
for section in config.sections():
for key, val in config.items(section):
if section != "global": # If not global prefix key with section
key = section+"_"+key
if val: argv.insert(1, val)
argv.insert(1, "--%s" % key)
return argv



# Expose arguments as class attributes
def setAttributes(self):
# Set attributes from arguments
args = vars(self.arguments)
for key, val in args.items():
setattr(self, key, val)


config = Config()
26 changes: 26 additions & 0 deletions src/Crypt/CryptBitcoin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from src.lib.BitcoinECC import BitcoinECC
import hashlib


def newPrivatekey(): # Return new private key
bitcoin = BitcoinECC.Bitcoin()
bitcoin.GeneratePrivateKey()
return bitcoin.PrivateEncoding()


def privatekeyToAddress(privatekey): # Return address from private key
bitcoin = BitcoinECC.Bitcoin()
bitcoin.BitcoinAddressFromPrivate(privatekey)
return bitcoin.BitcoinAddresFromPublicKey()


def sign(data, privatekey): # Return sign to data using private key
bitcoin = BitcoinECC.Bitcoin()
bitcoin.BitcoinAddressFromPrivate(privatekey)
sign = bitcoin.SignECDSA(data)
return sign


def verify(data, address, sign): # Verify data using address and sign
bitcoin = BitcoinECC.Bitcoin()
return bitcoin.VerifyMessageFromBitcoinAddress(address, data, sign)
18 changes: 18 additions & 0 deletions src/Crypt/CryptHash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import hashlib

def sha1sum(file, blocksize=65536):
if hasattr(file, "endswith"): # Its a string open it
file = open(file, "rb")
hash = hashlib.sha1()
for block in iter(lambda: file.read(blocksize), ""):
hash.update(block)
return hash.hexdigest()


if __name__ == "__main__":
import cStringIO as StringIO
a = StringIO.StringIO()
a.write("hello!")
a.seek(0)
print hashlib.sha1("hello!").hexdigest()
print sha1sum(a)
Empty file added src/Crypt/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions src/Debug/DebugHook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import gevent, sys

last_error = None
def handleError(*args):
global last_error
if not args: # Get last error
args = sys.exc_info()
silent = True
else:
silent = False
print "Error catched", args
last_error = args
if not silent: sys.__excepthook__(*args)

OriginalGreenlet = gevent.Greenlet
class ErrorhookedGreenlet(OriginalGreenlet):
def _report_error(self, exc_info):
handleError(exc_info[0], exc_info[1], exc_info[2])

sys.excepthook = handleError
gevent.Greenlet = gevent.greenlet.Greenlet = ErrorhookedGreenlet
reload(gevent)
60 changes: 60 additions & 0 deletions src/Debug/DebugMedia.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os, subprocess, re, logging, time
from Config import config

# Find files with extension in path
def findfiles(path, find_ext):
for root, dirs, files in os.walk(path, topdown = False):
for file in sorted(files):
file_path = root+"/"+file
file_ext = file.split(".")[-1]
if file_ext in find_ext and not file.startswith("all."): yield file_path


# Generates: all.js: merge *.js, compile coffeescript, all.css: merge *.css, vendor prefix features
def merge(merged_path):
merge_dir = os.path.dirname(merged_path)
s = time.time()
ext = merged_path.split(".")[-1]
if ext == "js": # If merging .js find .coffee too
find_ext = ["js", "coffee"]
else:
find_ext = [ext]

# If exits check the other files modification date
if os.path.isfile(merged_path):
merged_mtime = os.path.getmtime(merged_path)
changed = False
for file_path in findfiles(merge_dir, find_ext):
if os.path.getmtime(file_path) > merged_mtime:
changed = True
break
if not changed: return # Assets not changed, nothing to do

# Merge files
parts = []
for file_path in findfiles(merge_dir, find_ext):
parts.append("\n\n/* ---- %s ---- */\n\n" % file_path)
if file_path.endswith(".coffee"): # Compile coffee script
if not config.coffeescript_compiler:
logging.error("No coffeescript compiler definied, skipping compiling %s" % merged_path)
return False # No coffeescript compiler, skip this file
command = config.coffeescript_compiler % file_path.replace("/", "\\")
s = time.time()
compiler = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
logging.debug("Running: %s (Done in %.2fs)" % (command, time.time()-s))
source = compiler.stdout.read()
if source:
parts.append(source)
else:
error = compiler.stderr.read()
parts.append("alert('%s compile error: %s');" % (file_path, re.escape(error)) )
else: # Add to parts
parts.append(open(file_path).read())

merged = "\n".join(parts)
if ext == "css": # Vendor prefix css
from lib.cssvendor import cssvendor
merged = cssvendor.prefix(merged)
merged = merged.replace("\r", "")
open(merged_path, "wb").write(merged)
logging.debug("Merged %s (%.2fs)" % (merged_path, time.time()-s))
35 changes: 35 additions & 0 deletions src/Debug/DebugReloader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import logging, os, sys, time
import threading

try:
from fs.osfs import OSFS
pyfilesystem = OSFS("src")
except Exception, err:
logging.info("%s: For autoreload please download pyfilesystem (https://code.google.com/p/pyfilesystem/)" % err)
pyfilesystem = False


class DebugReloader:
def __init__ (self, callback, directory = "/"):
if pyfilesystem:
self.directory = directory
self.callback = callback
logging.debug("Adding autoreload: %s, cb: %s" % (directory, callback))
thread = threading.Thread(target=self.addWatcher)
thread.daemon = True
thread.start()


def addWatcher(self, recursive=True):
try:
time.sleep(1) # Wait for .pyc compiles
pyfilesystem.add_watcher(self.changed, path=self.directory, events=None, recursive=recursive)
except Exception, err:
print "File system watcher failed: %s (on linux pyinotify not gevent compatible yet :( )" % err


def changed(self, evt):
if not evt.path or evt.path.endswith("pyc"): return False # Ignore *.pyc changes
#logging.debug("Changed: %s" % evt)
time.sleep(0.1) # Wait for lock release
self.callback()
1 change: 1 addition & 0 deletions src/Debug/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from DebugReloader import DebugReloader
Loading

0 comments on commit d28e1cb

Please sign in to comment.