Exemple #1
0
class DanmuService(Service):

    def __init__(self):
        self.danmu = Danmu()
        self.log = Log('Danmu Service')
        self.command = _Operation()
        self.command_map = {
            '点歌': self.command.order_song,
            'Nami': ''
        }

    def run(self):
        try:
            self.parse_danmu()
            time.sleep(10)
        except Exception as e:
            self.log.error(e)

    def parse_danmu(self):
        """解析弹幕"""
        danmu_list = self.danmu.get()
        if danmu_list:
            for danmu in danmu_list:
                self.log.debug('%s: %s' % (danmu['name'], danmu['text']))
                self.danmu_map_func(danmu)

    def danmu_map_func(self, danmu):
        """将对应的指令映射到对应的Action上"""
        text = danmu['text']
        for key in self.command_map.keys():
            # 遍历查询comand是否存在 若存在则反射到对应的Action
            if text.find(key) == 0:
                danmu['command'] = danmu['text'][len(key): len(danmu['text'])].strip()
                self.command_map[key](danmu)
                break
Exemple #2
0
 def refresh_file_list(self, dir_path):
     novel_file_list = scan(unicode(dir_path))
     self.treeView.setModel(ProcessModel(self.treeView, novel_file_list))
     self.treeView.connect(self.treeView.selectionModel(),
                           SIGNAL("currentRowChanged(QModelIndex, QModelIndex)"),
                           self.save_and_load_novel_info)
     Log.info(u'加载小说目录[%s]完成'%dir_path)
Exemple #3
0
 def __init__(self):
     self.parseExcel = ParseExcel()
     self.log = Log()
     self.select = SelectTheSorting()
     self.pa = PageAction()
     self.pj = ParseJson()
     self.rm = RequestMethod()
 def navigate(url, locatorExpress):
     try:
         KeyWordsAction.driver.get(url)
         Log.info("访问URL:%s" % (url))
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("访问URL:%s异常" % (url))
         print str(e)
 def close_browser(value, elementExpress):
     try:
         KeyWordsAction.driver.quit()
         Log.info("关闭浏览器")
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("关闭浏览器y异常")
         print str(e)
 def sleep(second, elementExpress):
     try:
         time.sleep(second)
         Log.info("睡觉%d秒" % (second))
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("睡觉%d秒异常" % (second))
         print str(e)
Exemple #7
0
 def __init__(self):
     self.danmu = Danmu()
     self.log = Log('Danmu Service')
     self.command = _Operation()
     self.command_map = {
         '点歌': self.command.order_song,
         'Nami': ''
     }
Exemple #8
0
 def refresh_image_list(self, dir_path):
     for novel in self.treeView.model().novels():
         desc, portrait = self.db.query_novel_info(novel.title)
         if not os.path.exists(portrait):
             portrait = os.path.join(str(self.imageFilePath.text()), novel.title+'.jpg')
             if not os.path.exists(portrait):
                 portrait = os.path.join(str(self.imageFilePath.text()), novel.title+'.png')
             self.db.save_novel_info(novel.title, desc, portrait)
     Log.info(u'加载封面目录[%s]完成'%dir_path)
 def __init__(self):
     self.danmu = Danmu()
     self.musicDownloader = NeteaseMusic()
     self.log = Log('Danmu Service')
     self.commandMap = {
         '点歌': 'selectSongAction',
         'id': 'selectSongByIdAction'
     }
     pass
Exemple #10
0
class NewHtmlReport(object):
    def __init__(self):
        self.log = Log()

    def html(self, testSystem, caseSum, testPass, testFail, start_time,
             end_time, casePass, caseFail, id, step, motion, locatorExpression,
             value, expect, getText, locatorExpressionResult, runResult):
        table_tr2 = ""
        a = [
            "id", "step", "motion", "locatorExpression", "value", "expect",
            "getText", "locatorExpressionResult", "runResult"
        ]
        if type(id) == list:
            for i in range(len(id)):
                results = []
                results += [
                    id[i], step[i], motion[i], locatorExpression[i], value[i],
                    expect[i], getText[i], locatorExpressionResult[i],
                    runResult[i]
                ]
                b = results
                c = zip(a, b)
                d = dict(c)
                table_td_case = REPORT_TMPL_CASE % dict(
                    id=d["id"],
                    step=d["step"],
                    motion=d["motion"],
                    locatorExpression=d["locatorExpression"],
                    value=d["value"],
                    expect=d["expect"],
                    getText=d["getText"],
                    locatorExpressionResult=d["locatorExpressionResult"],
                    runResult=d["runResult"],
                    detail_id=d["id"],
                    hiddenRow_id=d["id"])
                table_tr2 += table_td_case

        table_td = html_template % dict(testSystem=testSystem,
                                        caseSum=caseSum,
                                        testPass=testPass,
                                        testFail=testFail,
                                        start_time=start_time,
                                        end_time=end_time,
                                        casePass=casePass,
                                        caseFail=caseFail,
                                        table_try=table_tr2)
        filename = '{name}测试报告.html'.format(name=testSystem)
        dir = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            'report')
        filename = os.path.join(dir, filename)
        # print(filename)
        self.log.info("用例执行完成请查看测试报告:" + filename)
        with open(filename, 'wb') as f:
            f.write(table_td.encode('utf8'))
 def __init__(self):
     self.danmu = Danmu()
     self.config = Config()
     self.neteaseMusic = NeteaseMusic()
     self.log = Log('Danmu Service')
     self.commandMap = {
         '点歌=': 'selectSongAction',
         'id=': 'selectSongByIdAction',
         'mv=': 'selectMvByIdAction',
         '切歌': 'DebugAction'
     }
     pass
 def click(value, locatorExpress):
     try:
         KeyWordsAction.driver.find_element(
             by=KeyWordsAction.objectMap.getLocator("baidu",
                                                    locatorExpress)[0],
             value=KeyWordsAction.objectMap.getLocator(
                 "baidu", locatorExpress)[1]).click()
         Log.info("点击搜索按钮")
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("点击搜索按钮异常")
         print str(e)
 def waitfor(value, elementExpress):
     try:
         KeyWordsAction.driver.implicitly_wait(10)
         KeyWordsAction.driver.find_element(
             by=KeyWordsAction.objectMap.getLocator("baidu",
                                                    elementExpress)[0],
             value=KeyWordsAction.objectMap.getLocator(
                 "baidu", elementExpress)[1])
         Log.info("智能等待")
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("智能等待异常")
         print str(e)
 def input(value, locatorExpress):
     try:
         KeyWordsAction.driver.find_element(
             by=KeyWordsAction.objectMap.getLocator("baidu",
                                                    locatorExpress)[0],
             value=KeyWordsAction.objectMap.getLocator(
                 "baidu", locatorExpress)[1]).clear()
         KeyWordsAction.driver.find_element(
             by=KeyWordsAction.objectMap.getLocator("baidu",
                                                    locatorExpress)[0],
             value=KeyWordsAction.objectMap.getLocator(
                 "baidu", locatorExpress)[1]).send_keys(value)
         Log.info("在输入框输入%s" % (value))
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("在输入框输入%s异常" % (value))
         print str(e)
Exemple #15
0
    def __init__(self):
        # 初始化变量
        self.config = Config()
        self.cookies = self.config.getCookies()

        self.log = Log('service/Msg')
        self.msg = Msg(self.cookies)
        self.robot = Robot(self.config.get('api_keys'))

        self.uid = int(self.cookies['DedeUserID'])
        self.admin_ids = self.config.get('admin_ids')
        self.receiver_ids = self.config.get('receiver_ids')
        self.cookies_str = self.config.get('cookies')
        self.userList = {}
        self.groupList = {}

        self.is_private = self.config.get('is_private')
Exemple #16
0
    def __init__(self):
        super(MainWindow, self).__init__()
        # uic.loadUi('ui/MainWindow.ui', self)
        self.setupUi(self)
        self.db = DB()
        self.timer = QtCore.QTimer()
        self.thread_pool = ThreadPool(1)
        self.portraitView.setScene(PortraitDisplayScene())
        # 选择小说内容所在目录
        self.novelFileSelector.connect(self.novelFileSelector,
                                       SIGNAL("clicked()"),
                                       lambda: self.update_input_text(self.novelFilePath))
        # 选择小说封面所在目录
        self.imageFileSelector.connect(self.imageFileSelector,
                                       SIGNAL("clicked()"),
                                       lambda: self.update_input_text(self.imageFilePath))
        # 内容目录更改后同步更新左面列表
        self.novelFilePath.connect(self.novelFilePath,
                                   SIGNAL("textChanged(QString)"),
                                   self.refresh_file_list)
        self.imageFilePath.connect(self.imageFilePath,
                                   SIGNAL("textChanged(QString)"),
                                   self.refresh_image_list)
        # 内容目录更改后保存到历史记录
        self.novelFilePath.connect(self.novelFilePath,
                                   SIGNAL("textChanged(QString)"),
                                   lambda x: self.db.save_param('LAST_NOVEL_PATH', str(x)))
        # 图片目录更改后保存到历史记录
        self.imageFilePath.connect(self.imageFilePath,
                                   SIGNAL("textChanged(QString)"),
                                   lambda x: self.db.save_param('LAST_IMAGE_PATH', str(x)))
        # 开始转换
        self.startConvert.connect(self.startConvert,
                                  SIGNAL("clicked()"),
                                  lambda: self.thread_pool.add_task(self.start_convert))
        # 日志定时刷新
        self.timer.connect(self.timer, SIGNAL("timeout()"), self.showLog)

        self.novelFilePath.setText(self.db.get_param('LAST_NOVEL_PATH'))
        self.imageFilePath.setText(self.db.get_param('LAST_IMAGE_PATH'))

        self.timer.start(100)
        Log.info(u'系统初始化完成...')
Exemple #17
0
class DownloadService(Service):
    def __init__(self):
        self.danmu = Danmu()
        self.log = Log('Download Service')
        self.musicDownloader = NeteaseMusic()

    # 获取下载队列 分发至下载函数
    def run(self):
        try:
            # 判断队列是否为空
            if DownloadQueue.empty():
                return

            # 获取新的下载任务
            task = DownloadQueue.get()
            if task and 'type' in task:
                if task['type'] == 'music':
                    self.musicDownload(task)
                elif task['type'] == 'vedio':
                    pass
        except Exception as e:
            self.log.error(e)
            pass

    def musicDownload(self, song):

        # 搜索歌曲并下载
        self.danmu.send('正在下载%s' % song['name'])
        filename = self.musicDownloader.download(song['id'])

        if filename:
            self.log.info('歌曲下载完毕 %s - %s' % (song['name'], song['singer']))

            # 加入播放队列
            PlayQueue.put({
                'type': 'music',
                'filename': filename,
                'name': song['name'],
                'singer': song['singer'],
                'username': song['username']
            })
        else:
            pass
Exemple #18
0
def genAll(novels, target_html_dir):
    db = DB()
    for novel in novels:
        Log.info(u'处理文件[%s]' % novel.file_name)
        novel_cur_dir = os.path.join(target_html_dir, novel.safe_title)
        if not os.path.exists(novel_cur_dir):
            os.mkdir(novel_cur_dir)
        write(novel_cur_dir, 'index.html', genNovelIndex(novel))
        desc, portrait = db.query_novel_info(novel.title)
        if portrait:
            shutil.copy(portrait, os.path.join(novel_cur_dir, 'post.jpg'))
        else:
            Log.warn(u'小说[%s]未找到封面图片' % novel.title)
        for volume in novel.volumes:
            if volume.content:
                write(novel_cur_dir, volume.safe_name + '.html',
                      genChapter(volume, volume))
            for chapter in volume.sub_chapters:
                write(novel_cur_dir,
                      volume.safe_name + '-' + chapter.safe_name + '.html',
                      genChapter(volume, chapter))
    write(target_html_dir, 'index.html', genIndex(novels))
Exemple #19
0
    def start_convert(self):
        Log.info(u'-------------------------开始生成 HTML-------------------------')
        novel_root_dir = unicode(self.novelFilePath.text())
        target_html_dir = os.path.join(novel_root_dir, 'html')
        if not os.path.exists(target_html_dir):
            os.makedirs(target_html_dir)

        Log.info(u'输出目录定位到:%s'%target_html_dir)
        HtmlGenerator.genAll(self.treeView.model().novels(), target_html_dir)
        Log.info(u'--------------------------任-务-完-成--------------------------')
Exemple #20
0
class Downloader:
    logger = Log("downloader")

    def __init__(self,
                 delay=5,
                 user_agent=r"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT)",
                 num_retries=1):
        """

        :param delay:
        :param user_agent:
        :param prxies:
        :param num_retries:
        :param cache:
        """
        self.throttle = Throttle(delay)
        self.user_agent = user_agent
        self.num_retries = num_retries

    def __call__(self, url):
        result = self.download(url=url,
                               headers={"User-Agent": self.user_agent},
                               num_retries=self.num_retries)
        return result

    def download(self, url, headers, num_retries):
        self.logger.i("Downloading: " + url)
        try:
            req = requests.get(url, headers=headers)
            html = req.text
            if self.num_retries > 0 and 500 <= req.status_code < 600:
                # 服务器错误则忽略缓存并重新下载
                html = None
        except reqException as e:
            self.logger.e(e)
            html = None
            if num_retries > 0:
                if hasattr(e, 'code') and 500 <= e.code <= 600:
                    html = self.download(url=url,
                                         headers=headers,
                                         num_retries=num_retries - 1)
        if html is None:
            self.throttle.wait(url)
            html = self.download(url=url,
                                 headers=headers,
                                 num_retries=num_retries)
        return html
 def open_browser(browserName, locatorExpress):
     try:
         if str(browserName).lower() == "ie":
             #或许还要指定驱动
             KeyWordsAction.driver = webdriver.Ie()
             Log.info("IE 实例已经声明")
         elif str(browserName).lower() == "chrome":
             #或许还要指定驱动
             KeyWordsAction.driver = webdriver.Chrome()
             Log.info("Chorme 实例已经声明")
         elif str(browserName).lower() == "firefox":
             #或许还要指定驱动
             KeyWordsAction.driver = webdriver.Firefox()
             Log.info("Firefox 实例已经声明")
     except Exception, e:
         KeyWordsAction.testResult = False
         Log.info("浏览器实例已经声明异常")
         print str(e)
Exemple #22
0
class SelectTheSorting(object):

    # 构造函数
    def __init__(self):
        self.login = Login()
        self.pa = PageAction()
        self.pj = ParseJson()
        self.log = Log()

    def selectSort(self, area, branch):
        # 登录
        self.login.loginMethod()
        # 选择区域
        # if area == "北京区域":
        # 选择区域
        self.pa.pageMotion(motion='click', locatorExpression="//input[@placeholder='请选择二级组织']")

        self.pa.pageMotion(motion='click', locatorExpression="//span[contains(text()," + "'" + area + "' " + ")]")
        self.log.info("选择" + area)
        if branch != None:
            self.pa.pageMotion(motion='click', locatorExpression="//input[@placeholder='请选择三级组织']")
            self.pa.pageMotion(motion='click', locatorExpression="//span[contains(text()," + "'" + branch + "' " + ")]")
            self.log.info("选择" + branch)
        else:
            pass
        # print("//span[contains(text(),"+"'"+area+"' " +")]")
        # 选择角色
        self.pa.pageMotion(motion='click', locatorExpression="//input[@placeholder='请选择角色']")
        self.pa.pageMotion(motion='click', locatorExpression="//span[contains(text(), '分院IT')]")
        self.log.info("选择分院IT角色")
        self.pa.pageMotion(motion='click_sleep', locatorExpression="//button[@type='button']")
        self.log.info("点击进入")

    def role(self):
        # print(self.pj.getRoleData("area"))
        # print()
        self.pa.pageMotion(motion='click', locatorExpression="//input[@placeholder='请选择二级组织']")
        self.pa.pageMotion(motion='click', locatorExpression="//span[contains(text()," + "'" + self.pj.getRoleData(
            "area") + "' " + ")]")
        self.pa.pageMotion(motion='click', locatorExpression="//input[@placeholder='请选择三级组织']")
        self.pa.pageMotion(motion='click', locatorExpression="//span[contains(text()," + "'" + self.pj.getRoleData(
            "branch") + "' " + ")]")
Exemple #23
0
    def connect(self):
        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)
        sta_if.connect(self.configuration.wifi.ssid, self.configuration.wifi.secret)

        while not sta_if.isconnected():
            self.rgb_led.blink(self.rgb_led.red_led)

        log = Log()
        log.write_log("IP configuration :")
        log.write_log(str(sta_if.ifconfig()))
        self.rgb_led.blink(self.rgb_led.green_led)
        return sta_if
Exemple #24
0
class _Operation(object):

    def __init__(self):
        self.danmu = Danmu()
        self.log = Log('Danmu Service')
        self.downloader = NeteaseMusic()

    def order_song(self, danmu):
        """点歌台"""
        # 如果命令全为数字,跳转到id点歌
        if danmu['command'].isdigit():
            song = self._order_song_id(danmu)
        # 否则按照歌名点歌
        else:
            song = self._order_song_name(danmu)

        if song:
            self.danmu.send('%s 点歌成功' % song['name'])
            DownloadQueue.put({
                    'type': 'music',
                    'id': song['id'],
                    'name': song['name'],
                    'singer': song['ar'][0]['name'],
                    'username': danmu['name']
            })
        else:
            self.danmu.send('找不到%s' % danmu['command'])
            self.log.info('找不到%s' % danmu['command'])

    def _order_song_name(self, danmu):
        """通过歌名点歌"""
        self.log.info('%s 点歌 [%s]' % (danmu['name'], danmu['command']))
        detail = danmu['command'].split('-')
        if len(detail) == 1:
            # 按歌曲名点歌
            song = self.downloader.search_single(danmu['command'].strip())
        elif len(detail) == 2:
            # 按歌曲名-歌手点歌
            song = self.downloader.search_single(detail[0].strip(), detail[1].strip())
        else:
            # 无效命令
            song = {}
        return song

    def _order_song_id(self, danmu):
        """通过id点歌"""
        self.log.info('%s id点歌 [%s]' % (danmu['name'], danmu['command']))
        song = self.downloader.get_info(danmu['command'].strip())
        return song
Exemple #25
0
class Login(object):

    # 构造函数
    def __init__(self):
        self.pa = PageAction()
        self.pc = ParseConfig()
        self.log = Log()

    # 登录方法
    def loginMethod(self):
        # 打开浏览器
        self.pa.openBrowser(self.pc.getValue("addres", "url"))
        self.log.info("打开浏览器")
        # 输入用户名
        self.pa.pageMotion(motion="input", locatorExpression="//input[@placeholder='请输入账号']",
                           value=self.pc.getValue("login", "username"))
        self.log.info("输入用户名")
        # 输入密码
        self.pa.pageMotion(motion="input", locatorExpression="//input[@placeholder='请输入密码']",
                           value=self.pc.getValue("login", "password"))
        self.log.info("输入密码")
        # 点击登录
        self.pa.pageMotion(motion="click", locatorExpression="//button[@type='button']")
        self.log.info("点击登录")
Exemple #26
0
 def __init__(self):
     self.pj = ParseJson()
     self.log = Log()
Exemple #27
0
class RequestMethod(object):
    def __init__(self):
        self.pj = ParseJson()
        self.log = Log()

    def runMethod(self, caseCount, startTime, casePresent):
        testPlanId = self.pj.gettestPlanId('testPlanId')
        if testPlanId == "0":

            header = {"Content-Type": "application/json"}
            data = {
                "baseSchemeId": self.pj.getbaseSchemeId('baseSchemeId'),
                "caseCount": caseCount,
                "startTime": startTime,
                "casePresent": casePresent,
                "testPlanId": ""
            }
            try:
                res = requests.post(
                    url="http://uat.atp.ikang.com/atp-api/report/testing",
                    data=json.dumps(data),
                    headers=header).json()
                time.sleep(2)
                self.log.info("进度条接口返回:" + json.dumps(res, ensure_ascii=False))
            except Exception as e:
                self.log.info("接口请求失败: %s" % e)

        else:

            header = {"Content-Type": "application/json"}
            data = {
                "baseSchemeId": self.pj.getbaseSchemeId('baseSchemeId'),
                "caseCount": caseCount,
                "startTime": startTime,
                "casePresent": casePresent,
                "testPlanId": testPlanId
            }
            try:
                res = requests.post(
                    url="http://uat.atp.ikang.com/atp-api/report/testing",
                    data=json.dumps(data),
                    headers=header).json()
                time.sleep(2)
                self.log.info("进度条接口返回:" + json.dumps(res, ensure_ascii=False))
            except Exception as e:
                self.log.info("接口请求失败: %s" % e)

    def uploading(self, caseCount, endTime, failureRate, systemName,
                  passingRate, startTime, message):

        testPlanId = str(self.pj.gettestPlanId("testPlanId"))

        if testPlanId == "0":
            data = MultipartEncoder({
                "baseSchemeId":
                str(self.pj.getbaseSchemeId("baseSchemeId")),
                "caseCount":
                str(caseCount),
                "endTime":
                str(endTime),
                "failRate":
                str(failureRate),
                "file":
                (systemName, open(report + systemName + "测试报告.html",
                                  'rb'), 'text/plain'),
                "passRate":
                str(passingRate),
                "startTime":
                str(startTime),
                "testResult":
                str(message),
                "testPlanId":
                ""
            })
            try:
                res = requests.post(
                    url='http://uat.atp.ikang.com/atp-api/report/upload',
                    data=data,
                    headers={
                        'Content-Type': data.content_type
                    }).json()
                time.sleep(2)
                self.log.info("上传接口返回:" + json.dumps(res, ensure_ascii=False))
            except Exception as e:
                self.log.info("请求接口失败:%s" % e)

        else:
            data = MultipartEncoder({
                "baseSchemeId":
                str(self.pj.getbaseSchemeId("baseSchemeId")),
                "caseCount":
                str(caseCount),
                "endTime":
                str(endTime),
                "failRate":
                str(failureRate),
                "file":
                (systemName, open(report + systemName + "测试报告.html",
                                  'rb'), 'text/plain'),
                "passRate":
                str(passingRate),
                "startTime":
                str(startTime),
                "testResult":
                str(message),
                "testPlanId":
                ""
            })
            try:
                res = requests.post(
                    url='http://uat.atp.ikang.com/atp-api/report/upload',
                    data=data,
                    headers={
                        'Content-Type': data.content_type
                    }).json()
                time.sleep(2)
                self.log.info("上传接口返回:" + json.dumps(res, ensure_ascii=False))
            except Exception as e:
                self.log.info("请求接口失败:%s" % e)
class DanmuService(Service):
    
    def __init__(self):
        self.danmu = Danmu()
        self.musicDownloader = NeteaseMusic()
        self.log = Log('Danmu Service')
        self.commandMap = {
            '点歌': 'selectSongAction',
            'id': 'selectSongByIdAction'
        }
        pass

    def run(self):
        try:
            self.parseDanmu()
            time.sleep(1.5)
        except Exception as e:
            self.log.error(e)

    # 解析弹幕
    def parseDanmu(self):
        danmuList = self.danmu.get()
        if danmuList:
            for danmu in danmuList:
                self.log.debug('%s: %s' % (danmu['name'], danmu['text']))
                self.danmuStateMachine(danmu)

    # 将对应的指令映射到对应的Action上
    def danmuStateMachine(self, danmu):
        text = danmu['text']
        commandAction = ''
        for key in self.commandMap:
            # 遍历查询comand是否存在 若存在则反射到对应的Action
            if text.find(key) == 0 and hasattr(self, self.commandMap[key]):
                danmu['command'] = danmu['text'][len(key) : len(danmu['text'])]
                getattr(self, self.commandMap[key])(danmu)
                break
        pass

    # 歌曲名点歌
    def selectSongAction(self, danmu):
        self.log.info('%s 点歌 [%s]' % (danmu['name'], danmu['command']))

        command = danmu['command']
        song = []
        # 按歌曲名-歌手点歌
        if command.find('-') != -1:
            detail = command.split('-')
            if len(detail) == 2:
                song = self.musicDownloader.searchSingle(detail[0], detail[1])
            else:
                # 查询失败
                song = {}
                pass
        # 直接按歌曲名点歌
        else:
            song = self.musicDownloader.searchSingle(danmu['command'])

        if song:
            self.danmu.send('%s点歌成功' % song['name'])
            DownloadQueue.put({
                    'type': 'music',
                    'id': song['id'],
                    'name': song['name'],
                    'singer': song['singer'],
                    'username': danmu['name']
                })
        else:
            # 未找到歌曲
            self.danmu.send('找不到%s' % danmu['command'])
            self.log.info('找不到%s' % danmu['command'])
            pass

    # 通过Id点歌
    def selectSongByIdAction(self, danmu):
        command = danmu['command']
        try:
            song = self.musicDownloader.getInfo(command)
            if song:
                self.danmu.send('%s点歌成功' % song['name'])
                DownloadQueue.put({
                        'type': 'music',
                        'id': song['id'],
                        'name': song['name'],
                        'singer': song['singer'],
                        'username': danmu['name']
                    })
            else:
                # 未找到歌曲
                raise Exception('未找到歌曲')
        except Exception as e:
            self.danmu.send('找不到%s' % danmu['command'])
            self.log.info('找不到%s' % danmu['command'])
Exemple #29
0
 def __init__(self):
     self.danmu = Danmu()
     self.log = Log('Media Service')
     self.config = Config()
Exemple #30
0
class MediaService(Service):

    def __init__(self):
        self.danmu = Danmu()
        self.log = Log('Media Service')
        self.config = Config()

    def run(self):
        try:
            # 判断队列是否为空
            if PlayQueue.empty():
                # 获取随机文件,播放
                musicPath = './resource/music/'
                randomMusic = self.getRandomFile(musicPath)

                musicName = os.path.basename(randomMusic)
                musicName = musicName.replace(os.path.splitext(randomMusic)[1], '')

                self.playMusic({
                    'username': '******',
                    'name': musicName,
                    'filename': musicPath + randomMusic
                }, True)
                return

            # 获取新的下载任务
            task = PlayQueue.get()
            if task and 'type' in task:
                if task['type'] == 'music':
                    self.playMusic(task)
                elif task['type'] == 'vedio':
                    pass

        except Exception as e:
            self.log.error(e)

    # 播放音乐
    def playMusic(self, music, autoPlay=False):
        imagePath = './resource/img/'
        randomImage = imagePath + self.getRandomFile(imagePath)
        self.log.info('[Music] 开始播放[%s]点播的[%s]' % (music['username'], music['name']))
        self.danmu.send('正在播放 %s' % music['name'])

        # 获取歌词
        assPath = './resource/lrc/default.ass'
        if 'lrc' in music:
            assPath = music['lrc']

        # 开始播放
        command = ffmpeg().getMusic(music=music['filename'], output=self.getRTMPUrl(), image=randomImage, ass=assPath)
        command = "%s 2>> ./log/ffmpeg.log" % command
        self.log.debug(command)
        process = subprocess.Popen(args=command, cwd=os.getcwd(), shell=True)
        process.wait()

        # 播放完毕
        if not autoPlay:
            os.remove(path=music['filename'])
        self.log.info('[Music] [%s]播放结束' % music['name'])

    # 获取推流地址
    def getRTMPUrl(self):
        url = self.config.get(module='rtmp', key='url')
        code = self.config.get(module='rtmp', key='code')
        return url + code

    # 获取随机文件
    def getRandomFile(self, path):
        fileList = os.listdir(path)
        if len(fileList) == 0:
            raise Exception('无法获取随机文件,%s为空' % path)

        index = random.randint(0, len(fileList) - 1)
        return fileList[index]