예제 #1
0
 def manual(path):
     try:
         plugin_root = os.path.dirname(P.blueprint.template_folder)
         filepath = os.path.join(plugin_root,  *path.split('/'))
         from tool_base import ToolBaseFile
         data = ToolBaseFile.read(filepath)
         return render_template('manual.html', data=data)
     except Exception as exception:
         P.logger.error('Exception:%s', exception)
         P.logger.error(traceback.format_exc())
예제 #2
0
def edit_file():
    path = request.args.get('path')

    if path is None:
        return error('No path in request')

    os_file_path = web_path_to_os_path(path)

    # Load the contents of the file
    from tool_base import ToolBaseFile

    #content = util.read_file(os_file_path).decode()
    #content = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
    content = ToolBaseFile.read(os_file_path)
    return get_file(path=path, content=content)
예제 #3
0
    def insert_info_xml(db_filepath, metadata_type):
        con = sqlite3.connect(db_filepath)

        ce = con.execute(
            'SELECT title, hash FROM metadata_items WHERE metadata_type BETWEEN 1 AND 2'
        )
        ce.row_factory = dict_factory
        datas = ce.fetchall()
        count = len(datas)
        for idx, item in enumerate(datas):
            row_ce = con.execute('SELECT hash FROM metadata WHERE hash = ?',
                                 (item['hash'], ))
            row_ce.row_factory = dict_factory
            row = row_ce.fetchall()
            if len(row) == 1:
                logger.warning(
                    f"{idx+1} / {count} : {item['title']} Already Info.xml saved"
                )
            elif len(row) == 0:
                metapath = os.path.join(
                    ModelSetting.get('base_path_metadata'),
                    'Movies' if metadata_type == 1 else 'TV Shows',
                    item['hash'][0], f"{item['hash'][1:]}.bundle", 'Contents',
                    '_combined', 'Info.xml')
                #logger.debug(metapath)
                if os.path.exists(metapath):
                    xml = ToolBaseFile.read(metapath)
                    insert_ce = con.execute(
                        'INSERT INTO metadata (hash, data) VALUES (?,?)',
                        (item['hash'], xml))
                    logger.warning(
                        f"{idx+1} / {count} : {item['title']} insert..")
                else:
                    logger.warning(
                        f"{idx+1} / {count} : {item['title']} Not exist Info.xml file"
                    )
        con.commit()
        con.close()
예제 #4
0
파일: plugin.py 프로젝트: soju6jan/SJVA3
def ajax(sub):
    logger.debug('AJAX %s %s', package_name, sub)
    try:
        if sub == 'foreground_command':
            command = request.form['command']
            ret = LogicNormal.foreground_command(command)
            return jsonify(ret)
        elif sub == 'foreground_command_close':
            ret = LogicNormal.foreground_command_close()
            return jsonify(ret)
        elif sub == 'job_new':
            ret = {}
            ret['ret'] = ModelCommand.job_new(request)
            ret['list'] = ModelCommand.job_list()
            return jsonify(ret)
        elif sub == 'job_save':
            ret = {}
            ret['ret'] = ModelCommand.job_save(request)
            ret['list'] = ModelCommand.job_list()
            return jsonify(ret)
        elif sub == 'scheduler_switch':
            ret = {}
            ret['ret'] = LogicNormal.scheduler_switch0(request)
            ret['list'] = ModelCommand.job_list()
            return jsonify(ret)
        elif sub == 'job_remove':
            ret = {}
            ret['ret'] = ModelCommand.job_remove(request)
            ret['list'] = ModelCommand.job_list()
            return jsonify(ret)
        elif sub == 'job_log_show':
            ret = {}
            job_id = request.form['job_id']
            ret['filename'] = '%s_%s.log' % (package_name, job_id)
            ret['ret'] = os.path.exists(
                os.path.join(path_data, 'log', ret['filename']))
            return jsonify(ret)
        elif sub == 'job_background':
            ret = {}
            job_id = request.form['job_id']
            ret['ret'] = LogicNormal.job_background(job_id)
            return jsonify(ret)
        elif sub == 'job_file_edit':
            ret = {}
            job_id = request.form['job_id']
            job = ModelCommand.get_job_by_id(job_id)
            ret['data'] = ToolBaseFile.read(job.filename)
            ret['ret'] = True
            return jsonify(ret)
        elif sub == 'file_save':
            ret = {}
            job_id = request.form['file_job_id']
            logger.debug(job_id)
            data = request.form['file_textarea']
            job = ModelCommand.get_job_by_id(job_id)
            ToolBaseFile.write(data.replace('\r\n', '\n'), job.filename)
            ret['ret'] = True
            return jsonify(ret)
        elif sub == 'foreground_command_by_job':
            ret = {}
            job_id = request.form['job_id']
            job = ModelCommand.get_job_by_id(job_id)
            ret['ret'] = LogicNormal.foreground_command(job.command,
                                                        job_id=job_id)
            return jsonify(ret)
        elif sub == 'process_close':
            ret = {'ret': 'fail'}
            job_id = request.form['job_id']
            if LogicNormal.process_close(
                    LogicNormal.process_list[int(job_id)]):
                ret['ret'] = 'success'
            return jsonify(ret)

        elif sub == 'send_process_command':
            ret = LogicNormal.send_process_command(request)
            return jsonify(ret)
        elif sub == 'command_list':
            ret = {}
            ret['list'] = ModelCommand.job_list()
            return jsonify(ret)
        elif sub == 'save':
            ret = {}
            ret['ret'] = LogicNormal.save(request)
            ret['list'] = ModelCommand.job_list()
            return jsonify(ret)

    except Exception as exception:
        logger.error('Exception:%s', exception)
        logger.error(traceback.format_exc())
예제 #5
0
    def process_ajax(self, sub, req):
        try:
            ret = {}
            if sub == 'command':
                command = req.form['command']
                if command == 'size':
                    #if req.form['arg1'] in ['plex_data', 'plex_db']:
                    path = req.form['arg2']
                    self.task_interface('size', (path, ))
                    ret = {
                        'ret': 'success',
                        'msg': '명령을 전달하였습니다. 잠시 후 결과 알림을 확인하세요.'
                    }
                elif command == 'execute':
                    if req.form['arg1'] == 'scanner':
                        data = ToolSubprocess.execute_command_return(
                            [req.form['arg2']])
                        data = data.replace('\n',
                                            '<br>').lstrip('"').rstrip('"')
                        ret['modal'] = data
                    elif req.form['arg1'] == 'sqlite':
                        data = []
                        data.append(f"SQLite 버전")
                        data.append(
                            f" - {ToolSubprocess.execute_command_return([req.form['arg2'], '-version'])}"
                        )
                        data.append("")
                        data.append(f"Plex Media Server 버전")
                        data.append(
                            f" - {ToolSubprocess.execute_command_return([req.form['arg2'], '--version'])}"
                        )
                        data = '<br>'.join(data)
                        ret['modal'] = data
                elif command == 'backup':
                    if req.form['arg1'] == 'plex_db':
                        self.task_interface('backup', (req.form['arg2'], ))
                        ret = {
                            'ret': 'success',
                            'msg': '명령을 전달하였습니다. 잠시 후 결과 알림을 확인하세요.'
                        }
                elif command == 'db':
                    if req.form['arg1'] == 'library_sections':
                        data = PlexDBHandle.library_sections(req.form['arg2'])
                        ret['modal'] = json.dumps(data,
                                                  indent=4,
                                                  ensure_ascii=False)
                elif command == 'clear':
                    if req.form['arg1'] == 'plex_phototranscode':
                        path = req.form['arg2']
                        self.task_interface('clear', (path, ))
                        ret = {
                            'ret': 'success',
                            'msg': '명령을 전달하였습니다. 잠시 후 결과 알림을 확인하세요.'
                        }
                elif command == 'system_agents':
                    data = PlexWebHandle.system_agents(url=req.form['arg1'],
                                                       token=req.form['arg2'])
                    data = json.loads(json.dumps(xmltodict.parse(data)))
                    ret['modal'] = json.dumps(data,
                                              indent=4,
                                              ensure_ascii=False)
                elif command == 'version':
                    url = req.form['arg1']
                    token = req.form['arg2']
                    msg = f"SJVA.bundle : {PlexWebHandle.get_sjva_version(url=url, token=token)}<br>SjvaAgent : {PlexWebHandle.get_sjva_agent_version(url=url, token=token)}<br>"
                    regex = re.compile("VERSION\s=\s'(?P<version>.*?)'")
                    text = requests.get(
                        'https://raw.githubusercontent.com/soju6jan/SJVA.bundle/master/SJVA.bundle/Contents/Code/version.py'
                    ).text
                    match = regex.search(text)
                    if match:
                        msg += u'SJVA.bundle (최신) : ' + match.group('version')
                    text = requests.get(
                        'https://raw.githubusercontent.com/soju6jan/SjvaAgent.bundle/main/Contents/Code/version.py'
                    ).text
                    match = regex.search(text)
                    if match:
                        msg += u'<br>SjvaAgent (최신) : ' + match.group(
                            'version')
                    return jsonify({'ret': 'success', 'msg': msg})
                elif command == 'make_sql':
                    self.make_sql()

            elif sub == 'plex_folder_test':
                program_path = req.form['program_path']
                data_path = req.form['data_path']
                if os.path.exists(program_path) == False:
                    ret = {'ret': 'fail', 'msg': '데이터 폴더가 없습니다.'}
                elif os.path.exists(data_path) == False:
                    ret = {'ret': 'fail', 'msg': '프로그램 폴더가 없습니다.'}
                else:
                    ret['data'] = {}
                    ret['data']['bin_scanner'] = os.path.join(
                        program_path, 'Plex Media Scanner')
                    ret['data']['bin_sqlite'] = os.path.join(
                        program_path, 'Plex SQLite')
                    ret['data']['path_db'] = os.path.join(
                        data_path, 'Plug-in Support', 'Databases',
                        'com.plexapp.plugins.library.db')
                    ret['data']['path_metadata'] = os.path.join(
                        data_path, 'Metadata')
                    ret['data']['path_media'] = os.path.join(
                        data_path, 'Media')
                    ret['data']['path_phototranscoder'] = os.path.join(
                        data_path, 'Cache', 'PhotoTranscoder')

                    if platform.system() == 'Windows':
                        ret['data']['bin_scanner'] += '.exe'
                        ret['data']['bin_sqlite'] += '.exe'
                        ret['data']['token'] = ModelSetting.get(
                            f'{name}_token')
                    else:
                        xml_string = ToolBaseFile.read(
                            os.path.join(data_path, 'Preferences.xml'))
                        result = xmltodict.parse(xml_string)
                        prefs = json.loads(json.dumps(result))
                        logger.warning(d(prefs))
                        ret['data']['token'] = prefs['Preferences'][
                            '@PlexOnlineToken']
                        ret['data']['machine'] = prefs['Preferences'][
                            '@ProcessedMachineIdentifier']

                    for key, value in ret['data'].items():
                        if key not in ['token', 'machine']:
                            if os.path.exists(value) == False:
                                ret = {
                                    'ret': 'fail',
                                    'msg': '올바른 경로가 아닙니다.<br>' + value
                                }
                                return jsonify(ret)
                    ret['ret'] = 'success'
                    ret['msg'] = '설정을 저장하세요.'
            return jsonify(ret)
        except Exception as e:
            P.logger.error(f'Exception:{str(e)}')
            P.logger.error(traceback.format_exc())
            return jsonify({'ret': 'danger', 'msg': str(e)})