예제 #1
0
def main_app(env, start_response):
    """Provides following features:
    - Serves static files
    - /debug route for mobile debugging
    - /command route for interacting with computer
    """
    request_path = env['PATH_INFO']

    if request_path == '/debug':
        return debug(env, start_response)

    elif request_path == '/settings':
        return get_settings(env, start_response)

    elif request_path == '/get_gif':
        ret, stdout, stderr = run_command(settings['gifScriptCommand'])
        print('STDOUT')
        print('------')
        print(stdout)
        print('STDERR')
        print('------')
        print(stderr)

        if ret != 0:
            response = 'Error'
            start_response('500 OK', HEADERS)
            return [json.dumps(response)]

        preview_path = path.get_resource('static/img/preview.gif')
        if not os.path.isfile(preview_path):
            response = 'Error'
            start_response('500 OK', HEADERS)
            return [json.dumps(response)]

        response = 'OK'
        start_response('200 OK', HEADERS)
        return [json.dumps(response)]

    elif request_path == '/save_gif':
        directory = os.path.abspath(settings['gifsDirectory'])

        new_name = str(int(time.time())) + '.gif'
        os.rename(path.get_resource('static/img/preview.gif'),
                  path.get_resource('static/img/%s' % new_name))
        shutil.move(path.get_resource('static/img/%s' % new_name), directory)

        response = 'OK'
        start_response('200 OK', HEADERS)
        return [json.dumps(response)]

    # Serve a file if it's found.
    else:
        if request_path == '/':
            request_path = '/static/index.html'

        return file_response(request_path, start_response)
예제 #2
0
def main_app(env, start_response):
    """Provides following features:
    - Serves static files
    - /debug route for mobile debugging
    - /command route for interacting with computer
    """
    request_path = env['PATH_INFO']

    if request_path == '/debug':
        return debug(env, start_response)

    elif request_path == '/settings':
        return get_settings(env, start_response)

    elif request_path == '/get_gif':
        ret, stdout, stderr = run_command(settings['gifScriptCommand'])
        print('STDOUT')
        print('------')
        print(stdout)
        print('STDERR')
        print('------')
        print(stderr)

        if ret != 0:
            response = 'Error'
            start_response('500 OK', HEADERS)
            return [json.dumps(response)]

        preview_path = path.get_resource('static/img/preview.gif')
        if not os.path.isfile(preview_path):
            response = 'Error'
            start_response('500 OK', HEADERS)
            return [json.dumps(response)]

        response = 'OK'
        start_response('200 OK', HEADERS)
        return [json.dumps(response)]

    elif request_path == '/save_gif':
        directory = os.path.abspath(settings['gifsDirectory'])

        new_name = str(int(time.time())) + '.gif'
        os.rename(path.get_resource('static/img/preview.gif'),
                  path.get_resource('static/img/%s' % new_name))
        shutil.move(path.get_resource('static/img/%s' % new_name), directory)

        response = 'OK'
        start_response('200 OK', HEADERS)
        return [json.dumps(response)]

    # Serve a file if it's found.
    else:
        if request_path == '/':
            request_path = '/static/index.html'

        return file_response(request_path, start_response)
예제 #3
0
def get_gif_files():
    gif_dir = os.path.abspath(path.get_resource('static/img/gifs'))
    gif_paths = glob.glob(os.path.join(gif_dir, '*.gif'))

    gif_files = []
    for gif_path in gif_paths:
        filename = os.path.basename(gif_path)
        url = os.path.join('/static/img/gifs/', filename)

        name, _ = os.path.splitext(filename)
        name_id = gif_id_from_name(name)

        im = Image.open(gif_path)
        width, height = im.size
        creation_time = os.path.getmtime(gif_path)

        gif_files.append((int(creation_time), {
            "url": url,
            "name": name,
            "id": name_id,
            "width": width,
            "height": height
        }))

    # Sort files based on creation time
    gif_files.sort()
    sorted_gif_files = []
    for creation_time, gif_file in gif_files:
        gif_file['created'] = creation_time
        sorted_gif_files.append(gif_file)

    return sorted_gif_files
예제 #4
0
def get_gif_files():
    gif_dir = os.path.abspath(path.get_resource('static/img/gifs'))
    gif_paths = glob.glob(os.path.join(gif_dir, '*.gif'))

    gif_files = []
    for gif_path in gif_paths:
        filename = os.path.basename(gif_path)
        url = os.path.join('/static/img/gifs/', filename)

        name, _ = os.path.splitext(filename)
        name_id = gif_id_from_name(name)

        im = Image.open(gif_path)
        width, height = im.size
        creation_time = os.path.getmtime(gif_path)

        gif_files.append((int(creation_time),
                         {"url": url, "name": name, "id": name_id,
                         "width": width, "height": height}))

    # Sort files based on creation time
    gif_files.sort()
    sorted_gif_files = []
    for creation_time, gif_file in gif_files:
        gif_file['created'] = creation_time
        sorted_gif_files.append(gif_file)

    return sorted_gif_files
예제 #5
0
def read_settings():
    file_path = path.get_resource('settings.json')
    try:
        content = open(file_path).read()
    except IOError, e:
        print('%s %s' % (_error_msg, file_path))
        print(e)
        sys.exit(2)
예제 #6
0
def read_settings():
    file_path = path.get_resource('settings.json')
    try:
        content = open(file_path).read()
    except IOError, e:
        print('%s %s' % (_error_msg, file_path))
        print(e)
        sys.exit(2)
예제 #7
0
def filepath(request_path):
    """Returns full filepath from request path.

    WARNING: This is not safe, one could use .. tricks to get into root path!!
    """
    if request_path.startswith('/'):
        request_path = request_path[1:]

    return path.get_resource(request_path)
예제 #8
0
def filepath(request_path):
    """Returns full filepath from request path.

    WARNING: This is not safe, one could use .. tricks to get into root path!!
    """
    if request_path.startswith('/'):
        request_path = request_path[1:]

    return path.get_resource(request_path)
예제 #9
0
파일: osx.py 프로젝트: vtoro/kauko
    def toggle_sleep_display(self):
        display_is_asleep = Quartz.CGDisplayIsAsleep(0)

        program_path = path.get_resource("vendor/SleepDisplay")
        if not display_is_asleep:
            subprocess.call([program_path])

        else:
            subprocess.call([program_path, "--wake"])
예제 #10
0
def main_app(env, start_response):
    """Provides following features:
    - Serves static files
    - /debug route for mobile debugging
    - /command route for interacting with computer
    """
    request_path = env['PATH_INFO']

    if request_path == '/debug':
        return debug(env, start_response)

    elif request_path == '/settings':
        return get_settings(env, start_response)

    # POST /gif
    elif request_path == '/gif':
        data = json.loads(get_post_data(env))
        gifs = read_json(GIFS_PATH)

        # Change gif's position in visible gifs
        for i, gif in enumerate(gifs['visible']):
            if gif['id'] == data['id']:
                gifs['visible'][i]['position'] = data['position']
                gifs['visible'][i]['height'] = data['height']

        # Set gif's possible new size
        gifs['all'][data['id']]['width'] = data['width']
        gifs['all'][data['id']]['height'] = data['height']
        gifs['all'][data['id']]['modified'] = int(time.time())

        # Save state to file
        save_json(GIFS_PATH, gifs)

        start_response('200 OK', [])
        return ['']

    # POST /hide_gif
    elif request_path == '/hide_gif':
        data = json.loads(get_post_data(env))
        gifs = read_json(GIFS_PATH)

        new_visible = [x for x in gifs['visible'] if x['id'] != data['id']]
        gifs['visible'] = new_visible

        # Save state to file
        save_json(GIFS_PATH, gifs)

        start_response('200 OK', [])
        return ['']

    elif request_path == '/tweets':
        tweets = open(
            path.get_resource('static/hashtag_tamperehuone.json')).read()

        start_response('200 OK', [])
        return [tweets]

    # GET /gifs or /gifs_no_state_change
    elif request_path.startswith('/gifs'):
        gifs = read_json(GIFS_PATH)

        # No state change allowed means that request should not save anything
        # to json state files
        stateChangeAllowed = not request_path.endswith('no_state_change')
        if not stateChangeAllowed:
            data = format_gifs(gifs)
            start_response('200 OK', [])
            return [json.dumps(data)]

        # Check if there are new gifs
        new_gifs_found = False
        gif_files = get_gif_files()
        for gif_file in gif_files:
            gif_id = gif_file['id']

            if gif_id not in gifs['all']:
                # New gif found, add it to all gifs and visible
                logger.info('Adding new gif %s to visible' % gif_file['name'])
                gifs['all'][gif_id] = gif_file
                gifs['all'][gif_id]['modified'] = int(time.time())

                add_new_gif(gifs['visible'], gif_file)
                new_gifs_found = True

        # Check if we should switch dancers
        if (time.time() >
                state['last_dancer_switch'] + settings['switchDancers']
                and not new_gifs_found and gif_files):

            retries = 50
            nextId = gifs['lastAddedId']
            while retries > 0:
                nextId = get_next_dancer_id(gif_files, nextId)

                if nextId not in [x['id'] for x in gifs['visible']]:
                    break

                retries -= 1

            gifs['lastAddedId'] = nextId
            nextGif = gifs['all'][nextId]

            if retries > 0:
                logging.info('Cycled dancers. Removed %s and added %s' %
                             (gifs['visible'][0]['id'], nextGif['id']))
                add_new_gif(gifs['visible'], nextGif)
                state['last_dancer_switch'] = time.time()

        save_json(GIFS_PATH, gifs)
        start_response('200 OK', [])
        return [json.dumps(format_gifs(gifs))]

    elif request_path == '/background':

        backgrounds = settings['backgrounds']
        background = '/static/img/disco.jpg'

        for range_start, range_end, img_url in backgrounds:
            if is_time_between(range_start, range_end):
                background = img_url
                break

        start_response('200 OK', [])
        return [json.dumps({"background": background})]

    # Serve a file if it's found.
    else:
        if request_path == '/':
            request_path = '/static/index.html'

        return file_response(request_path, start_response)
예제 #11
0
import mimetypes
import os
import urlparse
import string
import random
import time
from PIL import Image

import path
from settings import settings

script_dir = os.path.dirname(os.path.realpath(__file__))
logger = logging.getLogger(__name__)
browserLogger = logging.getLogger('browser')

GIFS_PATH = path.get_resource('gifs.json')

# Very bad way of saving state in the backend
state = {'last_dancer_switch': time.time()}


def main_app(env, start_response):
    """Provides following features:
    - Serves static files
    - /debug route for mobile debugging
    - /command route for interacting with computer
    """
    request_path = env['PATH_INFO']

    if request_path == '/debug':
        return debug(env, start_response)
예제 #12
0
def main_app(env, start_response):
    """Provides following features:
    - Serves static files
    - /debug route for mobile debugging
    - /command route for interacting with computer
    """
    request_path = env['PATH_INFO']

    if request_path == '/debug':
        return debug(env, start_response)

    elif request_path == '/settings':
        return get_settings(env, start_response)

    # POST /gif
    elif request_path == '/gif':
        data = json.loads(get_post_data(env))
        gifs = read_json(GIFS_PATH)

        # Change gif's position in visible gifs
        for i, gif in enumerate(gifs['visible']):
            if gif['id'] == data['id']:
                gifs['visible'][i]['position'] = data['position']
                gifs['visible'][i]['height'] = data['height']

        # Set gif's possible new size
        gifs['all'][data['id']]['width'] = data['width']
        gifs['all'][data['id']]['height'] = data['height']
        gifs['all'][data['id']]['modified'] = int(time.time())

        # Save state to file
        save_json(GIFS_PATH, gifs)

        start_response('200 OK', [])
        return ['']

    # POST /hide_gif
    elif request_path == '/hide_gif':
        data = json.loads(get_post_data(env))
        gifs = read_json(GIFS_PATH)

        new_visible = [x for x in gifs['visible'] if x['id'] != data['id']]
        gifs['visible'] = new_visible

        # Save state to file
        save_json(GIFS_PATH, gifs)

        start_response('200 OK', [])
        return ['']

    elif request_path == '/tweets':
        tweets = open(path.get_resource('static/hashtag_tamperehuone.json')).read()

        start_response('200 OK', [])
        return [tweets]

    # GET /gifs or /gifs_no_state_change
    elif request_path.startswith('/gifs'):
        gifs = read_json(GIFS_PATH)

        # No state change allowed means that request should not save anything
        # to json state files
        stateChangeAllowed = not request_path.endswith('no_state_change')
        if not stateChangeAllowed:
            data = format_gifs(gifs)
            start_response('200 OK', [])
            return [json.dumps(data)]

        # Check if there are new gifs
        new_gifs_found = False
        gif_files = get_gif_files()
        for gif_file in gif_files:
            gif_id = gif_file['id']

            if gif_id not in gifs['all']:
                # New gif found, add it to all gifs and visible
                logger.info('Adding new gif %s to visible' % gif_file['name'])
                gifs['all'][gif_id] = gif_file
                gifs['all'][gif_id]['modified'] = int(time.time())

                add_new_gif(gifs['visible'], gif_file)
                new_gifs_found = True

        # Check if we should switch dancers
        if (time.time() > state['last_dancer_switch'] + settings['switchDancers'] and
            not new_gifs_found and
            gif_files):

            retries = 50
            nextId = gifs['lastAddedId']
            while retries > 0:
                nextId = get_next_dancer_id(gif_files, nextId)

                if nextId not in [x['id'] for x in gifs['visible']]:
                    break

                retries -= 1

            gifs['lastAddedId'] = nextId
            nextGif = gifs['all'][nextId]

            if retries > 0:
                logging.info('Cycled dancers. Removed %s and added %s' % (gifs['visible'][0]['id'], nextGif['id']))
                add_new_gif(gifs['visible'], nextGif)
                state['last_dancer_switch'] = time.time()

        save_json(GIFS_PATH, gifs)
        start_response('200 OK', [])
        return [json.dumps(format_gifs(gifs))]

    elif request_path == '/background':

        backgrounds = settings['backgrounds']
        background = '/static/img/disco.jpg'

        for range_start, range_end, img_url in backgrounds:
            if is_time_between(range_start, range_end):
                background = img_url
                break

        start_response('200 OK', [])
        return [json.dumps({"background": background})]

    # Serve a file if it's found.
    else:
        if request_path == '/':
            request_path = '/static/index.html'

        return file_response(request_path, start_response)
예제 #13
0
import os
import urlparse
import string
import random
import time
from PIL import Image

import path
from settings import settings

script_dir = os.path.dirname(os.path.realpath(__file__))
logger = logging.getLogger(__name__)
browserLogger = logging.getLogger('browser')


GIFS_PATH = path.get_resource('gifs.json')


# Very bad way of saving state in the backend
state = {
    'last_dancer_switch': time.time()
}

def main_app(env, start_response):
    """Provides following features:
    - Serves static files
    - /debug route for mobile debugging
    - /command route for interacting with computer
    """
    request_path = env['PATH_INFO']