Coverage for coherence/backend.py : 49%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*-
# Licensed under the MIT license # http://opensource.org/licenses/mit-license.php
# Copyright 2007,, Frank Scholz <coherence@beebits.net>
""" the base class for all backends
if there are any UPnP service actions, that can't be handled by the service classes itself, or need some special adjustments for the backend, they need to be defined here.
Like maybe upnp_Browse for the CDS Browse action. """
# list the device classes below, like ['MediaServer','MediaRenderer']
""" the init method for a backend, should probably most of the time be overwritten when the init is done, send a signal to its device
the device will then setup and announce itself, after that it calls the backends upnp_init method """
""" do whatever is necessary with the stuff we can extract from the config dict, connect maybe to an external data-source and start up the backend after that's done, tell Coherence about it """
to wait for an answer from an external data-source first """ # self.init_completed()
""" inform Coherence that this backend is ready for announcement this method just accepts any form of arguments as we don't under which circumstances it is called """ None, backend=self)
""" this method gets called after the device is fired, here all initializations of service related state variables should happen, as the services aren't available before that point """ pass
""" the base class for all MediaServer backend stores """
""" the init method for a MediaServer backend, should probably most of the time be overwritten when the init is done, send a signal to its device
the device will then setup and announce itself, after that it calls the backends upnp_init method """
""" do whatever is necessary with the stuff we can extract from the config dict """
""" in case we want so serve something via the MediaServer web backend
the BackendItem should pass an URI assembled of urlbase + '/' + id to the DIDLLite.Resource """
'F': 'F', '11': '11', '16': '16', 'B': 'B', 'C': 'C', 'D': 'D', '13': '13', '17': '17', '8': '8', '9': '9', '10': '10', '15': '15', 'A': 'A', 'E': 'E'}
'8': lambda: self._get_all_items(0), 'B': lambda: self._get_all_items(0), })
""" # louie.send('Coherence.UPnP.Backend.init_completed', # None, backend=self)
""" if anything needs to be cleaned up upon shutdown of this backend, this is the place for it """ pass
""" a helper method to get all items as a response to some XBox 360 UPnP Search action probably never be used as the backend will overwrite the wmc_mapping with more appropriate methods """ continue else:
def get_by_id(self, id): """ called by the CDS or the MediaServer web
id is the id property of our DIDLLite item
if this MediaServer implements containers, that can share their content, like 'all tracks', 'album' and 'album_of_artist' - they all have the same track item as content - then the id may be passed by the CDS like this:
'id@container' or 'id@container@container@container...'
therefore a
if isinstance(id, basestring): id = id.split('@',1) id = id[0]
may be appropriate as the first thing to do when entering this method
should return
- None when no matching item for that id is found, - a BackendItem, - or a Deferred
"""
return None
""" the base class for all MediaServer backend items """
""" most of the time we collect the necessary data for an UPnP ContentDirectoryService Container or Object and instantiate it here
self.item = DIDLLite.Container(id,parent_id,name,...) or self.item = DIDLLite.MusicTrack(id,parent_id,name,...)
To make that a valid UPnP CDS Object it needs one or more DIDLLite.Resource(uri,protocolInfo)
self.item.res = [] res = DIDLLite.Resource(url, 'http-get:*:%s:*' % mimetype)
url : the urlbase of our backend + '/' + our id
res.size = size self.item.res.append(res) """
# the basename of a file, the album title, the artists name... # is expected to be unicode # when an UPnP ContentDirectoryService Container # this should be incremented on every modification
# the filepath of our media file, or alternatively # a FilePath or a ReverseProxyResource object
# the filepath or link into here
""" called by the CDS and the MediaServer web should return
- a list of its childs[start:end] - or a Deferred
if end == 0, the request is for all childs after start - childs[start:] """ pass
""" called by the CDS should return
- the number of its childs - len(childs) - or a Deferred
"""
""" called by the CDS and the MediaServer web should return
- an UPnP ContentDirectoryServer DIDLLite object - or a Deferred """ return self.item
""" called by the MediaServer web should return
- the name of the item, it is always expected to be in unicode """ return self.name
""" called by the MediaServer web should return
- the filepath where to find the media file that this item does refer to """ return self.location
""" called by the MediaServer web should return
- the filepath where to find the album art file
only needed when we have created for that item an albumArtURI property that does point back to us """ return self.cover
pass
""" creates a deferred chain to retrieve the rdf file, parse and extract the metadata and reschedule itself """
def fail(f): # TODO fix loggable thing self.info("fail %r", f) self.debug(f.getTraceback()) return f
dfr = getPage(rss_url) dfr.addCallback(etree.fromstring) dfr.addErrback(fail) dfr.addCallback(self.parse_data, container) dfr.addErrback(fail) dfr.addBoth(self.queue_update, rss_url, container) return dfr
""" extract media info and create BackendItems """ pass
from twisted.internet import reactor reactor.callLater(self.refresh, self.update_data, rss_url, container)
self.parent_id = self.parent.get_id() else:
return cmp_to_key(x.name, y.name)
child.external_id = external_id self.children_by_external_id[external_id] = child
self.children = []
self.children.remove(child) self.store.remove_item(child) if update: self.update_id += 1 if external_id is not None: child.external_id = None del self.children_by_external_id[external_id]
if not self.sorted: self.children = sorted( self.children.sort, key=cmp_to_key(self.sorting_method)) self.sorted = True if end != 0: return self.children[start:end] return self.children[start:]
if self.children is None: return 0 return len(self.children)
return self.store.urlbase + str(self.storage_id)
if self.item is None: self.item = DIDLLite.Container(self.storage_id, self.parent_id, self.name) self.item.childCount = len(self.children) return self.item
return self.update_id
childrenRetriever=None, **kwargs): Container.__init__(self, parent, title)
self.childrenRetrievingNeeded = True self.childrenRetrievingDeferred = None self.childrenRetriever = childrenRetriever self.children_retrieval_campaign_in_progress = False self.childrenRetriever_params = kwargs self.childrenRetriever_params['parent'] = self self.has_pages = ('per_page' in self.childrenRetriever_params)
self.external_id = None self.external_id = external_id
self.retrieved_children = {}
self.last_updated = 0 self.refresh = refresh
if self.external_id is not None and item.external_id is not None: return self.external_id == item.external_id return True
if self.children_retrieval_campaign_in_progress is True: self.retrieved_children[external_id] = child else: Container.add_child(self, child, external_id=external_id, update=update)
children_to_be_removed = {} children_to_be_replaced = {} children_to_be_added = {}
# Phase 1 # let's classify the item between items to be removed, # to be updated or to be added self.debug("Refresh pass 1:%d %d", len(new_children), len(old_children)) for id, item in list(old_children.items()): children_to_be_removed[id] = item for id, item in list(new_children.items()): if id in old_children: # print(id, "already there") children_to_be_replaced[id] = old_children[id] del children_to_be_removed[id] else: children_to_be_added[id] = new_children[id]
# Phase 2 # Now, we remove, update or add the relevant items # to the list of items self.debug("Refresh pass 2: %d %d %d", len(children_to_be_removed), len(children_to_be_replaced), len(children_to_be_added)) # Remove relevant items from Container children for id, item in list(children_to_be_removed.items()): self.remove_child(item, external_id=id, update=False) # Update relevant items from Container children for id, item in list(children_to_be_replaced.items()): old_item = item new_item = new_children[id] replaced = False if hasattr(old_item, 'replace_by'): replaced = old_item.replace_by(new_item) if replaced is False: # print("No replacement possible: # we remove and add the item again") self.remove_child(old_item, external_id=id, update=False) self.add_child(new_item, external_id=id, update=False) # Add relevant items to COntainer children for id, item in list(children_to_be_added.items()): self.add_child(item, external_id=id, update=False)
self.update_id += 1
self.last_updated = time.time() self.retrieved_children = {} self.children_retrieval_campaign_in_progress = True
self.children_retrieval_campaign_in_progress = False if success is True: self.update_children(self.retrieved_children, self.children_by_external_id) self.update_id += 1 self.last_updated = time.time() self.retrieved_children = {}
def items_retrieved(result, page, start_offset): if self.childrenRetrievingNeeded is True: new_offset = len(self.retrieved_children) return self.retrieve_children( new_offset, page + 1) # we try the next page return self.retrieved_children
self.childrenRetrievingNeeded = False if self.has_pages is True: self.childrenRetriever_params['offset'] = start self.childrenRetriever_params['page'] = page d = self.childrenRetriever(**self.childrenRetriever_params) d.addCallback(items_retrieved, page, start) return d
def all_items_retrieved(result): self.end_children_retrieval_campaign(True) return super(LazyContainer, self).get_children( start, request_count)
def error_while_retrieving_items(error): self.end_children_retrieval_campaign(False) return super(LazyContainer, self).get_children( start, request_count)
self.start_children_retrieval_campaign() if self.childrenRetriever is not None: d = self.retrieve_children(start) if start == 0: d.addCallbacks(all_items_retrieved, error_while_retrieving_items) return d else: self.end_children_retrieval_campaign() return self.children
# Check if an update is needed since last update current_time = time.time() delay_since_last_updated = current_time - self.last_updated period = self.refresh if (period > 0) and (delay_since_last_updated > period): self.info("Last update is older than %d s -> update data", period) self.childrenRetrievingNeeded = True
if self.childrenRetrievingNeeded is True: return self.retrieve_all_children(start, request_count) return Container.get_children(self, start, request_count)
return ROOT_CONTAINER_ID
return self.get_by_id(ROOT_CONTAINER_ID)
del self.store[item.storage_id] item.storage_id = -1 item.store = None
if isinstance(id, str): id = id.split('@', 1) id = id[0].split('.')[0] try: return self.store[int(id)] except (ValueError, KeyError): pass return None
return self.__class__.__name__ |