"""
:mod:`Intersections` -- determine line intersections for polygons and lines
===========================================================================

.. module:: Intersections
    :synopsis: Functions to determine line intersections for polygons and
               line features.

.. moduleauthor:: Craig Arthur <craig.arthur@ga.gov.au>

"""
import math

def convert2vertex(a1, a2):
    """
    Converts 2 1D arrays into a list of :class:`Points`.

    :param a1: ordinate
    :param a2: abscissa

    :returns: List of :class:`Point` objects.

    """

    result = [Point(x, y) for x, y in zip(a1, a2)]
    return result

def inLand(P, V):
    """
    Test to see if a point is within the list of vertices.

    :param P: :class:`Point` object.
    :param V: List of :class:`Point` objects that represent vertices of
              the shape to be tested. Must be a closed set.

    :returns: ``True`` if the point lies inside the vertices, ``False``
              otherwise.
    :rtype: boolean

    """
    return _cnPnPoly(P, V) and _wnPnPoly(P, V)

def _cnPnPoly(P, V):
    """
    Crossing number test for a point in a polygon.

    :param P: :class:`Point` object.
    :param V: List of :class:`Point` objects that represent vertices of
              the shape to be tested. Must be a closed set.

    :returns: 0 if outside, 1 if inside the polygon.

    Copyright 2001, softSurfer (www.softsurfer.com)
    This code may be freely used and modified for any purpose
    providing that this copyright notice is included with it.
    SoftSurfer makes no warranty for this code, and cannot be held
    liable for any real or imagined damage resulting from its use.
    Users of this code must verify correctness for their application.
    """
    cn = 0    # the crossing number counter
    n = len(V) - 1
    # loop through all edges of the polygon
    for i in range(n):    # edge from V[i] to V[i+1]
        if (V[i].y <= P.y and V[i + 1].y > P.y) \
                or (V[i].y > P.y and V[i + 1].y <= P.y):   # a downward crossing
            # compute the actual edge-ray intersect x-coordinate
            vt = (P.y - V[i].y) / (V[i + 1].y - V[i].y)
            if P.x < V[i].x + vt * (V[i + 1].x - V[i].x):  # P.x < intersect
                cn += 1   # a valid crossing of y=P.y right of P.x
    return cn % 2 == 1  # 0 if even (out), and 1 if odd (in)

def _wnPnPoly(P, V):
    """
    Winding number test for a point in a polygon. The winding number
    is zero only if the point is outside the polygon.

    :param P: :class:`Point` object.
    :param V: List of :class:`Point` objects that represent vertices of
              the shape to be tested. Must be a closed set.

    :returns: 0 if outside, 1 if inside the polygon.

    Copyright 2001, softSurfer (www.softsurfer.com)
    This code may be freely used and modified for any purpose
    providing that this copyright notice is included with it.
    SoftSurfer makes no warranty for this code, and cannot be held
    liable for any real or imagined damage resulting from its use.
    Users of this code must verify correctness for their application.
    """
    wn = 0    # the winding number counter
    n = len(V) - 1
    # loop through all edges of the polygon
    for i in range(n):    # edge from V[i] to V[i+1]
        if V[i].y <= P.y:          # start y <= P.y
            if V[i + 1].y > P.y:      # an upward crossing
                if _isLeft(V[i], V[i + 1], P) > 0:  # P left of edge
                    wn += 1            # have a valid up intersect
            elif V[i + 1].y <= P.y:     # a downward crossing
                if _isLeft(V[i], V[i + 1], P) < 0:  # P right of edge
                    wn -= 1            # have a valid down intersect
    return wn != 0

def _isLeft(P0, P1, P2):
    """
    Tests if a point is Left|On|Right of an infinite line.

    :param P0: One :clas:`Point` on the line.
    :param P1: Second :class:`Point` on the line.
    :param P2: :class:`Point` to be tested.

    :returns: >0 for ``P2`` left of the line through ``P0`` and ``P1``
              =0 for ``P2`` on the line
              <0 for ``P2`` right of the line

    Copyright 2001, softSurfer (www.softsurfer.com)
    This code may be freely used and modified for any purpose
    providing that this copyright notice is included with it.
    SoftSurfer makes no warranty for this code, and cannot be held
    liable for any real or imagined damage resulting from its use.
    Users of this code must verify correctness for their application.
    """
    return (P1.x - P0.x) * (P2.y - P0.y) - (P2.x - P0.x) * (P1.y - P0.y)

class Intersection(object):

    """
    An Intersection object.

    :param str state: Initial state of the :class:`Intersection` (default ``None``).

    Parameters: None
    Members: status (string) and points (list)
    Methods: None
    Internal Methods: None

    """

    def __init__(self, state=None):
        """
        Initialise the members of the object
        """
        self.status = state
        self.points = []

class Crossings(object):

    """
    Determine if a a line intersects some other geometric feature
    (another line, a circle, a polygon).

    """

    def __init__(self):
        """
        Initialise required fields - none required
        """

    def CircleLine(self, c, r, a1, a2):
        """
        Determine the intersection points of a circle and a line segment.

        :param c: :class:`Point` object describing the centre of the circle.
        :param r: Eadius of the circle in map units.
        :param a1: :class:`Point` object describing the start of the line segment.
        :param a2: :class:`Point` object describing the end of the line segment.

        :returns: :class:`Intersection` object with the
                  :attr:`Intersection.status` updated. "Inside" means the line
                  segment is wholly contained within the circle; "Outside"
                  means the line segment is wholly outside the circle;
                  "Intersection" means the line intersects the circle. In this
                  final case, the :attr:`points` attribute of the
                  :class:`Intersection` object is populated with a
                  :class:`Point` object of the location of the intersection.

        """

        a = (a2.x - a1.x) * (a2.x - a1.x) + (a2.y - a1.y) * (a2.y - a1.y)
        b = 2. * ((a2.x - a1.x) * (a1.x - c.x) + (a2.y - a1.y) * (a1.y - c.y))
        cc = c.x * c.x + c.y * c.y + a1.x * a1.x + a1.y * a1.y - 2. * \
            (c.x * a1.x + c.y * a1.y) - r * r
        deter = b * b - 4. * a * cc

        if deter < 0.:
            result = Intersection("Outside")
        elif deter == 0.:
            result = Intersection("Tangent")
        else:
            e = math.sqrt(deter)
            u1 = (-b + e) / (2. * a)
            u2 = (-b - e) / (2. * a)
            if (u1 < 0. or u1 > 1.) and (u2 < 0. or u2 > 1.):
                if (u1 < 0. and u2 < 0.) or (u1 > 1. and u2 > 1.):
                    result = Intersection("Outside")
                else:
                    result = Intersection("Inside")
            else:
                result = Intersection("Intersection")
                if 0. <= u1 and u1 <= 1.:
                    p = self.lerp(a1, a2, u1)
                    result.points.append(Point(p[0], p[1]))
                if 0. <= u2 and u2 <= 1.:
                    p = self.lerp(a1, a2, u2)
                    result.points.append(Point(p[0], p[1]))

        return result

    def CirclePolygon(self, c, r, points):
        """
        Determine the intersection points of a circle and a polygon.
        Uses :func:`Crossings.CircleLine` on each line segment in the
        polygon to determine if the two features intersect.

        :param c: :class:`Point` representing the centre of the circle.
        :param r: Radius of the circle in map units.
        :paran points: Array of :class:`Point` objects representing the
                       polygon.

        :returns: :class:`Intersection` object with updated status and points
                  attributes.
        """

        result = Intersection("No Intersection")
        if isinstance(points, list):
            for p in points:
                for i in range(len(p) - 1):
                    a1 = p[i]
                    a2 = p[i - 1]
                    inter = self.CircleLine(c, r, a1, a2)
                    if inter.status == "Intersection":
                        result.points.append(inter.points)
                        result.status = "Intersection"
        else:
            for i in range(len(points) - 1):
                a1 = points[i]
                a2 = points[i + 1]
                inter = self.CircleLine(c, r, a1, a2)
                if inter.status == "Intersection":
                    result.points.append(inter.points)
                    result.status = "Intersection"
        # if ( len(result.points) > 0. ):

        return result

    def lerp(self, a1, a2, u):
        """
        Linear interpolation between two points:

        :param a1: First :class:`Point`.
        :param a2: Second :class:`Point`.
        :param u: Fractional distance along the line between the two points.

        :return: Coordinates of the interpolated point as a tuple.
        """
        return (a1.x + (a2.x - a1.x) * u, a1.y + (a2.y - a1.y) * u)

    def LineLine(self, a1, a2, b1, b2):
        """
        Determine if two line segments intersect.

        :param a1: Starting :class:`Point` of line 1.
        :param a2: Ending :class:`Point` of line 1.
        :param b1: Starting :class:`Point` of line 2.
        :param b2: Ending :class:`Point` of line 2.

        :returns: :class:`Intersection` object with :attr:`status` set to
                  ``Intersection`` if the lines intersect, ``Coincident``
                  if the lines overlap, ``Parallel`` if the lines are
                  parallel or ``No Intersection`` if the lines do not
                  intersect. If the lines intersect, then the
                  :attr:`points` attribute is set to the location of the
                  intersection.

        """

        ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x)
        ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x)
        u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y)

        if u_b != 0:
            ua = ua_t / u_b
            ub = ub_t / u_b

            if 0 <= ua and ua <= 1 and 0 <= ub and ub <= 1:
                result = Intersection("Intersection")
                result.points.append(Point(a1.x + ua * (a2.x - a1.x),
                                           a1.y + ua * (a2.y - a1.y)))
            else:
                result = Intersection("No Intersection")
        else:
            if ua_t == 0 or ub_t == 0:
                result = Intersection("Coincident")
            else:
                result = Intersection("Parallel")

        return result

    def LinePolygon(self, a1, a2, points):
        """
        Determine if a line intersects a polygon.

        :param a1: Starting :class:`Point` of the line.
        :param a2: Ending :class:`Point` of the line.
        :param points: Collection of :class:`Point` objects that
                       represent the vertices of a polygon.

        """
        result = Intersection("No Intersection")
        if isinstance(points, list):
            for p in points:
                for i in range(len(p) - 1):
                    b1 = p[i]
                    b2 = p[i + 1]
                    inter = self.LineLine(a1, a2, b1, b2)
                    result.points.append(inter.points)
        else:
            for i in range(len(points) - 1):
                b1 = points[i]
                b2 = points[i + 1]
                inter = self.LineLine(a1, a2, b1, b2)
                result.points.append(inter.points)

        if len(result.points) > 0:
            result.status = "Intersection"

        return result

class Point(object):

    """
    Class representation for a Point
    Contains x and y members
    Created by Geoff Xu, 2006
    """

    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def getX(self):
        return self.x

    def getY(self):
        return self.y


import ee
import ipyleaflet
from ipyleaflet import TileLayer
from traitlets import default
from traitlets import Instance
from traitlets import Unicode

ee.Initialize()

def getTileLayerUrl(map_id):
  template = "https://earthengine.googleapis.com/map/{mapid}/{{z}}/{{x}}/{{y}}?token={token}"
  return template.format(**map_id)

class TileLayerEE(ipyleaflet.TileLayer):
    map_id = (
      ee.Image('NOAA/NGDC/ETOPO1')
        .select('bedrock')
        .sldStyle("""
          <RasterSymbolizer>\
            <ColorMap>\
              <ColorMapEntry color="#000033" quantity="-8000" label="deep" />\
              <ColorMapEntry color="#aaaaaa" quantity="-1" label="shallow" />\
              <ColorMapEntry color="#000000" quantity="0" label="Land" />\
              <ColorMapEntry color="#FFFFFF" quantity="4000" label="Land" />\
            </ColorMap>\
          </RasterSymbolizer>
        """).getMapId()
    )

    url = Unicode(
        "https://earthengine.googleapis.com/map/{mapid}/{{z}}/{{x}}/{{y}}?token={token}".format(**map_id)
    ).tag(sync=True)
    attribution = Unicode('Map data NOAA').tag(sync=True, o=True)

class Map(ipyleaflet.Map):

    default_tiles = Instance(TileLayerEE, allow_none=True)

    @default('default_tiles')
    def _default_tiles(self):
        return TileLayerEE()

    def __init__(self, **kwargs):
        super(Map, self).__init__(**kwargs)
        self.on_displayed(self._fire_children_displayed)
        if self.default_tiles is not None:
            self.layers = (self.default_tiles,)
        self.on_msg(self._handle_leaflet_event)


import datetime

from django import forms

from animal.models import Animal, SavedAnimal, MedicalExamination

class BaseAnimalForm(forms.ModelForm):
    class Meta:
        model = Animal
        exclude = ['owner', 'medical_history']

class CreateAnimalForm(BaseAnimalForm):
    pass

class EditAnimalForm(BaseAnimalForm):
    pass

class DeleteAnimalForm(BaseAnimalForm):
    class Meta:
        model = Animal
        fields = []

    def save(self, commit=True):
        if commit:
            self.instance.delete()

        return self.instance

def get_free_hours(date):
    available_hours = [hour for hour in range(9, 19)
                       if hour != 12 and not SavedAnimal.objects.filter(review_date=date, review_hour=hour).exists()]
    return available_hours

class SavedAnimalForm(forms.ModelForm):
    class Meta:
        model = SavedAnimal
        fields = ['review_date', 'review_hour', 'review_type', 'description']

        widgets = {
            'review_date': forms.DateInput(attrs={'type': 'date'}),
        }

    def clean_review_hour(self):
        review_date = self.cleaned_data.get('review_date')
        review_hour = self.cleaned_data.get('review_hour')

        existing_reviews = SavedAnimal.objects.filter(
            review_date=review_date,
            review_hour=review_hour,
        )

        available_hours = get_free_hours(review_date)

        if existing_reviews.exists():
            raise forms.ValidationError(
                f"The selected hour ({review_hour}) is already booked for this date. "
                f"Available hours for {review_date} are: {', '.join(map(str, available_hours))}."
            )

        if not review_hour:
            raise forms.ValidationError("Select hour for review.")

        return review_hour

    def clean_review_date(self):
        review_date = self.cleaned_data.get('review_date')
        if review_date:
            if review_date.weekday() in [5, 6]:
                raise forms.ValidationError("You cannot book on weekends (Saturday or Sunday).")

            if review_date < datetime.date.today():
                raise forms.ValidationError("You cannot book a past date for review.")

            reservations_count = SavedAnimal.objects.filter(review_date=review_date).count()
            if reservations_count >= 9:
                raise forms.ValidationError("The maximum number of reservations for this date has been reached."
                                            "Please choose another date.")
        return review_date

class EditSaveAnimalForm(SavedAnimalForm):
    pass

class ExaminationForm(forms.ModelForm):
    class Meta:
        model = MedicalExamination
        exclude = ['user', 'animal']


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 11:19:13 2018

@author: rohit
"""

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://wwww.facebook.com')
driver.implicitly_wait(3)
driver.execute_script("window.open('http://www.twitter.com','new window')")


import asyncio
import os.path
from concurrent.futures import ThreadPoolExecutor
from csv import DictWriter
from datetime import datetime
import gzip
import traceback

class NamedTupleCSVWriter:
    def __init__(self,tuple_type,filename_mask,use_gzip = False):
        self._fields = list(tuple_type._fields)
        self._last_filename = None
        self._filename_mask = filename_mask
        self._file_opened = None
        self._dict_writer = None
        self._header_written = False
        self._use_gzip = use_gzip

    def _ensure_file_opened(self):
        dt = datetime.now()
        actual_filename = dt.strftime(self._filename_mask)
        if self._file_opened is None or actual_filename != self._last_filename:
            self._last_filename = actual_filename
            self._header_written = os.path.exists(actual_filename)

            if not self._file_opened is None:
                self._file_opened.close()
            if self._use_gzip:
                self._file_opened = gzip.open(actual_filename,'at')
            else:
                self._file_opened = open(actual_filename,'a')

            self._dict_writer = DictWriter(self._file_opened, self._fields)

    def put_event(self,tuple):
        self._ensure_file_opened()
        row_contents = dict()
        for field in self._fields:
            row_contents[field] = getattr(tuple,field)

        if not self._header_written:
            self._header_written = True
            self._dict_writer.writeheader()

        self._dict_writer.writerow(row_contents)

    def __call__(self,tuple):
        self.put_event(tuple)

    def close(self):
        if not self._file_opened is None:
            self._file_opened.close()
            self._file_opened = None

class CSVWritersContext:
    def __init__(self):
        self._accounted_writers = list()

    def open(self,tuple_type,filename_mask,use_gzip = False):
        writer = NamedTupleCSVWriter(tuple_type, filename_mask, use_gzip = use_gzip)
        self._accounted_writers.append(writer)

        return writer

    def close(self,writer):
        writer.close()
        self._accounted_writers.remove(writer)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tcb):
        for writer in self._accounted_writers:
            try:
                writer.close()
            except:
                traceback.print_exc()

class AsyncNamedTupleCSVWriter:
    def __init__(self,wrapped_writter,executor = None):
        self._blocking_writer = wrapped_writter
        self._executor = executor

    async def put_event(self,tuple):
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(self._executor,lambda:self._blocking_writer.put_event(tuple))

    async def close(self):
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(self._executor,lambda:self._blocking_writer.close())

class AsyncCSVWritersContext:
    def __init__(self):
        self._blocking_writers_context = CSVWritersContext()
        self._executor = ThreadPoolExecutor(thread_name_prefix = "CSV Writer Threads")

    async def open(self,tuple_type,filename_mask,use_gzip = False):
        blocking_writer = self._blocking_writers_context.open(tuple_type,filename_mask,use_gzip)
        return AsyncNamedTupleCSVWriter(blocking_writer,self._executor)

    async def close(self,writer):
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(self._executor,self._blocking_writers_context.close(writer._blocking_writer))

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_value, tcb):
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(self._executor,lambda:self._blocking_writers_context.__exit__(exc_type, exc_value, tcb))

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tcb):
        self._blocking_writers_context.__exit__(exc_type, exc_value, tcb)


from enigma import eTimer, iServiceInformation, iPlayableService, ePicLoad, RT_VALIGN_CENTER, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, gFont, eListbox, ePoint, eListboxPythonMultiContent, eServiceCenter, getDesktop
from Components.MenuList import MenuList
from Screens.Screen import Screen
from Screens.ServiceInfo import ServiceInfoList, ServiceInfoListEntry
from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
from Components.Pixmap import Pixmap
from Components.Label import Label
from Screens.ChoiceBox import ChoiceBox
from ServiceReference import ServiceReference
from Components.Button import Button
from Components.ScrollLabel import ScrollLabel
from Components.Sources.List import List
from Screens.MessageBox import MessageBox
from Screens.HelpMenu import HelpableScreen
from twisted.internet import reactor, defer
from twisted.web import client
from twisted.web.client import HTTPClientFactory, downloadPage
from Components.ServiceEventTracker import ServiceEventTracker
from Components.Playlist import PlaylistIOInternal, PlaylistIOM3U, PlaylistIOPLS
from Components.ConfigList import ConfigList, ConfigListScreen
from Components.config import *
from Tools.Directories import resolveFilename, fileExists, pathExists, createDir, SCOPE_MEDIA, SCOPE_PLAYLIST, SCOPE_SKIN_IMAGE
from MC_Filelist import FileList
from Screens.InfoBarGenerics import InfoBarSeek
import os
from os import path as os_path, remove as os_remove, listdir as os_listdir
from __init__ import _
config.plugins.mc_ap = ConfigSubsection()
sorts = [('default',_("default")),('alpha',_("alphabet")), ('alphareverse',_("alphabet backward")),('date',_("date")),('datereverse',_("date backward")),('size',_("size")),('sizereverse',_("size backward"))]
config.plugins.mc_ap_sortmode = ConfigSubsection()
config.plugins.mc_ap_sortmode.enabled = ConfigSelection(sorts)
config.plugins.mc_ap.showJpg = ConfigYesNo(default=True)
config.plugins.mc_ap.jpg_delay = ConfigInteger(default=10, limits=(5, 999))
config.plugins.mc_ap.repeat = ConfigSelection(default="off", choices = [("off", "off"),("single", "single"),("all", "all")])
config.plugins.mc_ap.lastDir = ConfigText(default=resolveFilename(SCOPE_MEDIA))
screensaverlist = [('default',_("default"))]
hddpath="/hdd/saver/"
if pathExists(hddpath):
	files = os_listdir(hddpath)
	for x in files:
		if pathExists(hddpath + x):
			screensaverlist += [(hddpath +'%s/' % (x),_("%s") % (x))]
config.plugins.mc_ap.whichjpg = ConfigSelection(screensaverlist)
playlist = []
#try:
#	from enigma import evfd
#except Exception, e:
#	print "Media Center: Import evfd failed"
radirl = 'http://dev.nachtfalke.biz/nfr/downloads/bmcradio/Radiolist/'
#for lyrics
def getEncodedString(value):
	returnValue = ""
	try:
		returnValue = value.encode("utf-8", 'ignore')
	except UnicodeDecodeError:
		try:
			returnValue = value.encode("iso8859-1", 'ignore')
		except UnicodeDecodeError:
			try:
				returnValue = value.decode("cp1252").encode("utf-8")
			except UnicodeDecodeError:
				returnValue = "n/a"
	return returnValue
class myHTTPClientFactory(HTTPClientFactory):
	def __init__(self, url, method='GET', postdata=None, headers=None,
	agent="SHOUTcast", timeout=0, cookies=None,
	followRedirect=1, lastModified=None, etag=None):
		HTTPClientFactory.__init__(self, url, method=method, postdata=postdata,
		headers=headers, agent=agent, timeout=timeout, cookies=cookies,followRedirect=followRedirect)
def sendUrlCommand(url, contextFactory=None, timeout=50, *args, **kwargs):
	scheme, host, port, path = client._parse(url)
	factory = myHTTPClientFactory(url, *args, **kwargs)
	reactor.connectTCP(host, port, factory, timeout=timeout)
	return factory.deferred
mcpath = "/usr/lib/enigma2/python/Plugins/Extensions/BMediaCenter/"
def PlaylistEntryComponent(serviceref):
	res = [ serviceref ]
	text = serviceref.getName()
	if text == "":
		text = os_path.split(serviceref.getPath().split('/')[-1])[1]
	res.append((eListboxPythonMultiContent.TYPE_TEXT,25, 1, 470, 22, 0, RT_VALIGN_CENTER, text))
	return res
class PlayList(MenuList):
	def __init__(self, enableWrapAround = False):
		MenuList.__init__(self, playlist, enableWrapAround, eListboxPythonMultiContent)
		self.l.setFont(0, gFont("Regular", 15))
		self.l.setItemHeight(23)
		MC_AudioPlayer.currPlaying = -1
		self.oldCurrPlaying = -1
		self.serviceHandler = eServiceCenter.getInstance()
	def clear(self):
		del self.list[:]
		self.l.setList(self.list)
		MC_AudioPlayer.currPlaying = -1
		self.oldCurrPlaying = -1
	def getSelection(self):
		return self.l.getCurrentSelection()[0]
	def addFile(self, serviceref):
		self.list.append(PlaylistEntryComponent(serviceref))
	def updateFile(self, index, newserviceref):
		if index < len(self.list):
			self.list[index] = PlaylistEntryComponent(newserviceref, STATE_NONE)
	def deleteFile(self, index):
		if MC_AudioPlayer.currPlaying >= index:
			MC_AudioPlayer.currPlaying -= 1
		del self.list[index]
	def setCurrentPlaying(self, index):
		self.oldCurrPlaying = MC_AudioPlayer.currPlaying
		MC_AudioPlayer.currPlaying = index
		self.moveToIndex(index)
	def updateState(self, state):
		if len(self.list) > self.oldCurrPlaying and self.oldCurrPlaying != -1:
			self.list[self.oldCurrPlaying] = PlaylistEntryComponent(self.list[self.oldCurrPlaying][0], STATE_NONE)
		if MC_AudioPlayer.currPlaying != -1 and MC_AudioPlayer.currPlaying < len(self.list):
			self.list[MC_AudioPlayer.currPlaying] = PlaylistEntryComponent(self.list[MC_AudioPlayer.currPlaying][0], state)
		self.updateList()
	def playFile(self):
		self.updateState(STATE_PLAY)
	def pauseFile(self):
		self.updateState(STATE_PAUSE)
	def stopFile(self):
		self.updateState(STATE_STOP)
	def rewindFile(self):
		self.updateState(STATE_REWIND)
	def forwardFile(self):
		self.updateState(STATE_FORWARD)
	GUI_WIDGET = eListbox
	def updateList(self):
		self.l.setList(self.list)
	def getCurrentIndex(self):
		return MC_AudioPlayer.currPlaying
	def getCurrentEvent(self):
		l = self.l.getCurrentSelection()
		return l and self.serviceHandler.info(l[0]).getEvent(l[0])
	def getCurrent(self):
		l = self.l.getCurrentSelection()
		return l and l[0]
	def getServiceRefList(self):
		return [ x[0] for x in self.list ]
	def __len__(self):
		return len(self.list)
class MC_AudioPlayer(Screen, HelpableScreen, InfoBarSeek):
	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")
		self.jpgList = []
		self.jpgIndex = 0
		self.jpgLastIndex = -1
		self.isVisible = True
		self.coverArtFileName = ""
		self["fileinfo"] = Label()
		self["text"] = Label(_("Lyrics"))
		self["coverArt"] = MediaPixmap()
		self["currentfolder"] = Label()
		self["currentfavname"] = Label()
		self.standardInfoBar = False
		try:
			if config.av.downmix_ac3.value == False:
				config.av.downmix_ac3.value = True
				config.av.downmix_ac3.save()
				os.system("touch /tmp/.ac3on")
		except Exception as e:
			print ("Media Center: no ac3")
		self["play"] = Pixmap()
		self["green"] = Pixmap()
		self["screensaver"] = MediaPixmap()
		self.PlaySingle = 0
		MC_AudioPlayer.STATE = "NONE"
		lstdir = []
		self.playlist = PlayList()
		MC_AudioPlayer.playlistplay = 0
		MC_AudioPlayer.currPlaying = -1
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evEOF: self.doEOF,
				iPlayableService.evStopped: self.StopPlayback,
				iPlayableService.evUser+11: self.__evDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt,
				iPlayableService.evUser+14: self["screensaver"].screensaver
			})
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions",
			{
				"ok": (self.KeyOK, "Play selected file"),
				"playpause": (self.PlayPause, "Play / Pause"),
				"cancel": (self.Exit, "Exit Audio Player"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"menu": (self.showMenu, "File / Folder Options"),
				"video": (self.visibility, "Show / Hide Player"),
				"info": (self.showLyrics, "Lyrics"),
				"stop": (self.StopPlayback, "Stop Playback"),
				"red": (self.Playlists, "Playlists"),
				"green": (self.Repeat, "Repeat"),
				"yellow": (self.addFiletoPls, "Add file to playlist"),
				"blue": (self.Settings, "Settings"),
				"next": (self.KeyNext, "Next song"),
				"previous": (self.KeyPrevious, "Previous song"),
			}, -2)

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")
		currDir = config.plugins.mc_ap.lastDir.value
		if not pathExists(currDir):
			currDir = "/"
		sort = config.plugins.mc_ap_sortmode.enabled.value
		self["currentfolder"].setText(str(currDir))
		self.filelist = []
		self["filelist"] = []
		inhibitDirs = ["/bin", "/boot", "/dev", "/dev.static", "/etc", "/lib" , "/proc", "/ram", "/root" , "/sbin", "/sys", "/tmp", "/usr", "/var"]
		self.filelist = FileList(currDir, useServiceRef = True, showDirectories = True, showFiles = True, matchingPattern = "(?i)^.*\.(mp2|mp3|wav|wave|wma|m4a|ogg|ra|flac|m3u|pls|e2pls)", inhibitDirs = inhibitDirs, sort = sort)
		self["filelist"] = self.filelist
		self["filelist"].show()
		self.JpgTimer = eTimer()
		self.JpgTimer.callback.append(self.showBackgroundJPG)
		self.getJPG()
		self.FileInfoTimer = eTimer()
		self.FileInfoTimer.callback.append(self.updateFileInfo)
		self.onLayoutFinish.append(self.updategreen)
	def Repeat(self):
		if config.plugins.mc_ap.repeat.value == "off":
			config.plugins.mc_ap.repeat.value = "single"
			self["green"].instance.setPixmapFromFile(mcpath +"icons/repeatonegreen.png")
		elif config.plugins.mc_ap.repeat.value == "single":
			config.plugins.mc_ap.repeat.value = "all"
			self["green"].instance.setPixmapFromFile(mcpath +"icons/repeatallgreen.png")
		else:
			config.plugins.mc_ap.repeat.value = "off"
			self["green"].instance.setPixmapFromFile(mcpath +"icons/repeatoffgreen.png")
		config.plugins.mc_ap.save()
	def updategreen(self):
		if config.plugins.mc_ap.repeat.value == "all":
			self["green"].instance.setPixmapFromFile(mcpath +"icons/repeatallgreen.png")
		elif config.plugins.mc_ap.repeat.value == "single":
			self["green"].instance.setPixmapFromFile(mcpath +"icons/repeatonegreen.png")
		else:
			return
	def unlockShow(self):
		return
	def lockShow(self):
		return
	def up(self):
		self["filelist"].up()
#		if config.plugins.mc_global.vfd.value == "on":
#			evfd.getInstance().vfd_write_string(self["filelist"].getName())
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def down(self):
		self["filelist"].down()
#		if config.plugins.mc_global.vfd.value == "on":
#			evfd.getInstance().vfd_write_string(self["filelist"].getName())
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def leftUp(self):
		self["filelist"].pageUp()
#		if config.plugins.mc_global.vfd.value == "on":
#			evfd.getInstance().vfd_write_string(self["filelist"].getName())
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def rightDown(self):
		self["filelist"].pageDown()
#		if config.plugins.mc_global.vfd.value == "on":
#			evfd.getInstance().vfd_write_string(self["filelist"].getName())
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def KeyOK(self):
		if self["filelist"].canDescent():
			if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
			self.filelist.descent()
			self["currentfolder"].setText(str(self.filelist.getCurrentDirectory()))
		else:
			if self.filelist.getServiceRef().type == 4098: # playlist
				ServiceRef = self.filelist.getServiceRef()
				extension = ServiceRef.getPath()[ServiceRef.getPath().rfind('.') + 1:]
				if extension in self.playlistparsers:
					self.playlist.clear()
					playlist = self.playlistparsers[extension]()
					list = playlist.open(ServiceRef.getPath())
					for x in list:
						self.playlist.addFile(x.ref)
				self.playlist.updateList()
				MC_AudioPlayer.currPlaying = 0
				self.PlayServicepls()
			else:
				self.PlaySingle = 1
				self.PlayService()
	def PlayPause(self):
		if MC_AudioPlayer.STATE == "PLAY":
			service = self.session.nav.getCurrentService()
			pausable = service.pause()
			pausable.pause()
			MC_AudioPlayer.STATE = "PAUSED"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/pause_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		elif MC_AudioPlayer.STATE == "PAUSED":
			service = self.session.nav.getCurrentService()
			pausable = service.pause()
			pausable.unpause()
			MC_AudioPlayer.STATE = "PLAY"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		else:
			self.KeyOK()
	def KeyNext(self):
		if MC_AudioPlayer.STATE != "NONE":
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
			if MC_AudioPlayer.playlistplay == 1:
				next = self.playlist.getCurrentIndex() + 1
				if next < len(self.playlist):
					MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying + 1
				else:
					MC_AudioPlayer.currPlaying = 0
				self.PlayServicepls()
			else:
				self.down()
				self.PlayService()
	def KeyPrevious(self):
		if MC_AudioPlayer.STATE != "NONE":
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
			if MC_AudioPlayer.playlistplay == 1:
				next = self.playlist.getCurrentIndex() - 1
				if next != -1:
					MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying - 1
				else:
					MC_AudioPlayer.currPlaying = 0
				self.PlayServicepls()
			else:
				self.up()
				self.PlayService()
	def visibility(self, force=1):
		if self.isVisible == True:
			self.isVisible = False
			self.hide()
		else:
			self.isVisible = True
			self.show()
	def Playlists(self):
		self.session.openWithCallback(self.updd, MC_AudioPlaylist)
	def updd(self):
		self.updateFileInfo()
		sort = config.plugins.mc_ap_sortmode.enabled.value
		self.filelist.refresh(sort)
		if MC_AudioPlayer.STATE == "PLAY":
			self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		elif MC_AudioPlayer.STATE == "PAUSED":
			self["play"].instance.setPixmapFromFile(mcpath +"icons/pause_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		elif MC_AudioPlayer.STATE == "NONE":
			self["play"].instance.setPixmapFromFile(mcpath +"icons/stop_enabled.png")
		else:
			return
	def PlayService(self):
		playlistplay = 0
		self.JpgTimer.stop()
		self.session.nav.playService(self["filelist"].getServiceRef())
		MC_AudioPlayer.STATE = "PLAY"
		self.FileInfoTimer.start(2000, True)
		self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
		path = self["filelist"].getCurrentDirectory()
		self["coverArt"].updateCoverArt(path)
		if config.plugins.mc_ap.showJpg.value:
			time = config.plugins.mc_ap.jpg_delay.value * 1000
			self.JpgTimer.start(time, True)
	def PlayServicepls(self):
		MC_AudioPlayer.playlistplay = 1
		x = self.playlist.getCurrentIndex()
		x = len(self.playlist)
		self.session.nav.playService(self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()])
		MC_AudioPlayer.STATE = "PLAY"
		self.FileInfoTimer.start(2000, True)
		self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
		if config.plugins.mc_ap.showJpg.value:
			time = config.plugins.mc_ap.jpg_delay.value * 1000
			self.JpgTimer.start(time, True)
		#path = self["filelist"].getCurrentDirectory() + self["filelist"].getFilename()
		#self["coverArt"].updateCoverArt(path)
	def StopPlayback(self):
		if self.isVisible == False:
			self.show()
			self.isVisible = True
		if self.session.nav.getCurrentService() is None:
			return
		else:
			self.session.nav.stopService()
			if config.plugins.mc_ap.showJpg.value:
				self.JpgTimer.stop()
				self["screensaver"].showDefaultCover()
			MC_AudioPlayer.STATE = "NONE"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/stop_enabled.png")
	def JumpToFolder(self, jumpto = None):
		if jumpto is None:
			return
		else:
			self["filelist"].changeDir(jumpto)
			self["currentfolder"].setText(("%s") % (jumpto))
	def updateFileInfo(self):
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sComment = currPlay.info().getInfoString(iServiceInformation.sTagComment)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)
			if sTitle == "":
				sTitle = currPlay.info().getName().split('/')[-1]
			self["fileinfo"].setText(_("Title: ") + sTitle + _("\nArtist: ") + sArtist + _("\nAlbum: ") + sAlbum + _("\nYear: ") + sYear + _("\nGenre: ") + sGenre + _("\nComment: ") + sComment)
	def addFiletoPls(self):
		if self.filelist.canDescent():
			x = self.filelist.getName()
			if x == "..":
				return
			self.addDirtoPls(self.filelist.getSelection()[0])
		elif self.filelist.getServiceRef().type == 4098: # playlist
			ServiceRef = self.filelist.getServiceRef()
			extension = ServiceRef.getPath()[ServiceRef.getPath().rfind('.') + 1:]
			if extension in self.playlistparsers:
				playlist = self.playlistparsers[extension]()
				list = playlist.open(ServiceRef.getPath())
				for x in list:
					self.playlist.addFile(x.ref)
				self.playlist.updateList()
		else:
			self.playlist.addFile(self.filelist.getServiceRef())
			self.playlist.updateList()
	def addDirtoPls(self, directory, recursive = True):
		if directory == '/':
			return
		filelist = FileList(directory, useServiceRef = True, showMountpoints = False, isTop = True)
		for x in filelist.getFileList():
			if x[0][1] == True: #isDir
				#if recursive:
				#	if x[0][0] != directory:
				#		self.playlist.addFile(x[0][1])
				return
			elif filelist.getServiceRef() and filelist.getServiceRef().type == 4097:
				self.playlist.addFile(x[0][0])
		self.playlist.updateList()
	def deleteFile(self):
		self.service = self.filelist.getServiceRef()
		if self.service.type != 4098 and self.session.nav.getCurrentlyPlayingServiceOrGroup() is not None:
			if self.service == self.session.nav.getCurrentlyPlayingServiceOrGroup():
				self.StopPlayback()
		self.session.openWithCallback(self.deleteFileConfirmed, MessageBox, _("Do you really want to delete this file ?"))
	def deleteFileConfirmed(self, confirmed):
		if confirmed:
			delfile = self["filelist"].getFilename()
			os.remove(delfile)
			sort = config.plugins.mc_ap_sortmode.enabled.value
			self.filelist.refresh(sort)
	def deleteDir(self):
		self.session.openWithCallback(self.deleteDirConfirmed, MessageBox, _("Do you really want to delete this directory and it's content ?"))
	def deleteDirConfirmed(self, confirmed):
		if confirmed:
			import shutil
			deldir = self.filelist.getSelection()[0]
			shutil.rmtree(deldir)
			sort = config.plugins.mc_ap_sortmode.enabled.value
			self.filelist.refresh(sort)
	def getJPG(self):
		if config.plugins.mc_ap.whichjpg.value == "default":
			path = mcpath +"saver/"
		else:
			path = config.plugins.mc_ap.whichjpg.value
		for root, dirs, files in os.walk(path):
			for name in files:
				if name.endswith(".jpg"):
					self.jpgList.append(name)
	def showBackgroundJPG(self):
		if len(self.jpgList) > 0:
			if self.jpgIndex < len(self.jpgList) -1:
				self.jpgIndex += 1
			else:
				self.jpgIndex = 0
			print ("MediaCenter: Last JPG Index: " + str(self.jpgLastIndex))
			if self.jpgLastIndex != self.jpgIndex or self.jpgLastIndex == -1:
				if config.plugins.mc_ap.whichjpg.value == "default":
					path = mcpath +"saver/" + self.jpgList[self.jpgIndex]
				else:
					path = config.plugins.mc_ap.whichjpg.value + self.jpgList[self.jpgIndex]
				self["screensaver"].screensaver(path)
				self.jpgLastIndex = self.jpgIndex
				time = config.plugins.mc_ap.jpg_delay.value * 1000
				self.JpgTimer.start(time, True)
		else:
			print ("MediaCenter: No Background Files found ...")
	def doEOF(self):
		if MC_AudioPlayer.playlistplay == 1:
			next = self.playlist.getCurrentIndex() + 1
			if next < len(self.playlist):
				MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying + 1
				self.PlayServicepls()
		elif config.plugins.mc_ap.repeat.value == "single":
			self.StopPlayback()
			self.PlayService()
		elif config.plugins.mc_ap.repeat.value == "all":
			self.down()
			if self.filelist.getName() == "..":
				self.down()
				self.checkisdir()
			self.PlayService()
		else:
			self.down()
			self.PlayService()
	def checkisdir(self):
		if self["filelist"].canDescent():
			self.down()
			self.checkisdir()
		else:
			self.PlayService()
	def __evDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sVideoType = currPlay.info().getInfoString(iServiceInformation.sVideoType)
		self.session.open(MessageBox, _("This Dreambox can't decode %s video streams!") % sVideoType, type = MessageBox.TYPE_INFO,timeout = 20 )
	def __evPluginError(self):
		currPlay = self.session.nav.getCurrentService()
		message = currPlay.info().getInfoString(iServiceInformation.sUser+12)
		self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )
	def addPlaylistParser(self, parser, extension):
		self.playlistparsers[extension] = parser
	def Shuffle(self):
		if self.currPlaying == 1:
			return
		sort = "shuffle"
		self.filelist.refresh(sort)
	def showMenu(self):
		menu = []
		menu.append((_("shuffle"), "shuffle"))
		if self.filelist.canDescent():
			x = self.filelist.getName()
			if x == "..":
				return
			menu.append((_("add directory to playlist"), "copydir"))
			menu.append((_("delete directory"), "deletedir"))
		else:
			menu.append((_("add file to playlist"), "copyfile"))
			menu.append((_("add file to playlist and play"), "copyandplay"))
			menu.append((_("add all files in directory to playlist"), "copyfiles"))
			menu.append((_("delete file"), "deletefile"))
		self.session.openWithCallback(self.menuCallback, ChoiceBox, title="", list=menu)
	def menuCallback(self, choice):
		if choice is None:
			return
		if choice[1] == "copydir":
			self.addDirtoPls(self.filelist.getSelection()[0])
		elif choice[1] == "deletedir":
			self.deleteDir()
		elif choice[1] == "copyfile":
			self.addFiletoPls()
		elif choice[1] == "copyandplay":
			self.addFiletoPls()
			MC_AudioPlayer.currPlaying = len(self.playlist) - 1
			self.PlayServicepls()
		elif choice[1] == "copyfiles":
			self.addDirtoPls(os_path.dirname(self.filelist.getSelection()[0].getPath()) + "/", recursive = False)
		elif choice[1] == "deletefile":
			self.deleteFile()
		elif choice[1] == "shuffle":
			self.Shuffle()
	def Settings(self):
		self.session.openWithCallback(self.updd, AudioPlayerSettings)
	def Exit(self):
		if self.isVisible == False:
			self.visibility()
			return
		if self.filelist.getCurrentDirectory() is None:
			config.plugins.mc_ap.lastDir.value = "devicelist"
		else:
			config.plugins.mc_ap.lastDir.value = self.filelist.getCurrentDirectory()
		self.FileInfoTimer.stop()
		del self["coverArt"].picload
		del self["screensaver"].picload
		if os.path.isfile("/tmp/.ac3on"):
			config.av.downmix_ac3.value = False
			config.av.downmix_ac3.save()
			os.remove("/tmp/.ac3on")
		config.plugins.mc_ap.save()
		if self.session.nav.getCurrentService() is not None:
			self.session.nav.stopService()
		MC_AudioPlayer.STATE = "NONE"
#		if config.plugins.mc_global.vfd.value == "on":
#			evfd.getInstance().vfd_write_string(_("My Music"))
		self.close()
	def screensavercheckup(self):
		self.JpgTimer.stop()
		self["screensaver"].showDefaultCover()
		time = config.plugins.mc_ap.jpg_delay.value * 1000
		self.JpgTimer.start(time, True)
	def showLyrics(self):
		if MC_AudioPlayer.STATE == "PLAY":
			self.session.openWithCallback(self.updd, Lyrics)
class MC_WebRadio(Screen, HelpableScreen):
	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self.jpgList = []
		self.jpgIndex = 0
		self.jpgLastIndex = -1
		self.isVisible = True
		self["key_blue"] = Button(_("Settings"))
		self["fileinfo"] = Label()
		try:
			if config.av.downmix_ac3.value == False:
				config.av.downmix_ac3.value = True
				config.av.downmix_ac3.save()
				os.system("touch /tmp/.ac3on")
		except Exception as e:
			print ("Media Center: no ac3")
		self["play"] = Pixmap()
		self["screensaver"] = MediaPixmap()
		MC_AudioPlayer.STATE = "NONE"
		lstdir = []
		self.playlist = PlayList()
		MC_AudioPlayer.playlistplay = 0
		MC_AudioPlayer.currPlaying = -1
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evEOF: self.doEOF,
				iPlayableService.evStopped: self.StopPlayback,
				iPlayableService.evUser+11: self.__evDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+14: self["screensaver"].screensaver
			})
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions",
			{
				"ok": (self.KeyOK, "Play selected file"),
				"playpause": (self.PlayPause, "Play / Pause"),
				"cancel": (self.Exit, "Exit Audio Player"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"video": (self.visibility, "Show / Hide Player"),
				"green": (self.showMenu, "Menu"),
				"stop": (self.StopPlayback, "Stop Playback"),
				"red": (self.deleteFile, "Delete"),
				"blue": (self.Settings, "Settings"),
			}, -2)

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")
		currDir = mcpath +"radio/"
		if not pathExists(currDir):
			currDir = "/"
		self.filelist = []
		self["filelist"] = []
		inhibitDirs = ["/bin", "/boot", "/dev", "/dev.static", "/etc", "/lib" , "/proc", "/ram", "/root" , "/sbin", "/sys", "/tmp", "/usr", "/var"]
		self.filelist = FileList(currDir, useServiceRef = True, showDirectories = False, showFiles = True, matchingPattern = "(?i)^.*\.(m3u|pls|e2pls)", additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")

		self["filelist"] = self.filelist
		self["filelist"].show()
		self.JpgTimer = eTimer()
		self.JpgTimer.callback.append(self.showBackgroundJPG)
		self.getJPG()
		self.FileInfoTimer = eTimer()
		self.FileInfoTimer.callback.append(self.updateFileInfo)
	def unlockShow(self):
		return
	def lockShow(self):
		return
	def up(self):
		self["filelist"].up()
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def down(self):
		self["filelist"].down()
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def leftUp(self):
		self["filelist"].pageUp()
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def rightDown(self):
		self["filelist"].pageDown()
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
	def KeyOK(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
		ServiceRef = self.filelist.getServiceRef()
		extension = ServiceRef.getPath()[ServiceRef.getPath().rfind('.') + 1:]
		if extension in self.playlistparsers:
			self.playlist.clear()
			playlist = self.playlistparsers[extension]()
			list = playlist.open(ServiceRef.getPath())
			for x in list:
				self.playlist.addFile(x.ref)
		self.playlist.updateList()
		MC_AudioPlayer.currPlaying = 0
		self.PlayServicepls()
	def PlayPause(self):
		if MC_AudioPlayer.STATE == "PLAY":
			service = self.session.nav.getCurrentService()
			pausable = service.pause()
			pausable.pause()
			MC_AudioPlayer.STATE = "PAUSED"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/pause_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		elif MC_AudioPlayer.STATE == "PAUSED":
			service = self.session.nav.getCurrentService()
			pausable = service.pause()
			pausable.unpause()
			MC_AudioPlayer.STATE = "PLAY"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		else:
			self.KeyOK()
	def visibility(self, force=1):
		if self.isVisible == True:
			self.isVisible = False
			self.hide()
		else:
			self.isVisible = True
			self.show()
	def updd(self):
		self.updateFileInfo()
		sort = config.plugins.mc_ap_sortmode.enabled.value
		self.filelist.refresh(sort)
		if MC_AudioPlayer.STATE == "PLAY":
			self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		elif MC_AudioPlayer.STATE == "PAUSED":
			self["play"].instance.setPixmapFromFile(mcpath +"icons/pause_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		elif MC_AudioPlayer.STATE == "NONE":
			self["play"].instance.setPixmapFromFile(mcpath +"icons/stop_enabled.png")
		else:
			return
	def PlayServicepls(self):
		MC_AudioPlayer.playlistplay = 1
		x = self.playlist.getCurrentIndex()
		x = len(self.playlist)
		self.session.nav.playService(self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()])
		MC_AudioPlayer.STATE = "PLAY"
		self.FileInfoTimer.start(2000, True)
		self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
		if config.plugins.mc_ap.showJpg.value:
			time = config.plugins.mc_ap.jpg_delay.value * 1000
			self.JpgTimer.start(time, True)
		self.playlist.clear()
	def StopPlayback(self):
		if self.isVisible == False:
			self.show()
			self.isVisible = True
		if self.session.nav.getCurrentService() is None:
			return
		else:
			self.session.nav.stopService()
			if config.plugins.mc_ap.showJpg.value:
				self.JpgTimer.stop()
				self["screensaver"].showDefaultCover()
			MC_AudioPlayer.STATE = "NONE"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/stop_enabled.png")
	def updateFileInfo(self):
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sComment = currPlay.info().getInfoString(iServiceInformation.sTagComment)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)
			if sTitle == "":
				sTitle = currPlay.info().getName().split('/')[-1]
			self["fileinfo"].setText(_("Title: ") + sTitle + _("\nArtist: ") + sArtist + _("\nAlbum: ") + sAlbum + _("\nYear: ") + sYear + _("\nGenre: ") + sGenre + _("\nComment: ") + sComment)
		self.FileInfoTimer.start(10000, True)
	def deleteFile(self):
		self.service = self.filelist.getServiceRef()
		if self.service.type != 4098 and self.session.nav.getCurrentlyPlayingServiceOrGroup() is not None:
			if self.service == self.session.nav.getCurrentlyPlayingServiceOrGroup():
				self.StopPlayback()
		self.session.openWithCallback(self.deleteFileConfirmed, MessageBox, _("Do you really want to delete this file ?"))
	def deleteFileConfirmed(self, confirmed):
		if confirmed:
			delfile = self["filelist"].getFilename()
			os.remove(delfile)
			sort = config.plugins.mc_ap_sortmode.enabled.value
			self.filelist.refresh(sort)
	def getJPG(self):
		if config.plugins.mc_ap.whichjpg.value == "default":
			path = mcpath +"saver/"
		else:
			path = config.plugins.mc_ap.whichjpg.value
		for root, dirs, files in os.walk(path):
			for name in files:
				if name.endswith(".jpg"):
					self.jpgList.append(name)
	def showBackgroundJPG(self):
		if len(self.jpgList) > 0:
			if self.jpgIndex < len(self.jpgList) -1:
				self.jpgIndex += 1
			else:
				self.jpgIndex = 0
			if self.jpgLastIndex != self.jpgIndex or self.jpgLastIndex == -1:
				if config.plugins.mc_ap.whichjpg.value == "default":
					path = mcpath +"saver/" + self.jpgList[self.jpgIndex]
				else:
					path = config.plugins.mc_ap.whichjpg.value + self.jpgList[self.jpgIndex]
				self["screensaver"].screensaver(path)
				self.jpgLastIndex = self.jpgIndex
				time = config.plugins.mc_ap.jpg_delay.value * 1000
				self.JpgTimer.start(time, True)
		else:
			print ("MediaCenter: No Background Files found ...")
	def doEOF(self):
		self.StopPlayback()
		if config.plugins.mc_ap.showJpg.value:
			self.JpgTimer.stop()
			self["screensaver"].showDefaultCover()
	def __evDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sVideoType = currPlay.info().getInfoString(iServiceInformation.sVideoType)
		self.session.open(MessageBox, _("This Dreambox can't decode %s video streams!") % sVideoType, type = MessageBox.TYPE_INFO,timeout = 20 )
	def __evPluginError(self):
		currPlay = self.session.nav.getCurrentService()
		message = currPlay.info().getInfoString(iServiceInformation.sUser+12)
		self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )
	def addPlaylistParser(self, parser, extension):
		self.playlistparsers[extension] = parser
	def Settings(self):
		self.session.openWithCallback(self.updd, AudioPlayerSettings)
	def Exit(self):
		if self.isVisible == False:
			self.visibility()
			return
		self.FileInfoTimer.stop()
		del self["screensaver"].picload
		if os.path.isfile("/tmp/.ac3on"):
			config.av.downmix_ac3.value = False
			config.av.downmix_ac3.save()
			os.remove("/tmp/.ac3on")
		if self.session.nav.getCurrentService() is not None:
			self.session.nav.stopService()
		MC_AudioPlayer.STATE = "NONE"
		self.close()
	def screensavercheckup(self):
		self.JpgTimer.stop()
		self["screensaver"].showDefaultCover()
		time = config.plugins.mc_ap.jpg_delay.value * 1000
		self.JpgTimer.start(time, True)
	def showMenu(self):
		if fileExists("/tmp/index.txt"):
			os.remove("/tmp/index.txt")
		menu = []
		menu.append((_("70-80er"), "70-80er/"))
		menu.append((_("Alternative"), "Alternative/"))
		menu.append((_("Ambient"), "Ambient/"))
		menu.append((_("Artist"), "Artist/"))
		menu.append((_("Big Band"), "Big%20Band/"))
		menu.append((_("Blues"), "Blues/"))
		menu.append((_("Bluegrass"), "Bluegrass/"))
		menu.append((_("Chillout"), "Chillout/"))
		menu.append((_("Classic"), "classical/"))
		menu.append((_("Classic Rock"), "classic%20rock/"))
		menu.append((_("Countrymusic"), "Countrymusik/"))
		menu.append((_("Hip Hop"), "HipHop/"))
		menu.append((_("Hits"), "Hits/"))
		menu.append((_("Moviemusic"), "Moviemusik/"))
		menu.append((_("Oldies"), "Oldies/"))
		menu.append((_("Party"), "Party/"))
		menu.append((_("Reggae"), "Reggae/"))
		menu.append((_("Rock"), "Rock/"))
		menu.append((_("Rundfunk"), "Rundfunk/"))
		menu.append((_("Smooth"), "Smooth/"))
		menu.append((_("Soul"), "Soul/"))
		menu.append((_("Techno/House"), "Techno/"))
		menu.append((_("Worldmusic"), "Worldmusik/"))
		self.session.openWithCallback(self.menuCallback, ChoiceBox, title="", list=menu)
	def menuCallback(self, choice):
		if choice is None:
			return
		os.system("echo "+ choice[1] +" > /tmp/.webselect | wget -O /tmp/index.txt "+ radirl +""+ choice[1] + "index.txt")
		self.session.openWithCallback(self.updd, MC_WebDown)
class MC_WebDown(Screen):
	def __init__(self, session):
		Screen.__init__(self, session)
		list = []
		if fileExists("/tmp/index.txt"):
			names = open("/tmp/index.txt").read().split('\n')
			for x in names:
				list.append((x, _(x)))
		self["menu"] = List(list)
		self["actions"] = ActionMap(["OkCancelActions", "DirectionActions"],
		{
			"cancel": self.exit,
			"ok": self.okbuttonClick
		}, -1)
	def okbuttonClick(self):
		selection = self["menu"].getCurrent()
		if selection is not None:
			gen = open("/tmp/.webselect").read().split('\n')
			os.system("wget -O '"+ mcpath +"radio/"+ selection[1] +"' '"+ radirl +""+ gen[0] +""+ selection[1].replace(" ", "%20") +"'")
			os.remove("/tmp/index.txt")
			self.close()
	def exit(self):
		try:
			os.remove("/tmp/index.txt")
		except:
			print ("no Index found")
		self.close()
class MC_AudioPlaylist(Screen, InfoBarSeek):
	def __init__(self, session):
		Screen.__init__(self, session)
		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")
		self["key_red"] = Button("Back")
		self["key_green"] = Button(" ")
		self["key_yellow"] = Button(" ")
		self["key_blue"] = Button(_("File Browser"))
		self.jpgList = []
		self.jpgIndex = 0
		self.jpgLastIndex = -1
		self["play"] = Pixmap()
		self.isVisible = True
		self["fileinfo"] = Label()
		#self["coverArt"] = MediaPixmap()
		self["screensaver"] = MediaPixmap()
		self.FileInfoTimer = eTimer()
		self.FileInfoTimer.callback.append(self.updateFileInfo)
		self.PlaySingle = 0
		self.playlist = PlayList()
		self["playlist"] = self.playlist
		self.playlistIOInternal = PlaylistIOInternal()
		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evEOF: self.fileupdate,
				#iPlayableService.evStopped: self.StopPlayback,
				#iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt,
				iPlayableService.evUser+14: self["screensaver"].screensaver
			})
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions",
			{
				"ok": (self.KeyOK, "Play from selected file"),
				"cancel": (self.Exit, "Exit Audio Player"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"menu": (self.showMenu, "File / Folder Options"),
				"video": (self.visibility, "Show / Hide Player"),
				"info": (self.showLyrics, "Lyrics"),
				"stop": (self.StopPlayback, "Stop Playback"),
				"red": (self.Exit, "Close Playlist"),
				#"green": (self.close, "Play All"),
				#"yellow": (self.Exit, "Playlists"),
				"blue": (self.Exit, "Close Playlist"),
				"next": (self.KeyNext, "Next song"),
				"previous": (self.KeyPrevious, "Previous song"),
				"playpause": (self.PlayPause, "Play / Pause"),
				"stop": (self.StopPlayback, "Stop"),
			}, -2)
		self.JpgTimer = eTimer()
		self.JpgTimer.callback.append(self.showBackgroundJPG)
		self.getJPG()
		if MC_AudioPlayer.STATE != "NONE":
			self.updateFileInfo()
			if config.plugins.mc_ap.showJpg.value:
				time = config.plugins.mc_ap.jpg_delay.value * 1000
				self.JpgTimer.start(time, True)
	def unlockShow(self):
		return
	def lockShow(self):
		return
	def up(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
		self["playlist"].up()
	def down(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
		self["playlist"].down()
	def leftUp(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
		self["playlist"].pageUp()
	def rightDown(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
			self.screensavercheckup()
		self["playlist"].pageDown()
	def KeyOK(self):
		if len(self.playlist.getServiceRefList()):
			x = self.playlist.getSelectionIndex()
			self.playlist.setCurrentPlaying(self.playlist.getSelectionIndex())
			x = self.playlist.getCurrentIndex()
			x = len(self.playlist)
			self.PlayService()
	def PlayPause(self):
		if MC_AudioPlayer.STATE != "NONE":
			if MC_AudioPlayer.STATE == "PLAY":
				service = self.session.nav.getCurrentService()
				pausable = service.pause()
				pausable.pause()
				MC_AudioPlayer.STATE = "PAUSED"
			elif MC_AudioPlayer.STATE == "PAUSED":
				service = self.session.nav.getCurrentService()
				pausable = service.pause()
				pausable.unpause()
				MC_AudioPlayer.STATE = "PLAY"
			else:
				self.KeyOK()
	def KeyNext(self):
		if MC_AudioPlayer.STATE != "NONE":
			if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
			if MC_AudioPlayer.playlistplay == 1:
				next = self.playlist.getCurrentIndex() + 1
				if next < len(self.playlist):
					MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying + 1
				else:
					MC_AudioPlayer.currPlaying = 0
				self.PlayService()
			else:
				self.session.open(MessageBox, _("You have to close playlist before you can go to the next song while playing from file browser."), MessageBox.TYPE_ERROR)
	def KeyPrevious(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		if MC_AudioPlayer.playlistplay == 1:
			next = self.playlist.getCurrentIndex() - 1
			if next != -1:
				MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying - 1
			else:
				MC_AudioPlayer.currPlaying = 0
			self.PlayService()
		else:
			self.session.open(MessageBox, _("You have to close playlist before you can go to the previous song while playing from file browser."), MessageBox.TYPE_ERROR)
	def PlayService(self):
		MC_AudioPlayer.playlistplay = 1
		self.session.nav.playService(self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()])
		MC_AudioPlayer.STATE = "PLAY"
		self.FileInfoTimer.start(2000, True)
		self["play"].instance.setPixmapFromFile(mcpath +"icons/play_enabled.png")
		if config.plugins.mc_ap.showJpg.value:
			time = config.plugins.mc_ap.jpg_delay.value * 1000
			self.JpgTimer.start(time, True)
	#	path = self["filelist"].getCurrentDirectory()
	#	self["coverArt"].updateCoverArt(path)
	def StopPlayback(self):
		if self.isVisible == False:
			self.show()
			self.isVisible = True
		if self.session.nav.getCurrentService() is None:
			return
		else:
			self.session.nav.stopService()
			MC_AudioPlayer.STATE = "NONE"
			self["play"].instance.setPixmapFromFile(mcpath +"icons/stop_enabled.png")
			if config.plugins.mc_ap.showJpg.value:
				self.JpgTimer.stop()
				self["screensaver"].showDefaultCover()
	def visibility(self, force=1):
		if self.isVisible == True:
			self.isVisible = False
			self.hide()
		else:
			self.isVisible = True
			self.show()
	def Settings(self):
		self.session.openWithCallback(self.updd, MC_AudioPlaylist)
	def updd(self):
		if MC_AudioPlayer.STATE != "NONE" and config.plugins.mc_ap.showJpg.value:
				self.screensavercheckup()
		else:
			return
	def Exit(self):
		del self["screensaver"].picload
		if config.plugins.mc_ap.showJpg.value:
			self.JpgTimer.stop()
		self.close()
	def fileupdate(self):
		self.FileInfoTimer.start(2000, True)
		if config.plugins.mc_ap.showJpg.value:
			time = config.plugins.mc_ap.jpg_delay.value * 1000
			self.JpgTimer.start(time, True)
	def updateFileInfo(self):
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sComment = currPlay.info().getInfoString(iServiceInformation.sTagComment)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)
			if sTitle == "":
				sTitle = currPlay.info().getName().split('/')[-1]
			self["fileinfo"].setText("Title: " + sTitle + "\nArtist: " + sArtist + "\nAlbum: " + sAlbum + "\nYear: " + sYear + "\nGenre: " + sGenre + "\nComment: " + sComment)
	def save_playlist(self):
		from Screens.InputBox import InputBox
		self.session.openWithCallback(self.save_pls,InputBox, title=_("Please enter filename (empty = use current date)"),windowTitle = _("Save Playlist"))
	def save_pls(self, name):
		if name is not None:
			name = name.strip()
			if name == "":
				name = strftime("%y%m%d_%H%M%S")
			name += ".e2pls"
			self.playlistIOInternal.clear()
			for x in self.playlist.list:
				self.playlistIOInternal.addService(ServiceReference(x[0]))
			self.playlistIOInternal.save(resolveFilename(SCOPE_PLAYLIST) + name)
	def load_playlist(self):
		listpath = []
		playlistdir = resolveFilename(SCOPE_PLAYLIST)
		try:
			for i in os_listdir(playlistdir):
				listpath.append((i,playlistdir + i))
		except IOError as e:
			print ("Error while scanning subdirs ",e)
		self.session.openWithCallback(self.load_pls, ChoiceBox, title=_("Please select a playlist..."), list = listpath)
	def load_pls(self,path):
		if path is not None:
			self.playlist.clear()
			extension = path[0].rsplit('.',1)[-1]
			if extension in self.playlistparsers:
				playlist = self.playlistparsers[extension]()
				list = playlist.open(path[1])
				for x in list:
					self.playlist.addFile(x.ref)
			self.playlist.updateList()
	def delete_saved_playlist(self):
		listpath = []
		playlistdir = resolveFilename(SCOPE_PLAYLIST)
		try:
			for i in os_listdir(playlistdir):
				listpath.append((i,playlistdir + i))
		except IOError as e:
			print ("Error while scanning subdirs ",e)
		self.session.openWithCallback(self.delete_saved_pls, ChoiceBox, title=_("Please select a playlist to delete..."), list = listpath)
	def delete_saved_pls(self,path):
		if path is not None:
			self.delname = path[1]
			self.session.openWithCallback(self.delete_saved_pls_conf, MessageBox, _("Do you really want to delete %s?") % (path[1]))
	def delete_saved_pls_conf(self, confirmed):
		if confirmed:
			try:
				os_remove(self.delname)
			except OSError as e:
				self.session.open(MessageBox, _("Delete failed!"), MessageBox.TYPE_ERROR)
	def addPlaylistParser(self, parser, extension):
		self.playlistparsers[extension] = parser
	def showMenu(self):
		menu = []
		menu.append((_("delete from playlist"), "deleteentry"))
		menu.append((_("clear playlist"), "clear"))
		menu.append((_("load playlist"), "loadplaylist"));
		menu.append((_("save playlist"), "saveplaylist"));
		menu.append((_("delete saved playlist"), "deleteplaylist"));
		self.session.openWithCallback(self.menuCallback, ChoiceBox, title="", list=menu)
	def menuCallback(self, choice):
		if choice is None:
			return
		if choice[1] == "deleteentry":
			self.playlist.deleteFile(self.playlist.getSelectionIndex())
			self.playlist.updateList()
		elif choice[1] == "clear":
			self.playlist.clear()
		elif choice[1] == "loadplaylist":
			self.load_playlist()
		elif choice[1] == "saveplaylist":
			self.save_playlist()
		elif choice[1] == "deleteplaylist":
			self.delete_saved_playlist()
	def getJPG(self):
		if config.plugins.mc_ap.whichjpg.value == "default":
			path = mcpath +"saver/"
		else:
			path = config.plugins.mc_ap.whichjpg.value
		for root, dirs, files in os.walk(path):
			for name in files:
				if name.endswith(".jpg"):
					self.jpgList.append(name)
	def showBackgroundJPG(self):
		if len(self.jpgList) > 0:
			if self.jpgIndex < len(self.jpgList) -1:
				self.jpgIndex += 1
			else:
				self.jpgIndex = 0
			if self.jpgLastIndex != self.jpgIndex or self.jpgLastIndex == -1:
				path = mcpath +"saver/" + self.jpgList[self.jpgIndex]
				self["screensaver"].screensaver(path)
				self.jpgLastIndex = self.jpgIndex
				time = config.plugins.mc_ap.jpg_delay.value * 1000
				self.JpgTimer.start(time, True)
		else:
			print ("MediaCenter: No Background Files found ...")
	def showLyrics(self):
		if MC_AudioPlayer.STATE == "PLAY":
			self.session.openWithCallback(self.updd, Lyrics)
	def screensavercheckup(self):
		self.JpgTimer.stop()
		self["screensaver"].showDefaultCover()
		time = config.plugins.mc_ap.jpg_delay.value * 1000
		self.JpgTimer.start(time, True)
class Lyrics(Screen):
	if getDesktop(0).size().width() == 1920:
		skin = """
			<screen name="Lyrics" position="0,0" size="1920,1080" flags="wfNoBorder" backgroundColor="#00000000" title="Lyrics">
			<eLabel backgroundColor="#999999" position="50,50" size="620,2" zPosition="1"/>
			<widget name="headertext" position="50,73" zPosition="1" size="620,23" font="Regular;20" transparent="1"  foregroundColor="#fcc000" backgroundColor="#00000000"/>
			<widget name="coverly" position="700,120" size="160,133" zPosition="9" valign="center" halign="center" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/BMediaCenter/skins/defaultHD/images/no_coverArt.png" transparent="1" alphatest="blend" />
			<widget name="resulttext" position="50,100" zPosition="1" size="620,20" font="Regular;16" transparent="1"   backgroundColor="#00000000"/>
			<widget name="lyric_text" position="50,150" zPosition="2" size="620,350" font="Regular;18" transparent="0"  backgroundColor="#00000000"/>
			</screen>"""
	else:
		skin = """
			<screen name="Lyrics" position="0,0" size="720,576" flags="wfNoBorder" backgroundColor="#00000000" title="Lyrics">
			<eLabel backgroundColor="#999999" position="50,50" size="620,2" zPosition="1"/>
			<widget name="headertext" position="50,73" zPosition="1" size="620,23" font="Regular;20" transparent="1"  foregroundColor="#fcc000" backgroundColor="#00000000"/>
			<widget name="coverly" position="700,120" size="160,133" zPosition="9" valign="center" halign="center" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/BMediaCenter/skins/defaultHD/images/no_coverArt.png" transparent="1" alphatest="blend" />
			<widget name="resulttext" position="50,100" zPosition="1" size="620,20" font="Regular;16" transparent="1"   backgroundColor="#00000000"/>
			<widget name="lyric_text" position="50,150" zPosition="2" size="620,350" font="Regular;18" transparent="0"  backgroundColor="#00000000"/>
			</screen>"""
	def __init__(self, session):
		self.session = session
		Screen.__init__(self, session)
		self["headertext"] = Label(_("Lyrics"))
		self["resulttext"] = Label()
		self["coverly"] = MediaPixmap()
		curPlay = self.session.nav.getCurrentService()
		if curPlay is not None:
			title = curPlay.info().getInfoString(iServiceInformation.sTagTitle)
			os.system("echo '"+ str(title) +"' > /tmp/.oldplaying | echo '"+ str(title) +"' > /tmp/.curplaying ")
		self.RFTimer = eTimer()
		self.RFTimer.callback.append(self.refresh)
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUser+11: self["coverly"].coverlyrics
			})
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions",
			{
				"cancel": self.Exit,
				"up": self.pageUp,
				"left": self.pageUp,
				"down": self.pageDown,
				"right": self.pageDown
			}, -2)
		self["lyric_text"] = ScrollLabel()
		self.refresh()
		self.onLayoutFinish.append(self.startRun)
	def refresh(self):
		time = 10000
		self.RFTimer.start(time, True)
		curPlay = self.session.nav.getCurrentService()
		title = curPlay.info().getInfoString(iServiceInformation.sTagTitle)
		os.system("echo '"+ str(title) +"' > /tmp/.curplaying")
		old = open("/tmp/.oldplaying").read()
		oldtitle = old.split('\r\n')
		tit = open("/tmp/.curplaying").read()
		titlee = tit.split('\r\n')
		if oldtitle == titlee:
			return
		else:
			self.startRun()
			os.system("echo '"+ str(title) +"' > /tmp/.oldplaying")
	def startRun(self):
		text = getEncodedString(self.getLyricsFromID3Tag()).replace("\r\n","\n")
		text = text.replace("\r","\n")
		self["lyric_text"].setText(text)
	def getLyricsFromID3Tag(self):
		curPlay = self.session.nav.getCurrentService()
		if curPlay is not None:
			titlely = curPlay.info().getInfoString(iServiceInformation.sTagTitle)
			artistly = curPlay.info().getInfoString(iServiceInformation.sTagArtist)
			if titlely == "":
				titlely = curPlay.info().getName().split('/')[-1]
			if artistly == "":
				artistly = titlely
		from urllib import quote
		url = "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=%s&song=%s" % (quote(artistly), quote(titlely))
		sendUrlCommand(url, None,10).addCallback(self.gotLyrics).addErrback(self.urlError)
		return "No lyrics found in id3-tag, trying api.chartlyrics.com..."
	def urlError(self, error = None):
		if error is not None:
			self["resulttext"].setText(str(error.getErrorMessage()))
			self["lyric_text"].setText("")
	def gotLyrics(self, xmlstring):
		from xml.etree.cElementTree import fromstring as cet_fromstring
		root = cet_fromstring(xmlstring)
		lyrictext = ""
		lyrictext = root.findtext("{http://api.chartlyrics.com/}Lyric").encode("utf-8", 'ignore')
		self["lyric_text"].setText(lyrictext)
		title = root.findtext("{http://api.chartlyrics.com/}LyricSong").encode("utf-8", 'ignore')
		artist = root.findtext("{http://api.chartlyrics.com/}LyricArtist").encode("utf-8", 'ignore')
		coverly = root.findtext("{http://api.chartlyrics.com/}LyricCovertArtUrl").encode("utf-8", 'ignore')
		os.system("wget -O /tmp/.onlinecover "+ coverly +"")
		self["coverly"].coverlyrics()
		result = _("Response -> lyrics for: %s (%s)") % (title,artist)
		self["resulttext"].setText(result)
		if not lyrictext:
			self["resulttext"].setText(_("No lyrics found"))
			self["lyric_text"].setText("")
			self["coverly"].showDefaultCover()
	def pageUp(self):
		self["lyric_text"].pageUp()
	def pageDown(self):
		self["lyric_text"].pageDown()
	def Exit(self):
		del self["coverly"].picload
		if fileExists("/tmp/.onlinecover"):
			os.remove("/tmp/.onlinecover")
		if fileExists("/tmp/.curplaying") and fileExists("/tmp/.oldplaying"):
			os.system("rm -rf /tmp/.*playing")
		self.RFTimer.stop()
		self.close()
class MediaPixmap(Pixmap):
	def __init__(self):
		Pixmap.__init__(self)
		self.coverArtFileName = ""
		self.picload = ePicLoad()
		self.picload.PictureData.get().append(self.paintCoverArtPixmapCB)
		self.coverFileNames = ["cover.jpg", "folder.png", "folder.jpg"]
	def applySkin(self, desktop, screen):
		from Tools.LoadPixmap import LoadPixmap
		noCoverFile = None
		if self.skinAttributes is not None:
			for (attrib, value) in self.skinAttributes:
				if attrib == "pixmap":
					noCoverFile = value
					break
		if noCoverFile is None:
			noCoverFile = resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/no_coverArt.png")
		self.noCoverPixmap = LoadPixmap(noCoverFile)
		return Pixmap.applySkin(self, desktop, screen)
	def onShow(self):
		Pixmap.onShow(self)
		from Components.AVSwitch import AVSwitch
		sc = AVSwitch().getFramebufferScale()
		#0=Width 1=Height 2=Aspect 3=use_cache 4=resize_type 5=Background(#AARRGGBB)
		self.picload.setPara((self.instance.size().width(), self.instance.size().height(), sc[0], sc[1], False, 1, "#00000000"))
	def paintCoverArtPixmapCB(self, picInfo=None):
		ptr = self.picload.getData()
		if ptr != None:
			self.instance.setPixmap(ptr.__deref__())
	def updateCoverArt(self, path):
		while not path.endswith("/"):
			path = path[:-1]
		new_coverArtFileName = None
		for filename in self.coverFileNames:
			if fileExists(path + filename):
				new_coverArtFileName = path + filename
		if self.coverArtFileName != new_coverArtFileName:
			self.coverArtFileName = new_coverArtFileName
			if new_coverArtFileName:
				self.picload.startDecode(self.coverArtFileName)
			else:
				self.showDefaultCover()
	def showDefaultCover(self):
		self.instance.setPixmap(self.noCoverPixmap)
	def embeddedCoverArt(self):
		self.coverArtFileName = "/tmp/.id3coverart"
		self.picload.startDecode(self.coverArtFileName)
	def coverlyrics(self):
		self.coverArtFileName = "/tmp/.onlinecover"
		self.picload.startDecode(self.coverArtFileName)
	def screensaver(self, path):
		self.picload.startDecode(path)
class AudioPlayerSettings(Screen):
	def __init__(self, session):
		Screen.__init__(self, session)
		self["actions"] = NumberActionMap(["SetupActions"],
		{
			"ok": self.close,
			"cancel": self.close,
			"left": self.keyLeft,
			"right": self.keyRight,
			"0": self.keyNumber,
			"1": self.keyNumber,
			"2": self.keyNumber,
			"3": self.keyNumber,
			"4": self.keyNumber,
			"5": self.keyNumber,
			"6": self.keyNumber,
			"7": self.keyNumber,
			"8": self.keyNumber,
			"9": self.keyNumber
		}, -1)

		self.list = []
		self["configlist"] = ConfigList(self.list)
		self.list.append(getConfigListEntry(_("Screensaver Enable:"), config.plugins.mc_ap.showJpg))
		self.list.append(getConfigListEntry(_("Screensaver Interval"), config.plugins.mc_ap.jpg_delay))
		self.list.append(getConfigListEntry(_("Screensaver Style:"), config.plugins.mc_ap.whichjpg))
		self.list.append(getConfigListEntry(_("Filelist Sorting:"), config.plugins.mc_ap_sortmode.enabled))
	def keyLeft(self):
		self["configlist"].handleKey(KEY_LEFT)
	def keyRight(self):
		self["configlist"].handleKey(KEY_RIGHT)
	def keyNumber(self, number):
		self["configlist"].handleKey(KEY_0 + number)


from django.shortcuts import render, get_object_or_404
from restaurants.models import Restaurant, Town

# Create your views here.
def choose_town(request, food_id):

    rest_list = Restaurant.objects.filter(food=food_id)
    town_list=[]
    for r in rest_list:
        t = Town.objects.get(id=r.town.id)
        if t not in town_list:
            rests = Restaurant.objects.filter(food__id=food_id, town__id=t.id)
            town_list.append({'town':t, 'count':len(rests)})
    return render(request, 'restaurants/choose_town.html', {'food_id':food_id, 'town_list':town_list})

def choose_restaurant(request,food_id,town_id):
    rests = Restaurant.objects.filter(food__id=food_id, town__id=town_id)
    return render(request, 'restaurants/choose_restaurant.html', {'rests':rests})

def restaurant(request, rest_id, message=''):
    rest = Restaurant.objects.get(id=rest_id)
    rest_menu = rest.menu.split(';')
    rest_menu = [e for e in rest_menu if e not in ('',' ')]
    return render(request, 'restaurants/restaurant.html', {'restaurant':rest, 'rest_menu':rest_menu, 'message':message})

def vote(request, rest_id):
    rest = get_object_or_404(Restaurant, pk=rest_id)

    votes = rest.votes
    submitted = request.POST['note_utilisateur']
    average = (votes + int(submitted))/2
    rest.votes = average
    rest.save()

    rest_menu = rest.menu.split(';')
    rest_menu = [e for e in rest_menu if e not in ('',' ')]

    message='Thanks for your vote!'

    return render(request, 'restaurants/restaurant.html', {'restaurant':rest, 'rest_menu':rest_menu, 'message':message})


import os
from funasr.utils.job_runner import MultiProcessRunnerV3
import numpy as np
from funasr.utils.misc import load_scp_as_list, load_scp_as_dict
from collections import OrderedDict
from tqdm import tqdm
from scipy.ndimage import median_filter
import kaldiio

def load_mid_vad(vad_path):
    mid2segment_list = {}
    for one_line in open(vad_path, "rt"):
        utt_id, mid, start, end = one_line.strip().split(" ")
        start, end = float(start), float(end)
        if mid not in mid2segment_list:
            mid2segment_list[mid] = []
        mid2segment_list[mid].append((utt_id, start, end))

    return mid2segment_list

class MyRunner(MultiProcessRunnerV3):
    def prepare(self, parser):
        parser.add_argument("label_txt", type=str)
        parser.add_argument("oracle_vad", type=str, default=None)
        parser.add_argument("out_rttm", type=str)
        parser.add_argument("--sys_vad_prob", type=str, default=None)
        parser.add_argument("--sys_vad_threshold", type=float, default=None)
        parser.add_argument("--vad_smooth_size", type=int, default=7)
        parser.add_argument("--n_spk", type=int, default=4)
        parser.add_argument("--chunk_len", type=int, default=1600)
        parser.add_argument("--shift_len", type=int, default=400)
        parser.add_argument("--ignore_len", type=int, default=5)
        parser.add_argument("--smooth_size", type=int, default=7)
        parser.add_argument("--vote_prob", type=float, default=0.5)
        args = parser.parse_args()

        if not os.path.exists(os.path.dirname(args.out_rttm)):
            os.makedirs(os.path.dirname(args.out_rttm))

        utt2labels = load_scp_as_list(args.label_txt, 'list')
        utt2vad_prob = []
        if args.sys_vad_prob is not None and os.path.exists(args.sys_vad_prob):
            if args.verbose:
                print("Use system vad ark file {}".format(args.sys_vad_prob))
            for (key, vad_prob), (utt_id, _) in zip(kaldiio.load_ark(args.sys_vad_prob), utt2labels):
                utt2vad_prob.append((utt_id, vad_prob))
            utt2vad_prob = sorted(utt2vad_prob, key=lambda x: x[0])

        utt2labels = sorted(utt2labels, key=lambda x: x[0])
        mid2segment_list = load_mid_vad(args.oracle_vad)
        meeting2labels = OrderedDict()
        for utt_id, chunk_label in utt2labels:
            mid = utt_id.split("-")[0]
            if mid not in meeting2labels:
                meeting2labels[mid] = []
            meeting2labels[mid].append(chunk_label)

        mid2vad_list = {}
        if len(utt2vad_prob) > 0:
            for utt_id, vad_prob in utt2vad_prob:
                mid = utt_id.split("-")[0]
                if mid not in mid2vad_list:
                    mid2vad_list[mid] = []
                mid2vad_list[mid].append(vad_prob)

        task_list = [(mid, labels, mid2segment_list[mid], None) if len(mid2vad_list) == 0 else
                     (mid, labels, mid2segment_list[mid], mid2vad_list[mid])
                     for mid, labels in meeting2labels.items()]

        return task_list, None, args

    def post(self, result_list, args):
        ref_vad_rttm = open(args.out_rttm + ".ref_vad", "wt")
        sys_vad_rttm = open(args.out_rttm + ".sys_vad", "wt")
        for results in result_list:
            for one_result in results:
                ref_vad_rttm.writelines(one_result[0])
                sys_vad_rttm.writelines(one_result[1])
        ref_vad_rttm.close()
        sys_vad_rttm.close()

def int2vec(x, vec_dim=8, dtype=np.int):
    b = ('{:0' + str(vec_dim) + 'b}').format(x)
    # little-endian order: lower bit first
    return (np.array(list(b)[::-1]) == '1').astype(dtype)

def seq2arr(seq, vec_dim=8):
    return np.row_stack([int2vec(int(x), vec_dim) for x in seq])

def sample2ms(sample, sr=16000):
    return int(float(sample) / sr * 100)

def calc_multi_labels(chunk_label_list, chunk_len, shift_len, n_spk, vote_prob=0.5):
    n_chunk = len(chunk_label_list)
    last_chunk_valid_frame = len(chunk_label_list[-1]) - (chunk_len - shift_len)
    n_frame = (n_chunk - 2) * shift_len + chunk_len + last_chunk_valid_frame
    multi_labels = np.zeros((n_frame, n_spk), dtype=float)
    weight = np.zeros((n_frame, 1), dtype=float)
    for i in range(n_chunk):
        raw_label = chunk_label_list[i]
        for k in range(len(raw_label)):
            if raw_label[k] == '<unk>':
                raw_label[k] = raw_label[k-1] if k > 0 else '0'
        chunk_multi_label = seq2arr(raw_label, n_spk)
        chunk_len = chunk_multi_label.shape[0]
        multi_labels[i*shift_len:i*shift_len+chunk_len, :] += chunk_multi_label
        weight[i*shift_len:i*shift_len+chunk_len, :] += 1
    multi_labels = multi_labels / weight  # normalizing vote
    multi_labels = (multi_labels > vote_prob).astype(int)  # voting results
    return multi_labels

def calc_spk_turns(label_arr, spk_list):
    turn_list = []
    length = label_arr.shape[0]
    n_spk = label_arr.shape[1]
    for k in range(n_spk):
        if spk_list[k] == "None":
            continue
        in_utt = False
        start = 0
        for i in range(length):
            if label_arr[i, k] == 1 and in_utt is False:
                start = i
                in_utt = True
            if label_arr[i, k] == 0 and in_utt is True:
                turn_list.append([spk_list[k], start, i - start])
                in_utt = False
        if in_utt:
            turn_list.append([spk_list[k], start, length - start])
    return turn_list

def smooth_multi_labels(multi_label, win_len):
    multi_label = median_filter(multi_label, (win_len, 1), mode="constant", cval=0.0).astype(int)
    return multi_label

def calc_vad_mask(segments, total_len):
    vad_mask = np.zeros((total_len, 1), dtype=int)
    for _, start, end in segments:
        start, end = int(start * 100), int(end * 100)
        vad_mask[start: end] = 1
    return vad_mask

def calc_system_vad_mask(vad_prob_list, total_len, args):
    if vad_prob_list is None:
        return 1

    threshold = args.sys_vad_threshold
    chunk_len = args.chunk_len
    shift_len = args.shift_len
    frame_vad_mask = np.zeros((total_len, 1), dtype=float)
    weight = np.zeros((total_len, 1), dtype=float)
    for i, vad_prob in enumerate(vad_prob_list):
        frame_vad_mask[i * shift_len: i * shift_len + chunk_len] += np.greater(vad_prob, threshold).astype(float)
        weight[i * shift_len: i * shift_len + chunk_len] += 1.0
    frame_vad_mask = np.greater(frame_vad_mask / weight, args.vote_prob)
    frame_vad_mask = frame_vad_mask.astype(int)
    frame_vad_mask = smooth_multi_labels(frame_vad_mask.astype(int), args.vad_smooth_size)
    return frame_vad_mask

def generate_rttm(mid, multi_labels, spk_list, args):
    template = "SPEAKER {} 0 {:.2f} {:.2f} <NA> <NA> {} <NA> <NA>\n"
    spk_turns = calc_spk_turns(multi_labels, spk_list)
    spk_turns = sorted(spk_turns, key=lambda x: x[1])
    results = []
    for spk, st, dur in spk_turns:
        # TODO: handle the leak of segments at the change points
        if dur > args.ignore_len:
            results.append(template.format(mid, float(st) / 100, float(dur) / 100, spk))
    return results

def process(task_args):
    _, task_list, _, args = task_args
    spk_list = ["spk{}".format(i+1) for i in range(args.n_spk)]
    results = []
    for mid, chunk_label_list, segments_list, sys_vad_list in tqdm(task_list, total=len(task_list),
                                                                   ascii=True, disable=args.no_pbar):
        multi_labels = calc_multi_labels(chunk_label_list, args.chunk_len, args.shift_len, args.n_spk, args.vote_prob)
        multi_labels = smooth_multi_labels(multi_labels, args.smooth_size)
        oracle_vad_mask = calc_vad_mask(segments_list, multi_labels.shape[0])
        oracle_vad_rttm = generate_rttm(mid, multi_labels * oracle_vad_mask, spk_list, args)
        system_vad_mask = calc_system_vad_mask(sys_vad_list, multi_labels.shape[0], args)
        system_vad_rttm = generate_rttm(mid, multi_labels * system_vad_mask, spk_list, args)
        results.append([oracle_vad_rttm, system_vad_rttm])
    return results

if __name__ == '__main__':
    my_runner = MyRunner(process)
    my_runner.run()