def _update_type(self): """Update the type of this Media object. If there's a video file, mark this as a video type, else fallback to audio, if possible, or unknown (None) """ if any(file.type == VIDEO for file in self.files): return VIDEO elif any(file.type == AUDIO for file in self.files): return AUDIO return None
def tree(self, depth=10, secret_key=None, **kwargs): """Query for an expanded tree of categories. :param id: A :attr:`mediacore.model.media.Category.id` to lookup the parent node :type id: int :param name: A :attr:`mediacore.model.media.Category.name` to lookup the parent node :type name: str :param slug: A :attr:`mediacore.model.media.Category.slug` to lookup the parent node :type slug: str :param depth: Number of level deep in children to expand. Defaults to 10. The maximum allowed value defaults to 10 and is set via :attr:`app_globals.settings['api_tree_max_depth']`. :type limit: int :param api_key: The api access key if required in settings :type api_key: unicode or None :returns: JSON dict """ if asbool(app_globals.settings['api_secret_key_required']) \ and secret_key != app_globals.settings['api_secret_key']: return dict(error='Authentication Error') if any(key in kwargs for key in ('id', 'slug', 'name')): kwargs['depth'] = depth kwargs['tree'] = True return self._get_query(**kwargs) return self._index_query(depth=depth, tree=True)
def media_player(media, is_widescreen=False, show_like=True, show_dislike=True, show_download=False, show_embed=False, show_playerbar=True, show_popout=True, show_resize=False, show_share=True, js_init=None, **kwargs): """Instantiate and render the preferred player that can play this media. We make no effort to pick the "best" player here, we simply return the first player that *can* play any of the URIs associated with the given media object. It's up to the user to declare their own preferences wisely. Player preferences are fetched from the database and the :attr:`mediacore.model.players.c.data` dict is passed as kwargs to :meth:`AbstractPlayer.__init__`. :type media: :class:`mediacore.model.media.Media` :param media: A media instance to play. :param js_init: Optional function to call after the javascript player controller has been instantiated. Example of a function literal: ``function(controller){ controller.setFillScreen(true); }``. Any function reference can be used as long as it is defined in all pages and accepts the JS player controller as its first and only argument. :param \*\*kwargs: Extra kwargs for :meth:`AbstractPlayer.__init__`. :rtype: `str` or `None` :returns: A rendered player. """ uris = media.get_uris() # Find the first player that can play any uris for player_cls, player_data in fetch_enabled_players(): can_play = player_cls.can_play(uris) if any(can_play): break else: return None # Grab just the uris that the chosen player can play playable_uris = [uri for uri, plays in izip(uris, can_play) if plays] kwargs['data'] = player_data player = player_cls(media, playable_uris, **kwargs) return render('players/html5_or_flash.html', { 'player': player, 'media': media, 'uris': uris, 'is_widescreen': is_widescreen, 'js_init': js_init, 'show_like': show_like, 'show_dislike': show_dislike, 'show_download': show_download, 'show_embed': show_embed, 'show_playerbar': show_playerbar, 'show_popout': show_popout, 'show_resize': show_resize and player.supports_resizing, 'show_share': show_share, })
def index(self, order=None, offset=0, limit=10, api_key=None, **kwargs): """Query for a flat list of categories. :param id: An :attr:`id <mediacore.model.media.Category.id>` for lookup :type id: int :param name: A :attr:`name <mediacore.model.media.Category.name>` for lookup :type name: str :param slug: A :attr:`slug <mediacore.model.media.Category.slug>` for lookup :type slug: str :param order: A column name and 'asc' or 'desc', seperated by a space. The column name can be any one of the returned columns. Defaults to newest category first (id desc). :type order: str :param offset: Where in the complete resultset to start returning results. Defaults to 0, the very beginning. This is useful if you've already fetched the first 50 results and want to fetch the next 50 and so on. :type offset: int :param limit: Number of results to return in each query. Defaults to 10. The maximum allowed value defaults to 50 and is set via :attr:`app_globals.settings['api_media_max_results']`. :type limit: int :param api_key: The api access key if required in settings :type api_key: unicode or None :rtype: JSON-ready dict :returns: The returned dict has the following fields: count (int) The total number of results that match this query. categories (list of dicts) A list of **category_info** dicts, as generated by the :meth:`_info <mediacore.controllers.api.categories.CategoriesController._info>` method. The number of dicts in this list will be the lesser of the number of matched items and the requested limit. """ if asbool(app_globals.settings['api_secret_key_required']) \ and api_key != app_globals.settings['api_secret_key']: return dict(error='Authentication Error') if any(key in kwargs for key in ('id', 'slug', 'name')): kwargs['offset'] = offset kwargs['limit'] = limit kwargs['tree'] = False return self._get_query(**kwargs) return self._index_query(order, offset, limit, tree=False)
def can_edit(item): """Return True if the logged in user is a part of the Admins group. NOTE: The item argument is provided for future use only. """ ident = request.environ.get('repoze.who.identity', {}) perms = ident.get('permissions', 0) return perms and any(perm.lower() == 'edit' for perm in perms)
def is_admin(): """Return True if the logged in user is a part of the Admins group. This method will need to be replaced when we improve our user access controls. """ groups = request.environ.get('repoze.who.identity', {}).get('groups', 0) return groups and any(group.lower() == 'admins' for group in groups)
def pick_players(self, sorted_uris, media, kwargs): """Initialize the unique players best able to play the given URIs. Players are given priority based first on their ability to play higher priority URIs, then by the preferred order as they were originally given. This means that a Flash player may jump ahead of an HTML5 player if the RTMP protocol is preferred over HTTP. We attempt to instantiate only one player of each logical type. In the simplest case, we want just one html5 player and one flash player, but this logic could also handle other player types such as java or silverlight. We make no assumptions about the types here, we just instantiate the highest priority player for each logical type provided by the able players. :type sorted_uris: tuple :param sorted_uris: StorageURIs, ordered by the priority we want them to play in. :type media: :class:`mediacore.model.media.Media` :param media: The media object that is being rendered, to be passed to all instantiated player objects. :type kwargs: dict :param kwargs: The options dict that is passed to the player class at instantiation time. :rtype list: :returns: Instantiated player objects. """ # Find all the players that can play any URI able_players = [] for player_cls in self.players: can_play = player_cls.can_play(sorted_uris) if not any(can_play): continue # Grab all URIs that this player can play uris = [uri for uri, plays in izip(sorted_uris, can_play) if plays] # Find the index of the first URI that can play for sorting below priority = ifilter(itemgetter(1), enumerate(can_play)).next()[0] able_players.append((player_cls, uris, priority)) # Reorder those players by the priority of the first file they can play able_players.sort(key=itemgetter(2)) players = [] covered_types = set() # Instantiate the highest priority players for every logical type for player_cls, player_uris, priority in able_players: player_types = player_cls.logical_types if player_types.difference(covered_types): covered_types.update(player_types) player = player_cls(media, player_uris, **kwargs) players.append(player) return players
def is_admin(): """Return True if the logged in user is a part of the Admins group. TODO: This method will need to be replaced when we improve our user access controls. :returns: Whether or not the current user is an Admin. :rtype: bool """ ident = request.environ.get('repoze.who.identity', {}) groups = ident.get('groups', 0) return groups and any(group.lower() == 'admins' for group in groups)
def _all_links(self): """ finds all tags with link attributes sequentially. safe against modification of said attributes in-place. """ start = self.root while True: tag = start.findNext(lambda tag: any([( tag.get(i) for i in self.settings['attrs_considered_links'])])) if tag: start = tag yield tag else: break
def can_edit(item): """Return True if the logged in user has the 'edit' permission. :param item: When we improve our user access controls, this will be used to check edit permissions on a particular object. TODO: 'item' is currently an unimplemented argument. :type item: unimplemented :returns: Whether the current user has the 'edit' permission. :rtype: bool """ ident = request.environ.get('repoze.who.identity', {}) perms = ident.get('permissions', 0) return perms and any(perm.lower() == 'edit' for perm in perms)
def index(self, order=None, offset=0, limit=10, secret_key=None, **kwargs): """Query for a flat list of categories. :param id: A :attr:`mediacore.model.media.Category.id` for lookup :type id: int :param name: A :attr:`mediacore.model.media.Category.name` for lookup :type name: str :param slug: A :attr:`mediacore.model.media.Category.slug` for lookup :type slug: str :param order: A column name and 'asc' or 'desc', seperated by a space. The column name can be any one of the returned columns. Defaults to newest category first (id desc). :param offset: Where in the complete resultset to start returning results. Defaults to 0, the very beginning. This is useful if you've already fetched the first 50 results and want to fetch the next 50 and so on. :type offset: int :param limit: Number of results to return in each query. Defaults to 10. The maximum allowed value defaults to 50 and is set via :attr:`app_globals.settings['api_media_max_results']`. :type limit: int :param api_key: The api access key if required in settings :type api_key: unicode or None :returns: JSON dict """ if asbool(app_globals.settings['api_secret_key_required']) \ and secret_key != app_globals.settings['api_secret_key']: return dict(error='Authentication Error') if any(key in kwargs for key in ('id', 'slug', 'name')): kwargs['offset'] = offset kwargs['limit'] = limit kwargs['tree'] = False return self._get_query(**kwargs) return self._index_query(order, offset, limit, tree=False)
def preferred_player_for_media(media, **kwargs): uris = media.get_uris() from mediacore.model.players import fetch_enabled_players # Find the first player that can play any uris for player_cls, player_data in fetch_enabled_players(): can_play = player_cls.can_play(uris) if any(can_play): break else: return None # Grab just the uris that the chosen player can play playable_uris = [uri for uri, plays in izip(uris, can_play) if plays] kwargs['data'] = player_data return player_cls(media, playable_uris, **kwargs)
def _all_links(self): """ finds all tags with link attributes sequentially. safe against modification of said attributes in-place. """ start = self.root while True: tag = start.findNext( lambda tag : any( [(tag.get(i) for i in self.settings['attrs_considered_links'])] )) if tag: start = tag yield tag else : break
def tree(self, depth=10, api_key=None, **kwargs): """Query for an expanded tree of categories. :param id: A :attr:`mediacore.model.media.Category.id` to lookup the parent node :type id: int :param name: A :attr:`mediacore.model.media.Category.name` to lookup the parent node :type name: str :param slug: A :attr:`mediacore.model.media.Category.slug` to lookup the parent node :type slug: str :param depth: Number of level deep in children to expand. Defaults to 10. The maximum allowed value defaults to 10 and is set via :attr:`app_globals.settings['api_tree_max_depth']`. :type limit: int :param api_key: The api access key if required in settings :type api_key: unicode or None :rtype: JSON-ready dict :returns: The returned dict has the following fields: count (int) The total number of results that match this query. categories (list of dicts) A list of **category_info** dicts, as generated by the :meth:`_info <mediacore.controllers.api.categories.CategoriesController._info>` method. Each of these dicts represents a category at the top level of the hierarchy. Each dict has also been modified to have an extra 'children' field, which is a list of **category_info** dicts representing that category's children within the hierarchy. """ if asbool(app_globals.settings['api_secret_key_required']) \ and api_key != app_globals.settings['api_secret_key']: return dict(error='Authentication Error') if any(key in kwargs for key in ('id', 'slug', 'name')): kwargs['depth'] = depth kwargs['tree'] = True return self._get_query(**kwargs) return self._index_query(depth=depth, tree=True)
def main(parser, options): status = 0 output = [] if options.dump_to: s, o = dump_backup_file(options.dump_to) status += s output.append(o.strip()) DBSession.commit() # Commit and start a new transaction if options.read_from: s, o = restore_backup_file(options.read_from) status += s output.append(o.strip()) DBSession.commit() # Commit and start a new transaction if options.dump_files_dir: s, o = backup_files(options.dump_files_dir) status += s output.append(o.strip()) if options.restore_files_dir: s, o = restore_files(options.restore_files_dir) status += s output.append(o.strip()) if not any((options.dump_to, options.read_from, options.dump_files_dir, options.restore_files_dir)): parser.print_help() print "" status, output = 1, ['Incorrect or insufficient arguments provided.\n'] # print output and exit sys.stdout.write("\n---\n".join(output)) print "" if status == 0: print "Operation completed successfully." else: print "Error occurred in operation. You can use the --debug flag for more information." print "" sys.exit(status)
def media_player(media, is_widescreen=False, show_like=True, show_dislike=True, show_download=False, show_embed=False, show_playerbar=True, show_popout=True, show_resize=False, show_share=True, js_init=None, **kwargs): """Instantiate and render the preferred player that can play this media. We make no effort to pick the "best" player here, we simply return the first player that *can* play any of the URIs associated with the given media object. It's up to the user to declare their own preferences wisely. Player preferences are fetched from the database and the :attr:`mediacore.model.players.c.data` dict is passed as kwargs to :meth:`AbstractPlayer.__init__`. :type media: :class:`mediacore.model.media.Media` :param media: A media instance to play. :param js_init: Optional function to call after the javascript player controller has been instantiated. Example of a function literal: ``function(controller){ controller.setFillScreen(true); }``. Any function reference can be used as long as it is defined in all pages and accepts the JS player controller as its first and only argument. :param \*\*kwargs: Extra kwargs for :meth:`AbstractPlayer.__init__`. :rtype: `str` or `None` :returns: A rendered player. """ uris = media.get_uris() # Find the first player that can play any uris for player_cls, player_data in fetch_enabled_players(): can_play = player_cls.can_play(uris) if any(can_play): break else: return None # Grab just the uris that the chosen player can play playable_uris = [uri for uri, plays in izip(uris, can_play) if plays] kwargs['data'] = player_data player = player_cls(media, playable_uris, **kwargs) return render( 'players/html5_or_flash.html', { 'player': player, 'media': media, 'uris': uris, 'is_widescreen': is_widescreen, 'js_init': js_init, 'show_like': show_like, 'show_dislike': show_dislike, 'show_download': show_download, 'show_embed': show_embed, 'show_playerbar': show_playerbar, 'show_popout': show_popout, 'show_resize': show_resize and player.supports_resizing, 'show_share': show_share, })
def has_permission(self, permission_name): return any(perm.permission_name == permission_name for perm in self.permissions)
def contains_only_whitespace(node): if is_tag(node): if not any([not is_text(s) for s in node.contents]): if not any([unicode(s).strip() for s in node.contents]): return True return False