~facundo/encuentro/trunk

« back to all changes in this revision

Viewing changes to encuentro/image.py

  • Committer: Facundo Batista
  • Date: 2013-03-27 02:39:36 UTC
  • mfrom: (151.1.22 qtui)
  • mto: (151.2.2 trunk)
  • mto: This revision was merged to the branch mainline in revision 153.
  • Revision ID: facundo@taniquetil.com.ar-20130327023936-leainarptqpt7v7c
We do Qt now.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# FIXME: header and all that
 
2
 
 
3
 
 
4
import logging
 
5
import md5
 
6
import os
 
7
 
 
8
from twisted.web.client import getPage
 
9
 
 
10
from encuentro import platform
 
11
 
 
12
logger = logging.getLogger('encuentro.main')
 
13
 
 
14
 
 
15
class ImageGetter(object):
 
16
    """Image downloader and cache object."""
 
17
 
 
18
    def __init__(self, callback):
 
19
        self.callback = callback
 
20
        self.cache_dir = os.path.join(platform.cache_dir, 'encuentro.images')
 
21
        if not os.path.exists(self.cache_dir):
 
22
            os.makedirs(self.cache_dir)
 
23
 
 
24
    def get_image(self, episode_id, url):
 
25
        """Get an image and show it using the callback."""
 
26
        logger.info("Loading image for episode %s: %r", episode_id, url)
 
27
        file_name = md5.md5(url).hexdigest() + '.jpg'
 
28
        file_fullname = os.path.join(self.cache_dir, file_name)
 
29
        if os.path.exists(file_fullname):
 
30
            logger.debug("Image already available: %r", file_fullname)
 
31
            self.callback(episode_id, file_fullname)
 
32
            return
 
33
 
 
34
        def _d_callback(data, episode_id, file_fullname):
 
35
            """Cache the image and use the callback."""
 
36
            logger.debug("Image downloaded for episode_id %s, saving to %r",
 
37
                         episode_id, file_fullname)
 
38
            temp_file_name = file_fullname + '.tmp'
 
39
            with open(temp_file_name, 'wb') as fh:
 
40
                fh.write(data)
 
41
            os.rename(temp_file_name, file_fullname)
 
42
            self.callback(episode_id, file_fullname)
 
43
 
 
44
        logger.debug("Need to download the image")
 
45
        d = getPage(url)
 
46
        d.addCallback(_d_callback, episode_id, file_fullname)
 
47
        # FIXME: add an errback to log on error