Exemplo n.º 1
0
    def getImages(self, keyword):
        # Create filename from keyword
        filename = hashlib.new('sha1')
        filename.update(keyword)
        filename = filename.hexdigest() + ".json"
        filename = os.path.join(self.settings.get('tempfolder'), filename)

        if os.path.exists(filename) and self.settings.getUser(
                'refresh-content') > 0:  # Check age!
            age = math.floor((time.time() - os.path.getctime(filename)) / 3600)
            if age >= self.settings.getUser('refresh-content'):
                logging.debug('File too old, %dh > %dh, refreshing' %
                              (age, self.settings.getUser('refresh-content')))
                os.remove(filename)
                # Make sure we don't remember since we're refreshing
                memory = remember(filename, 0)
                memory.forget()

        if not os.path.exists(filename):
            # Request albums
            # Picasa limits all results to the first 1000, so get them
            params = {
                'kind':
                'photo',
                'start-index':
                1,
                'max-results':
                1000,
                'alt':
                'json',
                'access':
                'all',
                'imgmax':
                '1600u',  # We will replace this with width of framebuffer in pick_image
                # This is where we get cute, we pick from a list of keywords
                'fields':
                'entry(title,content,gphoto:timestamp,gphoto:videostatus)'  # No unnecessary stuff
            }
            if keyword != "":
                params['q'] = keyword
            url = 'https://picasaweb.google.com/data/feed/api/user/default'
            logging.debug('Downloading image list for %s...' % keyword)
            data = self.oauth.request(url, params=params)
            with open(filename, 'w') as f:
                f.write(data.content)
        images = None
        try:
            with open(filename) as f:
                images = json.load(f)
            logging.debug('Loaded %d images into list' %
                          len(images['feed']['entry']))
            return images, filename
        except:
            logging.exception('Failed to load images')
            os.remove(filename)
            return None, filename
Exemplo n.º 2
0
    def presentation(self):
        logging.info('Starting presentation')
        seen = []
        delay = 0
        while True:
            # Avoid showing images if the display is off
            if self.queryPowerFunc is not None and self.queryPowerFunc(
            ) is False:
                logging.info("Display is off, exit quietly")
                break

            imgs = cache = memory = None
            index = self.settings.getKeyword()
            tries = 20
            time_process = time.time()
            while tries > 0:
                tries -= 1
                if len(seen) == self.settings.countKeywords():
                    # We've viewed all images, reset
                    logging.info(
                        'All images we have keywords for have been seen, restart'
                    )
                    logging.info('Seen holds: %s', repr(seen))
                    logging.info('Settings.countKeywords() = %d',
                                 self.settings.countKeywords())

                    for saw in seen:
                        r = remember(saw, 0)
                        r.debug()
                        r.forget()
                    r = remember('/tmp/overallmemory.json', 0)
                    r.debug()
                    r.forget()
                    if self.settings.getUser('refresh-content') == 0:
                        logging.info('Make sure we refresh all images now')
                        for saw in seen:
                            os.remove(saw)
                    seen = []

                keyword = self.settings.getKeyword(index)
                imgs, cache = self.getImages(keyword)
                if imgs is None:
                    # Try again!
                    continue

                # If we've seen all images for this keyword, skip to next
                if cache in seen:
                    index += 1
                    if index == self.settings.countKeywords():
                        index = 0
                    continue

                memory = remember(cache, len(imgs['feed']['entry']))

                if not imgs or memory.seenAll():
                    if not imgs:
                        logging.error(
                            'Failed to load image list for keyword %s' %
                            keyword)
                    elif memory.seenAll():
                        seen.append(cache)
                        logging.debug(
                            'All images for keyword %s has been shown' %
                            keyword)
                    continue

                # Now, lets make sure we didn't see this before
                uri, mime, title, ts = self.pickImage(imgs, memory)
                if uri == '':
                    logging.warning('No image was returned from pickImage')
                    continue  # Do another one (well, it means we exhausted available images for this keyword)

                # Avoid having duplicated because of overlap from keywords
                memory = remember('/tmp/overallmemory.json', 0)
                if memory.seen(uri):
                    continue
                else:
                    memory.saw(uri)

                ext = helper.getExtension(mime)
                if ext is not None:
                    filename = os.path.join(self.settings.get('tempfolder'),
                                            'image.%s' % ext)
                    if self.downloadImage(uri, filename):
                        self.imageCurrent = filename
                        self.imageMime = mime
                        break
                    else:
                        logging.warning(
                            'Failed to download image, trying another one')
                else:
                    logging.warning('Mime type %s isn\'t supported' % mime)

            time_process = time.time() - time_process

            # Delay before we show the image (but take processing into account)
            # This should keep us fairly consistent
            if time_process < delay:
                time.sleep(delay - time_process)
            if tries == 0:
                self.display.message(
                    'Issues showing images\n\nCheck network and settings')
            else:
                self.display.image(self.imageCurrent)
                os.remove(self.imageCurrent)

            delay = self.settings.getUser('interval')
        self.thread = None
Exemplo n.º 3
0
  def getImages(self, keyword):
    # Create filename from keyword
    filename = hashlib.new('sha1')
    filename.update(repr(keyword))
    filename = filename.hexdigest() + ".json"
    filename = os.path.join(self.settings.get('tempfolder'), filename)

    if os.path.exists(filename) and self.settings.getUser('refresh-content') > 0: # Check age!
      age = math.floor( (time.time() - os.path.getctime(filename)) / 3600)
      if age >= self.settings.getUser('refresh-content'):
        logging.debug('File too old, %dh > %dh, refreshing' % (age, self.settings.getUser('refresh-content')))
        os.remove(filename)
        # Make sure we don't remember since we're refreshing
        memory = remember(filename, 0)
        memory.forget()

    if not os.path.exists(filename):
      # check if keyword is album
      '''url = 'https://photoslibrary.googleapis.com/v1/albums'
      data = self.oauth.request(url).json()
      albumid = None
      picturecount = self.settings.getUser('picturecount')
      for i in range(len(data['albums'])):
        if 'title' in data['albums'][i] and data['albums'][i]['title'] == keyword:
          albumid = data['albums'][i]['id']
      
      if albumid is None:
        url = 'https://photoslibrary.googleapis.com/v1/sharedAlbums'
        data = self.oauth.request(url).json()
        for i in range(len(data['sharedAlbums'])):
          if 'title' in data['sharedAlbums'][i] and data['sharedAlbums'][i]['title'] == keyword:
            albumid = data['sharedAlbums'][i]['id']

      # fallback to all pictures if album not available
      if albumid is not None:
        logging.debug('Got album: %s' % keyword)
        params = {
          'albumId' : albumid,
          'pageSize' : picturecount,
        }
      else:
        logging.debug('Couldn\'t get album: %s falling back to all images.' % keyword)
        params = {
          'pageSize' : picturecount,
          'filters': {
            'mediaTypeFilter': {
              'mediaTypes': [
                'PHOTO'
              ]
            }
          }
        }
      # Request albums      
      url = 'https://photoslibrary.googleapis.com/v1/mediaItems:search'
      #logging.debug('Downloading image list for %s...' % keyword)
      data = self.oauth.request(url, params=params,post=True)
      '''
      albumid = None
      albumid = self.checkForOwnAlbum(keyword)
      if albumid is None:
        albumid = self.checkForSharedAlbum(keyword)
      data = self.getPhotoList(albumid)

      if len(data) == 0:
        logging.warning('Requesting photo failed with status code %d (%s)', data.status_code, data.reason)
        return None, filename
      with open(filename, 'w') as f:
        json.dump(data,f)
    images = None
    try:
      with open(filename) as f:
        images = json.load(f)
      logging.debug('Loaded %d images into list' % len(images))
      return images, filename
    except:
      logging.exception('Failed to load images')
      os.remove(filename)
      return None, filename