Example #1
0
def loadPlaylist():
    if checkAppStopAction():
        return
    session = playlistdb.GetDbSession()
    global PlayListSet
    playlist = (session.query(playlistdb.PlayList)
            .filter(playlistdb.PlayList.status == 0)
            .order_by(playlistdb.PlayList.filename))
    for dev in ShopDevices:
        devPlaylist = None
        #获取当前的设备的播放列表
        if dev["name"] not in PlayListSet:
            PlayListSet[dev["name"]] = {'lastIndex':0,'playlist':[]}
        devPlaylist = PlayListSet[dev["name"]]
        newplaylist = []
        #遍历文件列表,获取需要播放的文件
        for mfile in playlist:
            if mfile.iotpath not in dev["path"]:
                continue
            if (dev["type"] == "Video" and mfile.mediatype not in ('Video','Image')) or \
                (dev["type"] == "Audio" and mfile.mediatype not in ('Audio')):
                continue
            newplaylist.append({
                'id':mfile.playlistid,
                'mediaid':mfile.mediaid,
                'filename':mfile.filename,
                'iotpath':mfile.iotpath,
                'extension':mfile.extension,
                'duration':mfile.duration})
        logger.info(dev["name"]+"节目单:"+ json.dumps(newplaylist))
        devPlaylist["playlist"] = newplaylist
Example #2
0
def resourceItemWorker(iotPath, resourceList):
    session = playlistdb.GetDbSession()
    idlist = []
    for item in resourceList:
        idlist.append(item["id"])
        _, item_filename_ext = os.path.splitext(item["filename"])
        try:
            existitem = (session.query(playlistdb.PlayList).filter(
                playlistdb.PlayList.mediaid == item["id"]).first())
            if existitem == None:
                newplaylistid = uuid.uuid1().hex
                newplaylistRow = playlistdb.PlayList(
                    playlistid=newplaylistid,
                    iotpath=iotPath,
                    mediaid=item["id"],
                    filename=item["filename"],
                    extension=item_filename_ext,
                    createdon=datetime.datetime.now(),
                    tag=item["tag"],
                    modifiedon=datetime.datetime.now(),
                    urlpath=item["path"],
                    status=10,
                    playcount=0,
                    mediatype=item["mediatype"],
                    size=item["size"],
                    duration=item["duration"])
                session.add(newplaylistRow)
                session.commit()
            else:
                if existitem.filename != item["filename"]:
                    existitem.filename = item["filename"]
                if existitem.duration != item["duration"]:
                    existitem.duration = item["duration"]
                if existitem.urlpath != item["path"]:
                    existitem.urlpath = item["path"]
                if existitem.iotpath != iotPath:
                    existitem.iotpath = iotPath
                if existitem.tag != item["tag"]:
                    existitem.tag = item["tag"]
                # status 状态:0 启用,1停用,2,已删除,20,待删除,10:待启用,11:准备中,
                if existitem.status == 2:
                    existitem.status = 10
                elif existitem.status in (1, 20):
                    existitem.status = 0
                if existitem.status == 0:
                    #本地文件夹
                    #localPath = sys.path[0] + "/resources/"
                    localPath = baseDir + "/resources/"
                    #本地文件路径
                    localFile = localPath + existitem.mediaid + existitem.extension
                    #检查本地文件是否已存在,如果存在则无需下载
                    if not os.path.exists(localFile):
                        existitem.status = 10
                session.commit()
                logger.info("资源" + item["filename"] + "(" + item["id"] +
                            ")已注册")
        except Exception as err:
            logger.warning(
                "资源验证失败:" + item["filename"] + "(" + item["id"] + "),%s", err)
    return idlist
Example #3
0
def playMediaWorker(deviceHost):
    #检查是否到达禁播时间
    global NoADUntil
    if deviceHost in NoADUntil:
        noadtime = NoADUntil[deviceHost]
        if  datetime.datetime.now().timetuple() < noadtime:
            time.sleep(3)
            _thread.start_new_thread(playMediaWorker,(deviceHost,))
            return

    #处理重启情况
    if checkAppStopAction():
        return

    try:
        #获取设备信息
        deviceInfo = None
        for dev in ShopDevices:
            if dev["name"] == deviceHost:
                deviceInfo = dev
        if deviceInfo == None or deviceInfo["name"] != deviceHost:
            return
        if deviceInfo["state"] != "On":
            logger.warning( deviceInfo["name"]+"设备已停用。")
            return
        logger.info("获取设备" + deviceInfo["name"] + "的播放列表")
        
        mediafile = getNextMediaFile(deviceHost)
        if mediafile == None :
            logger.info("设备" + deviceInfo["name"] + "无可播放的媒体资源")
            time.sleep(30)
            _thread.start_new_thread(playMediaWorker,(deviceHost,))
            return
        threadDuration = mediafile["duration"] / 1000 - 1
        if threadDuration < 0:
            threadDuration = 0

        logger.info("播放媒体文件" + mediafile["filename"] + "至" + deviceInfo["name"] + ",执行时间:" + str(threadDuration) + "秒")
        if deviceInfo["protocol"] == "DLNA":
            threadDuration -= 2
            localfilename ="http://" +LocalHttpHost +":" +LocalHttpPort + "/"+ mediafile["mediaid"] + mediafile["extension"]
            logger.info("视频文件地址:"+localfilename)
            _thread.start_new_thread(playVedio,(deviceInfo["name"] , localfilename))
        elif deviceInfo["protocol"] == "AudioCard":
            threadDuration +=2
            localfilename = "resources/"+ mediafile["mediaid"] + mediafile["extension"]
            logger.info("本机声卡播放:"+localfilename)
            _thread.start_new_thread(playMusic,(deviceInfo["name"], localfilename))
        else:
            pass

        session = playlistdb.GetDbSession()
        targetRow = (session.query(playlistdb.PlayList)
                    .filter(playlistdb.PlayList.playlistid == mediafile["id"])
                    .first())
        if targetRow != None:
            targetRow.lastplaytime = datetime.datetime.now()
            targetRow.playcount = targetRow.playcount+1
            targetRow.modifiedon = datetime.datetime.now()
            session.commit()
        time.sleep(threadDuration)
        _thread.start_new_thread(playMediaWorker,(deviceHost,))
    except Exception as err:
        logger.error( deviceHost+ ",播放媒体出错。%s",err)
        time.sleep(5)
        _thread.start_new_thread(playMediaWorker,(deviceHost,))
Example #4
0
def downloadResource():
    #处理重启情况
    if checkAppStopAction():
        return
    logger.info("查找需要下载的资源")
    session2 = playlistdb.GetDbSession()
    playlistTarget = (session2.query(playlistdb.PlayList)
        .filter(or_(playlistdb.PlayList.status == 10,playlistdb.PlayList.status == 11))
        .first())
    if playlistTarget != None :
        logger.info("资源" + playlistTarget.filename + "准备下载中...")
        url = ResourceHost + quote(playlistTarget.urlpath) + quote(playlistTarget.filename)
        #本地文件夹
        localPath = sys.path[0] + "/resources/"
        #本地文件路径
        localFile = localPath + playlistTarget.mediaid + playlistTarget.extension
        #检查本地文件是否已存在,如果存在则无需下载
        if os.path.exists(localFile) :
            finfo = os.stat(localFile)
            if finfo.st_size == playlistTarget.size :
                logger.info("文件" + playlistTarget.filename + "已存在,无需下载")
                playlistTarget.status = 0
                playlistTarget.modifiedon = datetime.datetime.now()
                session2.commit()
                _thread.start_new_thread(downloadResource,())
                return
            else:
                #处理未下载完成的任务
                try:
                    os.remove(localFile)
                except Exception as err:
                    logger.warning("文件" + localFile + "已存在,下载未完成,但无法访问。%s",err)
                    time.sleep(5)
                    _thread.start_new_thread(downloadResource,())
                    return
        
        if playlistTarget.status != 11:
            playlistTarget.status = 11
            playlistTarget.modifiedon = datetime.datetime.now()
            session2.commit()
        logger.info("资源下载" + playlistTarget.filename + ".请求:" + url)
        try:
            response = requests.get(url, stream=True)
            response.raise_for_status()
            with open(localFile,"wb") as wfile:
                for chunk in response.iter_content(chunk_size=1024 * 8):
                    if chunk:
                        wfile.write(chunk)
                wfile.close()
        except Exception as err:
            logger.error("资源" + playlistTarget.filename + "下载发生错误.%s",err)
            playlistTarget.status = 10
            playlistTarget.modifiedon = datetime.datetime.now()
            time.sleep(5)
            _thread.start_new_thread(downloadResource,())
            return
        finfo = os.stat(localFile)
        if finfo.st_size == playlistTarget.size :
            logger.info("资源" + playlistTarget.filename + "下载完成")
            playlistTarget.status = 0
            playlistTarget.modifiedon = datetime.datetime.now()
            loadPlaylist()
        else:
            logger.error("资源" + playlistTarget.filename + "下载失败")
            os.remove(localFile)
            playlistTarget.status = 10
            time.sleep(1)
            playlistTarget.modifiedon = datetime.datetime.now()
        session2.commit()
        time.sleep(1)
        _thread.start_new_thread(downloadResource,())
    else:  
        logger.info("没有需要下载的资源")
        time.sleep(60)
        _thread.start_new_thread(downloadResource,())
Example #5
0
def checkPlayList(): 
    if checkAppStopAction():
        return
    #检查是否有更新
    checkFileURI = PlaylistURI+'.txt'
    try:
        checkRequest = requests.get(checkFileURI)
    except Exception as err:
        logger.error("无法获取更新标记文本信息,请检查网络.%s",err)
        return
    if checkRequest.status_code == 200:
        checkCode = checkRequest.text
    else:
        logger.error("请求媒体更新标记失败")
    with open(_LAST_UPDATE_,'r') as cf:
        localCheckCode = cf.read()
    if localCheckCode == checkCode:
        logger.info("媒体列表未发现更新。")
        return
    #获取媒体列表
    logger.info("获取资源数据,资源地址:"+PlaylistURI)
    if PlaylistURI == '':
        logger.warning("未配置资料主机地址。")
        return
    #注册新文件
    try:
        confRequest = requests.get(PlaylistURI)
    except Exception as err:
        logger.error("无法获取播放资源.%s",err)
        return
    playlistIds = []
    if confRequest.status_code == 200 :
        logger.info("资源单获取成功,进行验证")
        jdata = json.loads(confRequest.text)
        for i in jdata:
            pfiles = playPlanWorker(i)
            if pfiles != None :
                playlistIds = playlistIds + pfiles
    else:
        logger.warning("资源单获取失败")

    #处理已删除文件
    session = playlistdb.GetDbSession()
    notdelFiles = (session.query(playlistdb.PlayList)
                            .filter(playlistdb.PlayList.status != 20))
    nflist = []
    for nf in notdelFiles:
        nflist.append(nf.mediaid)
    diffFiles = list(set(nflist).difference(set(playlistIds)))
    isDirty = False
    for nf in notdelFiles:
        if nf.mediaid in diffFiles:
            logger.info(nf.filename + "文件标记为删除")
            nf.status = 20
            isDirty = True
    if isDirty:
        session.commit()
    diffFiles = list(set(playlistIds).difference(set(nflist)))
    loadPlaylist()
    with open(_LAST_UPDATE_,'w') as cf:
        cf.writelines(checkCode)
    logger.info("资源检查完成")