Skip to content

Commit

Permalink
Merge pull request #27 from Postcard/v0.3.4
Browse files Browse the repository at this point in the history
V0.3.4
  • Loading branch information
benoitguigal committed Jun 4, 2015
2 parents 7c32b86 + b92c814 commit 9c8ff93
Show file tree
Hide file tree
Showing 6 changed files with 137 additions and 24 deletions.
8 changes: 7 additions & 1 deletion figureraspbian/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf8 -*-

import os
import time
import logging
logging.basicConfig(level='INFO')
Expand Down Expand Up @@ -46,6 +46,12 @@ def get_listener():
api.download(ticket_css_url, settings.STATIC_ROOT)
except Exception:
pass
logger.info("Downloading example snapshot...")
snapshot_example_url = "%s/%s" % (settings.API_HOST, 'static/snapshots/example.jpg')
try:
api.download(snapshot_example_url, os.path.join(settings.MEDIA_ROOT, 'snapshots'))
except Exception:
pass

listener = get_listener()

Expand Down
8 changes: 8 additions & 0 deletions figureraspbian/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
logger = logging.getLogger(__name__)
import time
import os
import random

from ZEO import ClientStorage
from ZODB import DB
Expand Down Expand Up @@ -82,6 +83,9 @@ def get_code(self):
def add_ticket(self, ticket):
return self.data.add_ticket(ticket)

def get_random_ticket(self):
return self.data.get_random_ticket()

def upload_tickets(self):
while self.data.last_upload_index != (len(self.data.tickets) - 1):
try:
Expand Down Expand Up @@ -110,6 +114,10 @@ def add_ticket(self, ticket):
self.tickets.append(ticket)
self._p_changed = True

def get_random_ticket(self):
active_tickets = [ticket for ticket in self.tickets if ticket['installation'] == self.installation.id]
return random.choice(active_tickets) if active_tickets else None

def upload_tickets(self):
""" Upload the older ticket """
if len(self.tickets) > 0:
Expand Down
13 changes: 1 addition & 12 deletions figureraspbian/devices/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,7 @@ def capture(self, installation):
if settings.FLASH_ON:
self.light.flash_off()

# Get date
if settings.CAMERA_TYPE == 'CANON':
date = datetime.now(pytz.timezone(settings.TIMEZONE))
else:
error, info = gp.gp_camera_file_get_info(
self.camera,
folder,
name,
self.context)
date = datetime.fromtimestamp(info.file.mtime)
timezone = pytz.timezone(settings.TIMEZONE)
timezone.localize(date)
date = datetime.now(pytz.timezone(settings.TIMEZONE))

# Get snapshot file
error, camera_file = gp.gp_camera_file_get(
Expand Down
42 changes: 35 additions & 7 deletions figureraspbian/processus.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
from .db import Database, managed
import phantomjs

# Pre-calculated random_ticket to be used
random_snapshot_path = None
code = None


def run():
with managed(Database()) as db:
try:
installation = db.data.installation

if installation.id is not None:
# Database is initialized !

Expand All @@ -39,10 +42,6 @@ def run():
blinking_task = devices.OUTPUT.blink()

# Render ticket
start = time.time()
code = db.get_code()
end = time.time()
logger.info('Successfully claimed code in %s seconds', end - start)

start = time.time()
random_text_selections = [ticketrenderer.random_selection(variable) for
Expand All @@ -51,10 +50,29 @@ def run():
random_image_selections = [ticketrenderer.random_selection(variable) for
variable in
ticket_template['image_variables']]

global code
if code:
current_code = code
else:
# we need to claim a code
start = time.time()
current_code = db.get_code()
end = time.time()
logger.info('Successfully claimed code in %s seconds', end - start)

global random_snapshot_path
if random_snapshot_path:
current_random_snapshot_path = random_snapshot_path
else:
random_ticket = db.get_random_ticket()
current_random_snapshot_path = random_ticket['snapshot'] if random_ticket else None

rendered_html = ticketrenderer.render(
ticket_template['html'],
snapshot_path,
code,
current_random_snapshot_path,
current_code,
date,
ticket_template['images'],
random_text_selections,
Expand All @@ -81,7 +99,6 @@ def run():

# Set Output to True
devices.OUTPUT.set(False)

# Save ticket to disk
ticket_path = join(settings.MEDIA_ROOT, 'tickets', basename(snapshot_path))
with open(ticket_path, "wb") as f:
Expand All @@ -104,6 +121,17 @@ def run():
'random_image_selections': random_image_selections
}
db.add_ticket(ticket)

# Calculate random snapshot path
random_ticket = db.get_random_ticket()
random_snapshot_path = random_ticket['snapshot'] if random_ticket else None

# Calculate new code
start = time.time()
code = db.get_code()
end = time.time()
logger.info('Successfully claimed code in %s seconds', end - start)

else:
logger.warning("Current installation has ended. Skipping processus execution")
except Exception as e:
Expand Down
84 changes: 81 additions & 3 deletions figureraspbian/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import transaction

from .db import transaction_decorate
from . import phantomjs


class TestTicketRenderer(unittest.TestCase):
Expand All @@ -41,9 +40,10 @@ def test_random_selection_empty_variable(self):

def test_render(self):
"""
TicketRenderer should render a ticket
TicketRenderer should render a ticket when no random_snapshot
"""
html = '{{snapshot}} {{code}} {{datetime | datetimeformat}} {{textvariable_1}} {{imagevariable_2}} {{image_1}}'
html = '{{snapshot}} {{code}} {{datetime | datetimeformat}} ' \
'{{textvariable_1}} {{imagevariable_2}} {{image_1}}'
code = '5KIJ7'
date = parser.parse("Tue Jun 22 07:46:22 EST 2010")
images = [{'id': '1', 'image': 'path/to/image'}]
Expand All @@ -52,6 +52,7 @@ def test_render(self):
rendered_html = ticketrenderer.render(
html,
'/path/to/snapshot',
None,
code,
date,
images,
Expand All @@ -61,6 +62,51 @@ def test_render(self):
'http://localhost:8080/media/images/image http://localhost:8080/media/images/image'
self.assertIn(expected, rendered_html)

def test_render_random_snapshot_None(self):
"""
TicketRender should render a ticket when random snapshot but None is provided
"""
html = '<img src={{random_snapshot}}>'
code = '5KIJ7'
date = parser.parse("Tue Jun 22 07:46:22 EST 2010")
images = [{'id': '1', 'image': 'path/to/image'}]
random_text_selections = [('1', {'id': '2', 'text': 'Titi'}), ('2', None)]
random_image_slections = [('2', {'id': 1, 'image': '/path/to/image'})]
rendered_html = ticketrenderer.render(
html,
'/path/to/snapshot',
None,
code,
date,
images,
random_text_selections,
random_image_slections)
expected = '<img src=>'
self.assertIn(expected, rendered_html)

def test_render_random_snapshot(self):
"""
TicketRenderer should render a ticket with a random snapshot
"""
html = '<img src={{random_snapshot}}>'
code = '5KIJ7'
date = parser.parse("Tue Jun 22 07:46:22 EST 2010")
images = [{'id': '1', 'image': 'path/to/image'}]
random_text_selections = [('1', {'id': '2', 'text': 'Titi'}), ('2', None)]
random_image_slections = [('2', {'id': 1, 'image': '/path/to/image'})]
rendered_html = ticketrenderer.render(
html,
'/path/to/snapshot',
'/path/to/random/snapshot',
code,
date,
images,
random_text_selections,
random_image_slections)
expected = '<img src=http://localhost:8080/media/snapshots/snapshot>'
self.assertIn(expected, rendered_html)


def test_set_date_format(self):
"""
Ticket renderer should handle datetimeformat filter
Expand Down Expand Up @@ -408,6 +454,38 @@ def test_upload_tickets(self):
db.upload_tickets()
self.assertFalse(api.create_ticket.called)

def test_get_random_ticket(self):
"""
Get a random ticket should pick a random ticket in the ticket list
"""
with managed(Database()) as db:
time1 = datetime.now(pytz.timezone(settings.TIMEZONE))
time2 = datetime.now(pytz.timezone(settings.TIMEZONE))
ticket = db.get_random_ticket()
self.assertIsNone(ticket)
ticket_1 = {
'installation': '1',
'snapshot': '/path/to/snapshot',
'ticket': 'path/to/ticket',
'dt': time1,
'code': 'JHUYG',
'random_text_selections': [],
'random_image_selections': []
}
ticket_2 = {
'installation': '1',
'snapshot': '/path/to/snapshot',
'ticket': 'path/to/ticket',
'dt': time2,
'code': 'JU76G',
'random_text_selections': [],
'random_image_selections': []
}
db.add_ticket(ticket_1)
db.add_ticket(ticket_2)
ticket = db.get_random_ticket()
self.assertIn(ticket, [ticket_1, ticket_2])


class TestProcessus(unittest.TestCase):

Expand Down
6 changes: 5 additions & 1 deletion figureraspbian/ticketrenderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,13 @@ def random_selection(variable):
return variable['id'], random.choice(variable['items'])


def render(html, snapshot, code, date, images, random_text_selections, random_image_selections):
def render(html, snapshot, random_snapshot, code, date, images, random_text_selections, random_image_selections):
snapshot_url = 'http://localhost:8080/media/snapshots/%s' % os.path.basename(snapshot)
context = {'snapshot': snapshot_url}
random_snapshot_url = ('http://localhost:8080/media/snapshots/%s' % os.path.basename(random_snapshot) if
random_snapshot else
'http://localhost:8080/media/snapshots/example.jpg')
context['random_snapshot'] = random_snapshot_url
for (text_variable_id, item) in random_text_selections:
text = item['text'] if item else ''
context['textvariable_%s' % text_variable_id] = text
Expand Down

0 comments on commit 9c8ff93

Please sign in to comment.