Example #1
0
File: fs.py Project: Etenil/anvil
def user_branch_dir(username, branch=None):
    """Returns the path to the branch of user. If branch is None,
    then returns the path to the user's branch repository."""
    if branch == None:
        return os.path.join(config.val('home_dir'), "users", username)
    else:
        return os.path.join(config.val('home_dir'), "users", username, branch)
Example #2
0
File: fs.py Project: Etenil/anvil
def project_branch_dir(project, branch=None):
    """Returns the path to the branch of project. If branch is None,
    then returns the path to the project's branch repository."""
    if branch == None:
        return os.path.join(config.val('home_dir'), "projects", project)
    else:
        return os.path.join(config.val('home_dir'), "projects", project, branch)
Example #3
0
def run():
    logger.info("Retrieving myepisodes list")
    raw_feed = url.urlopen(config.val("rss")).read()
    title_list = re.findall("<title>(.*?)</title>", raw_feed)

    # Counting results, using a flag
    results = 0
    downloaded_flag = 0

    # Notification text - this var is updated each time a torrent is successfully found
    body = "Downloading episodes:\n"

    for title in title_list:
        title_cut = re.findall("\[ (.*?) \]", title)
        dropped_shows = config.dropped_shows()

        # If title is "", it's not a show. Also filtering according to specified year, and skipping some specific shows
        if len(title_cut) == 0:
            logger.info("Skipping empty line")
            continue
        elif int(title_cut[3][-4:]) < config.val("limit_date"):
            logger.info("Skipping show older than limit date (" + title_cut[3][-4:] + ")")
            continue
        elif title_cut[0] in dropped_shows:
            logger.info("Skipping specific show")
            continue
        else:
            results += 1

        episode_nbr = "S" + title_cut[1][:2] + "E" + title_cut[1][-2:]
        episode = title_cut[0] + " " + episode_nbr
        logger.info("Found episode : " + episode)

        # Searching episode, updating body notification if download has started
        logger.info("Searching episode")
        downloaded = torrent.download(episode)
        if downloaded:
            body = body + downloaded + "\n"
            downloaded_flag = 1

            # If nothing new, or could not fetch anything
    if results == 0 or downloaded_flag == 0:
        logger.info("Nothing new today")
    else:
        # Pushing notification
        logger.info("Pushing notification")
        config.notification(body)

        # Writing logs for web interface
    write_logs(body)

    return results
Example #4
0
File: fs.py Project: Etenil/anvil
def check_users():
    userspath = os.path.join(config.val('home_dir'), "users")
    logf = open("/tmp/anvserve", "w")
    logf.write(userspath)
    logf.close()
    if not os.path.exists(userspath):
        os.makedirs(userspath)
Example #5
0
def send(origin, dest, subject, message):
    body = string.join((
            "From: %s" % origin,
            "To: %s" % dest,
            "Subject: %s" % subject,
            "",
            message),
            "\r\n")
    try:
        s = smtplib.SMTP(config.val('smtp'))
        s.sendmail(origin, dest.split(","), body)
        s.quit()
    except:
        pass
Example #6
0
def download(title):
	# Searching for the title. Returning None if not found
	link = search(title)
	if link == None: 
		logger.info("Link was empty")
		return None

	# Downloading title
	logger.info("Fetching torrent")
	cmd = ["wget", "--no-check-certificate", link, "-qO", "/tmp/dl.torrent"]
	sp.call(cmd)
	
	# Sending .torrent to STB
	logger.info("Sending to STB")
	time.sleep(0.5)
	target_file = config.val("target_folder")+"/"+title+".torrent"
	cmd = ["mv", "/tmp/dl.torrent", target_file]
	sp.call(cmd)

	return title
Example #7
0
File: ssh.py Project: Etenil/anvil
def regenerate_keys():
    db = None
    try:
        db = MySQLdb.connect(host=config.val('db.host'),
                             user=config.val('db.user'),
                             passwd=config.val('db.pwd'),
                             db=config.val('db.name'))
    except:
        return False
    c = db.cursor()
    c.execute("SELECT * FROM ssh_keys")
    if not os.path.exists(os.path.join(config.val('home_dir'), '.ssh')):
        os.makedirs(os.path.join(config.val('home_dir'), '.ssh'))
    auth_keys = os.path.join(config.val('home_dir'), ".ssh/authorized_keys")
    key_file = open(auth_keys, 'w')
    for row in c:
        key_file.write("command=\"bzr anv-serve %d --inet\" %s\n" % (row[1], row[2]))
    key_file.close()
    os.chmod(auth_keys, stat.S_IRWXU)
    return True
Example #8
0
File: fs.py Project: Etenil/anvil
def add_project_branch(projectname, branch):
    os.makedirs(os.path.join(config.val('home_dir'), "projects", projectname, branch))
Example #9
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from RPiSensors import htu21d
import math, sqlite3, time, json, urllib2, config, datetime
import config
conn = sqlite3.connect('sensors.db')
c = conn.cursor()

if (config.val("sensors")=="yes"):
        import RPi.GPIO as GPIO, time, os
        # SENSORS (temperature, humidity)
        # init
        bus = 1
        sensor = htu21d.Htu21d(bus)
        sensor.use_temperature=True
        temp = sensor.temperature
        time.sleep(1)
        humi = sensor.humidity
        # write
        c.execute("INSERT INTO temp VALUES (?,?)", ( round(temp,2), int(time.time()) ))
        conn.commit()
        c.execute("INSERT INTO humi VALUES (?,?)", ( round(humi,2), int(time.time()) ))
        conn.commit()

        time.sleep(1)

        # LIGHT
        DEBUG = 1
        GPIO.setmode(GPIO.BCM)
        # fetch
Example #10
0
#!/usr/bin/env python

import json, urllib2, config

if __name__ == "__main__":
	data = urllib2.urlopen("https://developer-api.nest.com/devices.json?auth="+config.val("nest"))
	d = json.load(data)
	co_alarm_state = d['smoke_co_alarms'][config.val("nest_id")]['co_alarm_state']
	smoke_alarm_state = d['smoke_co_alarms'][config.val("nest_id")]['smoke_alarm_state']
	battery_health = d['smoke_co_alarms'][config.val("nest_id")]['battery_health']

	if co_alarm_state=="ok" and smoke_alarm_state=="ok" and battery_health=="ok":
		print "ok"
	else:
		print "ko"
Example #11
0
#!/usr/bin/env python

import json, urllib2, config, cgi

if __name__ == "__main__":

	form = cgi.FieldStorage()
	title = form['title'].value
	velib_station=config.val("velib_station_"+title)

	data = urllib2.urlopen("https://api.jcdecaux.com/vls/v1/stations/"+velib_station+"?contract=Paris&apiKey="+config.val("velib_key"))
	d = json.load(data)
	available_bikes = d['available_bikes']

	print available_bikes
Example #12
0
import matplotlib.pyplot as plt
print "Importing BeautifulSoup..."
from bs4 import BeautifulSoup
import config


### CHECKING INPUTS ###
# update --> updates data from Runkeeper if this arg is provided (or if no data exists yet).

if not(os.path.isfile(route_id+".log")) or ( len(sys.argv)>3 and str(sys.argv[3])=="update" ):
	print "Updating source file..."
	if os.path.isfile(route_id+".log"):
		bashCommand = "rm "+route_id+".log"
		os.system(bashCommand)
	
	bashCommand = "wget http://runkeeper.com/user/"+config.val("runkeeper_username")+"/route/"+route_id+" -O "+route_id+".log"
	os.system(bashCommand)

### END ###


print "Parsing data..."
soup = BeautifulSoup(open(route_id+".log"))
activities = soup.find_all('tr', id="routeActivityListItem")
activities_curated = {}

date_conversion = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}

for activity in activities:
	date = activity.findChildren('td')[0].text.strip()[0:28]
	date_curated = datetime.date( int(date[24:28]), int(date_conversion[str(date[4:7])]), int(date[8:10]) )
Example #13
0
File: fs.py Project: Etenil/anvil
def delete_project_branch(projectname, branch):
    shutil.rmtree(os.path.join(config.val('home_dir'), "projects", projectname, branch))
Example #14
0
File: fs.py Project: Etenil/anvil
def delete_project(projectname):
    shutil.rmtree(os.path.join(config.val('home_dir'), "projects", projectname))
Example #15
0
			msg = self.socket.recv(int(query.headers['Content-Length']))
			
			print msg

			query.postContent = msg

		# get response
		response = httpresponse.makeResponse(query,self.config)

		self.socket.send(response)
		self.socket.close()

##########################################

# load configuration
config = config.Config('pyhttpd.conf')
config.showConfig()

# create sockets
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), int(config.val('Port'))))

s.listen(int(config.val('MaxConnections')))

while True:  
	(clientsocket, address) = s.accept()
	
	# start the client thread
	ClientThread(clientsocket, config).start()

Example #16
0
File: fs.py Project: Etenil/anvil
def check_projects():
    projspath = os.path.join(config.val('home_dir'), "projects")
    if not os.path.exists(projspath):
        os.makedirs(projspath)
Example #17
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3, config, re
import subprocess as sp
conn = sqlite3.connect('sensors.db')
c = conn.cursor()

alert=""

if (config.val("sensors")=="yes"):
	# TEMPERATURE & HUMIDITY
	# fetch
	c.execute("SELECT * FROM temp ORDER BY date DESC LIMIT 3")
	temp = c.fetchone()[0]
	prev_temp = c.fetchone()[0]
	prev_prev_temp = c.fetchone()[0]
	c.execute("SELECT * FROM humi ORDER BY date DESC LIMIT 2")
	humi = c.fetchone()[0]
	prev_humi = c.fetchone()[0]
	# notifications
	if humi >= config.val("max_humi") and prev_humi < config.val("max_humi"):
	        alert=alert+"Humidity level above "+str(config.val("max_humi"))+"%25. "
	elif humi <= config.val("min_humi") and prev_humi > config.val("min_humi"):
	        alert=alert+"Humidity level below "+str(config.val("min_humi"))+"%25. "
	if temp >= config.val("max_temp") and prev_temp < config.val("max_temp") and prev_prev_temp < config.val("max_temp"):
	        alert=alert+"Temperature level above "+str(config.val("max_temp"))+"°C. "
	elif temp <= config.val("min_temp") and prev_temp > config.val("min_temp") and prev_prev_temp > config.val("min_temp"):
	        alert=alert+"Temperature level below "+str(config.val("min_temp"))+"°C. "

	# LIGHT TURNED ON
Example #18
0
File: fs.py Project: Etenil/anvil
def delete_user(username):
    shutil.rmtree(os.path.join(config.val('home_dir'), "users", username))
Example #19
0
File: fs.py Project: Etenil/anvil
def delete_user_branch(username, branch):
    shutil.rmtree(os.path.join(config.val('home_dir'), "users", username, branch))