This commit is contained in:
soju6jan
2022-10-02 20:18:05 +09:00
parent b9c3aac91f
commit 29930fdef7
150 changed files with 53982 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
VERSION="4.0.0"
from support import d
from .init_main import Framework
frame = Framework.get_instance()
F = frame
logger = frame.logger
app = frame.app
celery = frame.celery
db = frame.db
scheduler = frame.scheduler
socketio = frame.socketio
path_app_root = frame.path_app_root
path_data = frame.path_data
get_logger = frame.get_logger
from .init_declare import check_api, User
from flask_login import login_required
from .scheduler import Job
frame.initialize_system()
from system.setup import SystemModelSetting
frame.initialize_plugin()
+102
View File
@@ -0,0 +1,102 @@
from flask import request, abort
from functools import wraps
from flask import request
def check_api(original_function):
@wraps(original_function)
def wrapper_function(*args, **kwargs): #1
from framework import F
#logger.debug('CHECK API... {} '.format(original_function.__module__))
#logger.warning(request.url)
#logger.warning(request.form)
try:
if F.SystemModelSetting.get_bool('auth_use_apikey'):
if request.method == 'POST':
apikey = request.form['apikey']
else:
apikey = request.args.get('apikey')
#apikey = request.args.get('apikey')
if apikey is None or apikey != F.SystemModelSetting.get('auth_apikey'):
F.logger.warning('CHECK API : ABORT no match ({})'.format(apikey))
F.logger.warning(request.environ.get('HTTP_X_REAL_IP', request.remote_addr))
abort(403)
return
except Exception as e:
F.logger.warning('CHECK API : ABORT exception')
abort(403)
return
return original_function(*args, **kwargs) #2
return wrapper_function
# Suuport를 logger 생성전에 쓰지 않기 위해 중복 선언
import logging
class CustomFormatter(logging.Formatter):
"""Logging Formatter to add colors and count warning / errors"""
grey = "\x1b[38;21m"
yellow = "\x1b[33;21m"
red = "\x1b[31;21m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
green = "\x1B[32m"
# pathname filename
#format = "[%(asctime)s|%(name)s|%(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
format = '[{yellow}%(asctime)s{reset}|{color}%(levelname)s{reset}|{green}%(name)s{reset}|%(pathname)s:%(lineno)s] {color}%(message)s{reset}'
FORMATS = {
logging.DEBUG: format.format(color=grey, reset=reset, yellow=yellow, green=green),
logging.INFO: format.format(color=green, reset=reset, yellow=yellow, green=green),
logging.WARNING: format.format(color=yellow, reset=reset, yellow=yellow, green=green),
logging.ERROR: format.format(color=red, reset=reset, yellow=yellow, green=green),
logging.CRITICAL: format.format(color=bold_red, reset=reset, yellow=yellow, green=green)
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
# Suuport를 logger 생성전에 쓰지 않기 위해 중복 선언
def read_yaml(filepath):
import yaml
with open(filepath, encoding='utf8') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
return data
class User:
def __init__(self, user_id, email=None, passwd_hash=None, authenticated=False):
self.user_id = user_id
self.email = email
self.passwd_hash = passwd_hash
self.authenticated = authenticated
def __repr__(self):
r = {
'user_id': self.user_id,
'email': self.email,
'passwd_hash': self.passwd_hash,
'authenticated': self.authenticated,
}
return str(r)
def can_login(self, passwd_hash):
from support.base.aes import SupportAES
tmp = SupportAES.decrypt(self.passwd_hash)
return passwd_hash == tmp
def is_active(self):
return True
def get_id(self):
return self.user_id
def is_authenticated(self):
return self.authenticated
def is_anonymous(self):
return False
+442
View File
@@ -0,0 +1,442 @@
import os, sys, traceback, time, logging, logging.handlers, shutil, platform
from datetime import datetime
from pytz import timezone, utc
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO
from flask_cors import CORS
from flaskext.markdown import Markdown
from flask_login import LoginManager, login_required
from .init_declare import check_api, CustomFormatter
class Framework:
__instance = None
@classmethod
def get_instance(cls):
if cls.__instance == None:
cls.__instance = Framework()
return cls.__instance
def __init__(self):
self.logger = None
self.app = None
self.celery = None
self.db = None
self.scheduler = None
self.socketio = None
self.path_app_root = None
self.path_data = None
self.users = {}
self.__level_unset_logger_list = []
self.__logger_list = []
self.__exit_code = -1
self.login_manager = None
#self.plugin_instance_list = {}
#self.plugin_menus = {}
# 그냥 F. 로 접근 하게....
self.SystemModelSetting = None
self.Job = None
self.login_required = login_required
self.check_api = check_api
self.__initialize()
def __initialize(self):
self.__config_initialize("first")
self.__make_default_dir()
self.logger = self.get_logger(__package__)
from support import set_logger
set_logger(self.logger)
self.__prepare_starting()
self.app = Flask(__name__)
self.__config_initialize('flask')
self.db = SQLAlchemy(self.app, session_options={"autoflush": False})
if True or self.config['run_flask']:
from .scheduler import Scheduler, Job
self.scheduler = Scheduler(self)
self.Job = Job
if self.config['use_gevent']:
self.socketio = SocketIO(self.app, cors_allowed_origins="*")
else:
self.socketio = SocketIO(self.app, cors_allowed_origins="*", async_mode='threading')
CORS(self.app)
Markdown(self.app)
self.login_manager = LoginManager()
self.login_manager.init_app(self.app)
self.login_manager.login_view = "/system/login"
self.celery = self.__init_celery()
def __init_celery(self):
try:
from celery import Celery
#if frame.config['use_celery'] == False or platform.system() == 'Windows':
if self.config['use_celery'] == False:
raise Exception('no celery')
try:
redis_port = os.environ['REDIS_PORT']
except:
redis_port = '6379'
self.app.config['CELERY_BROKER_URL'] = 'redis://localhost:%s/0' % redis_port
self.app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:%s/0' % redis_port
celery = Celery(self.app.name, broker=self.app.config['CELERY_BROKER_URL'], backend=self.app.config['CELERY_RESULT_BACKEND'])
celery.conf['CELERY_ENABLE_UTC'] = False
celery.conf.update(
task_serializer='pickle',
result_serializer='pickle',
accept_content=['pickle'],
timezone='Asia/Seoul'
)
from celery import bootsteps
from celery.bin import Option
celery.user_options['worker'].add(
Option('--config_filepath', action='store', dest='config_filepath', default='.', help='')
)
class CustomArgs(bootsteps.Step):
def __init__(self, worker, config_filepath=None, **options):
from . import F
F.logger.info("celery config filepath: {config_filepath}")
celery.steps['worker'].add(CustomArgs)
except Exception as e:
self.logger.error('CELERY!!!')
self.logger.error(f'Exception:{str(e)}')
self.logger.error(traceback.format_exc())
def dummy_func():
pass
class celery(object):
class task(object):
def __init__(self, *args, **kwargs):
if len(args) > 0:
self.f = args[0]
def __call__(self, *args, **kwargs):
if len(args) > 0 and type(args[0]) == type(dummy_func):
return args[0]
self.f(*args, **kwargs)
return celery
def initialize_system(self):
from system.setup import P
SystemInstance = P
try:
self.db.create_all()
except Exception as e:
self.logger.error('CRITICAL db.create_all()!!!')
self.logger.error(f'Exception:{str(e)}')
self.logger.error(traceback.format_exc())
SystemInstance.plugin_load()
self.app.register_blueprint(SystemInstance.blueprint)
self.config['flag_system_loading'] = True
self.__config_initialize('member')
self.__config_initialize('system_loading_after')
self.SystemModelSetting = SystemInstance.ModelSetting
def initialize_plugin(self):
from system.setup import P as SP
from .init_web import jinja_initialize
jinja_initialize(self.app)
#system.LogicPlugin.custom_plugin_update()
from .init_plugin import PluginManager
self.PluginManager = PluginManager
PluginManager.plugin_init()
PluginManager.plugin_menus['system'] = {'menu':SP.menu, 'match':False}
#from .init_menu import init_menu, get_menu_map
from .init_menu import MenuManager
MenuManager.init_menu()
#init_menu(self.plugin_menu)
#system.SystemLogic.apply_menu_link()
if self.config['run_flask']:
if self.config.get('port') == None:
self.config['port'] = SP.SystemModelSetting.get_int('port')
from . import log_viewer
from . import init_route
self.__make_default_logger()
self.logger.info('### LAST')
self.logger.info(f"### PORT: {self.config['port']}")
self.logger.info('### Now you can access App by webbrowser!!')
def __prepare_starting(self):
# 여기서 monkey.patch시 너무 늦다고 문제 발생
if self.config['run_flask'] and self.config.get('use_celery') == True:
try:
from gevent import monkey
#from gevent import monkey;monkey.patch_all()
#print('[MAIN] gevent mokey patch!!')
#sys.getfilesystemencoding = lambda: 'UTF-8'
except:
self.config['use_celery'] = False
print('[MAIN] gevent not installed!!')
###################################################
# 환경
###################################################
def __config_initialize(self, mode):
if mode == "first":
self.config = {}
self.config['os'] = platform.system()
self.config['flag_system_loading'] = False
self.config['run_flask'] = True if sys.argv[0].endswith('main.py') else False
self.config['run_celery'] = True if sys.argv[0].find('celery') != -1 else False
self.config['path_app'] = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if self.config['os'] == 'Windows' and self.config['path_app'][0] != '/':
self.config['path_app'] = self.config['path_app'][0].upper() + self.config['path_app'][1:]
self.path_app_root = self.config['path_app']
self.config['path_working'] = os.getcwd()
self.__process_args()
self.__load_config()
self.__init_define()
elif mode == "flask":
self.app.secret_key = os.urandom(24)
#self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/db/system.db?check_same_thread=False'
self.app.config['SQLALCHEMY_BINDS'] = {}
self.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
self.app.config['TEMPLATES_AUTO_RELOAD'] = True
self.app.config['JSON_AS_ASCII'] = False
elif mode == 'system_loading_after':
pass
#from system import SystemModelSetting
"""
app.config['config']['running_type'] = 'native'
if 'SJVA_RUNNING_TYPE' in os.environ:
app.config['config']['running_type'] = os.environ['SJVA_RUNNING_TYPE']
else:
import platform
if platform.system() == 'Windows':
app.config['config']['running_type'] = 'windows'
"""
def __init_define(self):
self.config['DEFINE'] = {}
# 이건 필요 없음
self.config['DEFINE']['MAIN_SERVER_URL'] = 'https://server.sjva.me'
def __process_args(self):
# celery 에서 args 처리시 문제 발생.
if self.config['run_flask']:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='.', help='config filepath. Default: {current folder}/config.yaml')
parser.add_argument('--repeat', default=0, type=int, help=u'Do not set. This value is set by automatic')
args = parser.parse_args()
self.config['arg_repeat'] = args.repeat
self.config['arg_config'] = args.config
else:
# 아주 안좋은 구조..
# celery user_options으로 configfilepath를 받은 후 처리해야하나, 로그파일 경로 등에서 데이터 폴더 위치를 미리 사용하는 경우가 많다.
# sys.argv에서 데이터 경로를 바로 가져와서 사용.
self.config['arg_repeat'] = 0
self.config['arg_config'] = sys.argv[-1].split('=')[-1]
#self.config['arg_config'] =
def __load_config(self):
from .init_declare import read_yaml
#if self.config['run_flask']:
if self.config['arg_config'] == '.':
#self.config['config_filepath'] = os.path.join(self.path_app_root, 'config.yaml')
self.config['config_filepath'] = os.path.join(self.config['path_working'], 'config.yaml')
if not os.path.exists(self.config['config_filepath']):
shutil.copy(
os.path.join(self.path_app_root, 'files', 'config.yaml.template'),
self.config['config_filepath']
)
else:
self.config['config_filepath'] = self.config['arg_config']
#os.environ['FLASK_FARM_CONFIG_FILEPATH'] = self.config['config_filepath']
#else:
# self.config['config_filepath'] = os.environ['FLASK_FARM_CONFIG_FILEPATH']
# self.logger.info(f"CELERY config : {self.config['config_filepath']}")
data = read_yaml(self.config['config_filepath'])
for key, value in data.items():
self.config[key] = value
if self.config['path_data'] == '.':
self.config['path_data'] = self.config['path_working']
# 예외적으로 현재폴더가 app일 경우 지저분해지는 것을 방지하기 위해 data 로 지정
if self.config['path_data'] == self.config['path_working']:
self.config['path_data'] = os.path.join(self.config['path_working'], 'data')
self.path_data = self.config['path_data']
def __make_default_dir(self):
os.makedirs(self.config['path_data'], exist_ok=True)
tmp = os.path.join(self.config['path_data'], 'tmp')
try:
import shutil
if os.path.exists(tmp):
shutil.rmtree(tmp)
except:
pass
sub = ['db', 'log', 'tmp']
for item in sub:
tmp = os.path.join(self.config['path_data'], item)
os.makedirs(tmp, exist_ok=True)
###################################################
###################################################
# 로그
###################################################
def get_logger(self, name):
logger = logging.getLogger(name)
if not logger.handlers:
level = logging.DEBUG
try:
if self.config['flag_system_loading']:
try:
from system import SystemModelSetting
level = SystemModelSetting.get_int('log_level')
except:
level = logging.DEBUG
if self.__level_unset_logger_list is not None:
for item in self.__level_unset_logger_list:
item.setLevel(level)
self.__level_unset_logger_list = None
else:
self.__level_unset_logger_list.append(logger)
if name.startswith('apscheduler'):
level = logging.CRITICAL
else:
self.__logger_list.append(logger)
except:
pass
logger.setLevel(level)
file_formatter = logging.Formatter(u'[%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s] %(message)s')
def customTime(*args):
utc_dt = utc.localize(datetime.utcnow())
my_tz = timezone("Asia/Seoul")
converted = utc_dt.astimezone(my_tz)
return converted.timetuple()
file_formatter.converter = customTime
file_max_bytes = 1 * 1024 * 1024
fileHandler = logging.handlers.RotatingFileHandler(filename=os.path.join(self.path_data, 'log', f'{name}.log'), maxBytes=file_max_bytes, backupCount=5, encoding='utf8', delay=True)
streamHandler = logging.StreamHandler()
# handler에 fommater 세팅
fileHandler.setFormatter(file_formatter)
streamHandler.setFormatter(CustomFormatter())
# Handler를 logging에 추가
logger.addHandler(fileHandler)
logger.addHandler(streamHandler)
return logger
def __make_default_logger(self):
self.get_logger('apscheduler.scheduler')
self.get_logger('apscheduler.executors.default')
try: logging.getLogger('socketio').setLevel(logging.ERROR)
except: pass
try: logging.getLogger('engineio').setLevel(logging.ERROR)
except: pass
try: logging.getLogger('apscheduler.scheduler').setLevel(logging.ERROR)
except: pass
try: logging.getLogger('apscheduler.executors.default').setLevel(logging.ERROR)
except: pass
try: logging.getLogger('werkzeug').setLevel(logging.ERROR)
except: pass
def set_level(self, level):
try:
for l in self.__logger_list:
l.setLevel(level)
self.__make_default_logger()
except:
pass
###################################################
def start(self):
host = '0.0.0.0'
for i in range(10):
try:
#self.logger.debug(d(self.config))
self.socketio.run(self.app, host=host, port=self.config['port'], debug=self.config['debug'], use_reloader=self.config['use_reloader'])
self.logger.warning(f"EXIT CODE : {self.__exit_code}")
# 2021-05-18
if self.config['running_type'] in ['termux', 'entware']:
os._exit(self.__exit_code)
else:
if self.__exit_code != -1:
sys.exit(self.__exit_code)
else:
self.logger.warning(f"framework.exit_code is -1")
break
except Exception as exception:
self.logger.error(f"Start ERROR : {str(exception)}")
host = '127.0.0.1'
time.sleep(10*i)
continue
except KeyboardInterrupt:
self.logger.error('KeyboardInterrupt !!')
#except SystemExit:
# return
#sys.exit(self.__exit_code)
# system 플러그인에서 콜
def restart(self):
self.__exit_code = 1
self.__app_close()
def shutdown(self):
self.__exit_code = 0
self.__app_close()
def __app_close(self):
try:
from .init_plugin import PluginManager
PluginManager.plugin_unload()
self.socketio.stop()
except Exception as exception:
self.logger.error('Exception:%s', exception)
self.logger.error(traceback.format_exc())
def get_recent_version(self):
try:
import requests
url = f"{self.config['DEFINE']['MAIN_SERVER_URL']}/version"
self.config['recent_version'] = requests.get(url).text
return True
except Exception as e:
self.logger.error(f'Exception:{str(e)}')
self.logger.error(traceback.format_exc())
self.config['recent_version'] = '확인 실패'
return False
+104
View File
@@ -0,0 +1,104 @@
import os, copy, shutil
from framework import F, d
from support.base.yaml import SupportYaml
class MenuManager:
menu_map = None
@classmethod
def __load_menu_yaml(cls):
menu_yaml_filepath = os.path.join(F.config['path_data'], 'db', 'menu.yaml')
if os.path.exists(menu_yaml_filepath) == False:
shutil.copy(
os.path.join(F.config['path_app'], 'files', 'menu.yaml.template'),
menu_yaml_filepath
)
cls.menu_map = SupportYaml.read_yaml(menu_yaml_filepath)
"""
for cate in cls.menu_map:
cate['count'] = 0
cls.menu_map.insert(len(cls.menu_map)-1, {
'name':'미분류', 'count':0, 'list':[]
})
cls.menu_map[-1]['count'] = 1
F.logger.debug(cls.menu_map)
"""
@classmethod
def init_menu(cls):
#F.logger.debug(d(plugin_menus))
#print(plugin_menus)
cls.__load_menu_yaml()
from .init_plugin import PluginManager
plugin_menus = PluginManager.plugin_menus
copy_map = []
for category in cls.menu_map:
if 'uri' in category:
copy_map.append(category)
continue
cate_count = 0
tmp_cate_list = []
for item in category['list']:
if item['uri'] in plugin_menus:
plugin_menus[item['uri']]['match'] = True
tmp_cate_list.append(plugin_menus[item['uri']]['menu'])
cate_count += 1
elif item['uri'].startswith('http'):
tmp_cate_list.append({
'uri': item['uri'],
'name': item['name'],
'target': item.get('target', '_blank')
})
cate_count += 1
elif (len(item['uri'].split('/')) > 1 and item['uri'].split('/')[0] in plugin_menus) or item['uri'].startswith('javascript') or item['uri'] in ['-']:
tmp_cate_list.append({
'uri': item['uri'],
'name': item.get('name', ''),
})
cate_count += 1
elif item['uri'] == 'setting':
if len(PluginManager.setting_menus) > 0:
tmp_cate_list.append({
'uri': item['uri'],
'name': item.get('name', ''),
'list': PluginManager.setting_menus
})
if cate_count > 0:
copy_map.append({
'name': category['name'],
'list': tmp_cate_list,
'count': cate_count
})
cls.menu_map = copy_map
make_dummy_cate = False
for name, plugin_menu in plugin_menus.items():
#F.logger.info(d(plugin_menu))
#if 'uri' not in plugin_menu['menu']:
# continue
if plugin_menu['match'] == False:
if make_dummy_cate == False:
make_dummy_cate = True
cls.menu_map.insert(len(cls.menu_map)-1, {
'name':'미분류', 'count':0, 'list':[]
})
c = cls.menu_map[-2]
c['count'] += 1
c['list'].append(plugin_menu['menu'])
#F.logger.warning(d(cls.menu_map))
@classmethod
def get_menu_map(cls):
return cls.menu_map
+293
View File
@@ -0,0 +1,293 @@
import os, sys, traceback, threading, platform
from framework import F, d
class PluginManager:
plugin_list = {}
plugin_menus = {}
setting_menus = []
@classmethod
def get_plugin_name_list(cls):
#if not app.config['config']['auth_status']:
# return
"""
plugin_path = os.path.join(frame.config['path_app'], 'plugins')
sys.path.insert(0, plugin_path)
from system import SystemModelSetting
plugins = os.listdir(plugin_path)
"""
plugins = []
pass_include = []
except_plugin_list = []
#2019-07-17
if F.config.get('plugin_loading_only_devpath', None) != True:
try:
plugin_path = os.path.join(F.config['path_data'], 'plugins')
if os.path.exists(plugin_path) == True and os.path.isdir(plugin_path) == True:
sys.path.insert(1, plugin_path)
tmps = os.listdir(plugin_path)
add_plugin_list = []
for t in tmps:
if not t.startswith('_') and os.path.isdir(os.path.join(plugin_path, t)):
add_plugin_list.append(t)
plugins = plugins + add_plugin_list
pass_include = pass_include + add_plugin_list
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
# 2018-09-04
try:
plugin_path = F.SystemModelSetting.get('plugin_dev_path')
if plugin_path != '':
if os.path.exists(plugin_path):
sys.path.insert(0, plugin_path)
tmps = os.listdir(plugin_path)
add_plugin_list = []
for t in tmps:
if not t.startswith('_') and os.path.isdir(os.path.join(plugin_path, t)):
add_plugin_list.append(t)
plugins = plugins + add_plugin_list
pass_include = pass_include + add_plugin_list
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
# plugin_loading_list
try:
plugin_loading_list = F.config.get('plugin_loading_list', None)
if plugin_loading_list != None and type(plugin_loading_list) == type([]):
new_plugins = []
for _ in plugins:
if _ in plugin_loading_list:
new_plugins.append(_)
plugins = new_plugins
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
# plugin_except_list
try:
plugin_except_list = F.config.get('plugin_except_list', None)
if plugin_except_list != None and type(plugin_except_list) == type([]):
new_plugins = []
for _ in plugins:
if _ not in plugin_except_list:
new_plugins.append(_)
plugins = new_plugins
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
return plugins
# menu, blueprint, plugin_info, plugin_load, plugin_unload
@classmethod
def plugin_init(cls):
try:
plugins = cls.get_plugin_name_list()
plugins = sorted(plugins)
F.logger.debug(plugins)
for plugin_name in plugins:
#logger.debug(len(system.LogicPlugin.current_loading_plugin_list))
#if plugin_name.startswith('_'):
# continue
#if plugin_name == 'terminal' and platform.system() == 'Windows':
# continue
#if plugin_name in except_plugin_list:
# F.logger.debug('Except plugin : %s' % frame.plugin_menu)
# continue
F.logger.debug(f'[+] PLUGIN LOADING Start.. [{plugin_name}]')
entity = {'version':'3'}
try:
mod = __import__('%s' % (plugin_name), fromlist=[])
mod_plugin_info = None
# 2021-12-31
#import system
#if plugin_name not in system.LogicPlugin.current_loading_plugin_list:
# system.LogicPlugin.current_loading_plugin_list[plugin_name] = {'status':'loading'}
try:
mod_plugin_info = getattr(mod, 'plugin_info')
entity['module'] = mod
"""
if 'category' not in mod_plugin_info and 'category_name' in mod_plugin_info:
mod_plugin_info['category'] = mod_plugin_info['category_name']
if 'policy_point' in mod_plugin_info:
if mod_plugin_info['policy_point'] > app.config['config']['point']:
system.LogicPlugin.current_loading_plugin_list[plugin_name]['status'] = 'violation_policy_point'
continue
if 'policy_level' in mod_plugin_info:
if mod_plugin_info['policy_level'] > app.config['config']['level']:
system.LogicPlugin.current_loading_plugin_list[plugin_name]['status'] = 'violation_policy_level'
continue
if 'category' in mod_plugin_info and mod_plugin_info['category'] == 'beta':
if SystemModelSetting.get_bool('use_beta') == False:
system.LogicPlugin.current_loading_plugin_list[plugin_name]['status'] = 'violation_beta'
continue
"""
except Exception as exception:
#logger.error('Exception:%s', exception)
#logger.error(traceback.format_exc())
#mod_plugin_info = getattr(mod, 'setup')
F.logger.warning(f'[!] PLUGIN_INFO not exist : [{plugin_name}]')
if mod_plugin_info == None:
try:
mod = __import__(f'{plugin_name}.setup', fromlist=['setup'])
entity['version'] = '4'
except Exception as e:
F.logger.error(f'Exception:{str(e)}')
F.logger.error(traceback.format_exc())
F.logger.warning(f'[!] NOT normal plugin : [{plugin_name}]')
#entity['version'] = 'not_plugin'
try:
if entity['version'] != '4':
mod_blue_print = getattr(mod, 'blueprint')
else:
entity['setup_mod'] = mod
entity['P'] = getattr(mod, 'P')
mod_blue_print = getattr(entity['P'], 'blueprint')
if mod_blue_print:
#if plugin_name in pass_include or is_include_menu(plugin_name):
F.app.register_blueprint(mod_blue_print)
except Exception as exception:
#logger.error('Exception:%s', exception)
#logger.error(traceback.format_exc())
F.logger.warning(f'[!] BLUEPRINT not exist : [{plugin_name}]')
cls.plugin_list[plugin_name] = entity
#system.LogicPlugin.current_loading_plugin_list[plugin_name]['status'] = 'success'
#system.LogicPlugin.current_loading_plugin_list[plugin_name]['info'] = mod_plugin_info
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
F.logger.debug('no blueprint')
#from tool_base import d
#logger.error(d(system.LogicPlugin.current_loading_plugin_list))
# 2021-07-01 모듈에 있는 DB 테이블 생성이 안되는 문제
# 기존 구조 : db.create_all() => 모듈 plugin_load => celery task 등록 후 리턴
# 변경 구조 : 모듈 plugin_load => db.create_all() => celery인 경우 리턴
# plugin_load 를 해야 하위 로직에 있는 DB가 로딩된다.
# plugin_load 에 db는 사용하는 코드가 있으면 안된다. (테이블도 없을 때 에러발생)
try:
#logger.warning('module plugin_load in celery ')
cls.plugin_list['mod']['module'].plugin_load()
except Exception as exception:
F.logger.debug(f'mod plugin_load error!!')
#logger.error('Exception:%s', exception)
#logger.error(traceback.format_exc())
# import가 끝나면 DB를 만든다.
# 플러그인 로드시 DB 초기화를 할 수 있다.
if not F.config['run_celery']:
try:
F.db.create_all()
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
F.logger.debug('db.create_all error')
if not F.config['run_flask']:
# 2021-06-03
# 모듈의 로직에 있는 celery 함수는 등록해주어야한다.
#try:
# logger.warning('module plugin_load in celery ')
# plugin_instance_list['mod'].plugin_load()
#except Exception as exception:
# logger.error('module plugin_load error')
# logger.error('Exception:%s', exception)
# logger.error(traceback.format_exc())
# 2021-07-01
# db때문에 위에서 로딩함.
return
for key, entity in cls.plugin_list.items():
try:
mod_plugin_load = None
if entity['version'] == '3':
mod_plugin_load = getattr(entity['module'], 'plugin_load')
elif entity['version'] == '4':
mod_plugin_load = getattr(entity['P'], 'plugin_load')
#if mod_plugin_load and (key in pass_include or is_include_menu(key)):
if mod_plugin_load:
def func(mod_plugin_load, key):
try:
F.logger.debug(f'[!] plugin_load threading start : [{key}]')
#mod.plugin_load()
mod_plugin_load()
F.logger.debug(f'[!] plugin_load threading end : [{key}]')
except Exception as exception:
F.logger.error('### plugin_load exception : %s', key)
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
# mod는 위에서 로딩
if key != 'mod':
t = threading.Thread(target=func, args=(mod_plugin_load, key))
t.setDaemon(True)
t.start()
#if key == 'mod':
# t.join()
except Exception as exception:
F.logger.debug(f'[!] PLUGIN_LOAD function not exist : [{key}]')
#logger.error('Exception:%s', exception)
#logger.error(traceback.format_exc())
#logger.debug('no init_scheduler')
try:
mod_menu = None
if entity['version'] == '3':
mod_menu = getattr(entity['module'], 'menu')
elif entity['version'] == '4':
mod_menu = getattr(entity['P'], 'menu')
if mod_menu:# and (key in pass_include or is_include_menu(key)):
cls.plugin_menus[key]= {'menu':mod_menu, 'match':False}
if entity['version'] == '4':
setting_menu = getattr(entity['P'], 'setting_menu')
if setting_menu != None:
cls.setting_menus.append(setting_menu)
except Exception as exception:
F.logger.debug('no menu')
F.logger.debug('### plugin_load threading all start.. : %s ', len(cls.plugin_list))
# 모든 모듈을 로드한 이후에 app 등록, table 생성, start
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
@classmethod
def plugin_unload(cls):
for key, entity in cls.plugin_list.items():
try:
if entity['version'] == '3':
mod_plugin_unload = getattr(entity['module'], 'plugin_unload')
elif entity['version'] == '4':
mod_plugin_unload = getattr(entity['P'], 'plugin_unload')
#if plugin_name == 'rss':
# continue
#mod_plugin_unload = getattr(mod, 'plugin_unload')
if mod_plugin_unload:
mod_plugin_unload()
#mod.plugin_unload()
except Exception as e:
F.logger.error('module:%s', key)
F.logger.error(f'Exception:{str(e)}')
F.logger.error(traceback.format_exc())
try:
from system.setup import P
P.plugin_unload()
except Exception as e:
F.logger.error(f'Exception:{str(e)}')
F.logger.error(traceback.format_exc())
+121
View File
@@ -0,0 +1,121 @@
# -*- coding: utf-8 -*-
#########################################################
# python
import os
import sys
from datetime import datetime, timedelta
import json
import traceback
# third-party
from flask import redirect, render_template, Response, request, jsonify, send_from_directory
from flask_login import login_user, logout_user, current_user, login_required
# sjva 공용
from framework import F, check_api, app, db, VERSION, logger, path_data
import system
@F.app.route('/global/ajax/<sub>', methods=['GET', 'POST'])
@login_required
def global_ajax(sub):
#logger.debug('/global/ajax/%s', sub)
if sub == 'listdir':
if 'path' in request.form:
#if os.path.isfile(request.form['path']):
# return jsonify('')
path = request.form['path']
if os.path.isfile(path):
path = os.path.dirname(path)
result_list = os.listdir(path)
if 'only_dir' in request.form and request.form['only_dir'].lower() == 'true':
result_list = [name for name in result_list if os.path.isdir(os.path.join(path, name))]
result_list.sort()
result_list = [f"{x}|{os.path.join(path,x)}" for x in result_list]
tmp = os.path.dirname(path)
if path != tmp:
result_list = [f'..|{tmp}'] + result_list
return jsonify(result_list)
else:
return jsonify(None)
elif sub == 'is_available_edit':
# globalEditBtn
try:
import flaskcode
return jsonify(True)
except:
return jsonify(True)
@app.route('/robots.txt')
def robot_to_root():
return send_from_directory('', 'static/file/robots.txt')
@app.route("/")
@app.route("/None")
@app.route("/home")
def home():
return redirect('/system/home')
@app.route("/version")
def get_version():
return VERSION
@app.route("/open/<path:path>")
@login_required
def open_file(path):
return send_from_directory('/', path)
@app.route("/file/<path:path>")
@check_api
def file2(path):
logger.debug('file2 :%s', path)
return send_from_directory('/', path)
@app.route("/up", methods=['GET', 'POST'])
def upload():
# curl -F file=@downloader_video.tar https://dev.soju6jan.com/up
#
try:
if request.method == 'POST':
f = request.files['file']
from werkzeug import secure_filename
tmp = secure_filename(f.filename)
logger.debug('upload : %s', tmp)
f.save(os.path.join(path_data, 'upload', tmp))
return jsonify('success')
except Exception as exception:
logger.error('Exception:%s', exception)
logger.error(traceback.format_exc())
return jsonify('fail')
+58
View File
@@ -0,0 +1,58 @@
import re
from flask_login import current_user
from framework import F
def get_menu(full_query):
match = re.compile(r'\/(?P<menu>.*?)\/manual\/(?P<sub2>.*?)($|\?)').match(full_query)
if match:
return match.group('menu'), 'manual', match.group('sub2')
match = re.compile(r'\/(?P<menu>.*?)\/(?P<sub>.*?)\/(?P<sub2>.*?)($|\/|\?)').match(full_query)
if match:
return match.group('menu'), match.group('sub'), match.group('sub2')
match = re.compile(r'\/(?P<menu>.*?)\/(?P<sub>.*?)($|\/|\?)').match(full_query)
if match:
return match.group('menu'), match.group('sub'), None
match = re.compile(r'\/(?P<menu>.*?)($|\/|\?)').match(full_query)
if match:
return match.group('menu'), None , None
return 'home', None, None
def get_theme():
return F.SystemModelSetting.get('theme')
#def get_login_status():
# if current_user is None:
# return False
# return current_user.is_authenticated
def get_web_title():
try:
return F.SystemModelSetting.get('web_title')
except:
return 'Home'
def is_https():
return (F.SystemModelSetting.get('ddns').find('https://') != -1)
def jinja_initialize(app):
#from .init_menu import get_menu_map, get_plugin_menu
from .init_menu import MenuManager
app.jinja_env.globals.update(get_menu=get_menu)
app.jinja_env.globals.update(get_theme=get_theme)
app.jinja_env.globals.update(get_menu_map=MenuManager.get_menu_map)
app.jinja_env.globals.update(get_web_title=get_web_title)
app.jinja_env.filters['get_menu'] = get_menu
app.jinja_env.filters['get_theme'] = get_theme
app.jinja_env.filters['get_menu_map'] = MenuManager.get_menu_map
app.jinja_env.filters['get_web_title'] = get_web_title
app.jinja_env.auto_reload = True
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
+132
View File
@@ -0,0 +1,132 @@
import os, traceback, time, threading
from flask import request
from framework import F
from support.base.util import SingletonClass
namespace = 'log'
@F.socketio.on('connect', namespace='/%s' % namespace)
def socket_connect():
F.logger.debug('log connect')
@F.socketio.on('start', namespace='/%s' % namespace)
def socket_file(data):
try:
package = filename = None
if 'package' in data:
package = data['package']
else:
filename = data['filename']
LogViewer.instance().start(package, filename, request.sid)
F.logger.debug('start package:%s filename:%s sid:%s', package, filename, request.sid)
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
@F.socketio.on('disconnect', namespace='/%s' % namespace)
def disconnect():
try:
LogViewer.instance().disconnect(request.sid)
F.logger.debug('disconnect sid:%s', request.sid)
except Exception as exception:
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
class WatchThread(threading.Thread):
def __init__(self, package, filename):
super(WatchThread, self).__init__()
self.stop_flag = False
self.package = package
self.filename = filename
self.daemon = True
def stop(self):
self.stop_flag = True
def run(self):
F.logger.debug('WatchThread.. Start %s', self.package)
if self.package is not None:
logfile = os.path.join(F.config['path_data'], 'log', f'{self.package}.log')
key = 'package'
value = self.package
else:
logfile = os.path.join(F.config['path_data'], 'log', self.filename)
key = 'filename'
value = self.filename
if os.path.exists(logfile):
with open(logfile, 'r') as f:
f.seek(0, os.SEEK_END)
while not self.stop_flag:
line = f.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
F.socketio.emit("add", {key : value, 'data': line}, namespace='/log', broadcast=True)
F.logger.debug('WatchThread.. End %s', value)
else:
F.socketio.emit("add", {key : value, 'data': 'not exist logfile'}, namespace='/log', broadcast=True)
class LogViewer(SingletonClass):
watch_list = {}
@classmethod
def start(cls, package, filename, sid):
# 2019-04-02 간만에 봤더니 헷깔려서 적는다
# 이 쓰레드는 오픈시 이전 데이타만을 보내는 쓰레드다. 실시간보는거 아님.
def thread_function():
if package is not None:
logfile = os.path.join(F.config['path_data'], 'log', f'{package}.log')
else:
logfile = os.path.join(F.config['path_data'], 'log', filename)
if os.path.exists(logfile):
ins_file = open(logfile, 'r', encoding='utf8') ## 3)
line = ins_file.read()
F.socketio.emit("on_start", {'data': line}, namespace='/log')
F.logger.debug('on_start end')
else:
F.socketio.emit("on_start", {'data': 'not exist logfile'}, namespace='/log')
if package is not None:
key = package
else:
key = filename
thread = threading.Thread(target=thread_function, args=())
thread.daemon = True
thread.start()
if key not in cls.watch_list:
cls.watch_list[key] = {}
cls.watch_list[key]['sid'] = []
cls.watch_list[key]['thread'] = WatchThread(package, filename)
cls.watch_list[key]['thread'].start()
cls.watch_list[key]['sid'].append(sid)
@classmethod
def disconnect(cls, sid):
find = False
find_key = None
for key, value in cls.watch_list.items():
F.logger.debug('key:%s value:%s', key, value)
for s in value['sid']:
if sid == s:
find = True
find_key = key
value['sid'].remove(s)
break
if find:
break
if not find:
return
if not cls.watch_list[find_key]['sid']:
F.logger.debug('thread kill')
cls.watch_list[find_key]['thread'].stop()
del cls.watch_list[find_key]
+253
View File
@@ -0,0 +1,253 @@
import traceback
from pytz import timezone
from datetime import datetime, timedelta
from random import randint
from apscheduler.jobstores.base import JobLookupError
from apscheduler.triggers.cron import CronTrigger
import traceback, threading
from datetime import datetime
from pytz import timezone
from random import randint
from support.base.util import pt
class Scheduler(object):
job_list = []
first_run_check_thread = None
def __init__(self, frame):
self.frame = frame
self.logger = frame.logger
try:
if frame.config['use_gevent']:
from apscheduler.schedulers.gevent import GeventScheduler
self.sched = GeventScheduler(timezone='Asia/Seoul')
else:
raise Exception('')
except:
from apscheduler.schedulers.background import BackgroundScheduler
self.sched = BackgroundScheduler(timezone='Asia/Seoul')
self.sched.start()
self.logger.info('SCHEDULER start..')
@pt
def first_run_check_thread_function(self):
try:
#time.sleep(60)
#for i in range(5):
flag_exit = True
for job_instance in self.job_list:
if not job_instance.run:
continue
if job_instance.count == 0 and not job_instance.is_running and job_instance.is_interval:
#if job_instance.count == 0 and not job_instance.is_running:
job = self.sched.get_job(job_instance.job_id)
if job is not None:
self.logger.warning('job_instance : %s', job_instance.plugin)
self.logger.warning('XX job re-sched:%s', job)
flag_exit = False
tmp = randint(1, 20)
job.modify(next_run_time=datetime.now(timezone('Asia/Seoul')) + timedelta(seconds=tmp))
#break
else:
pass
if flag_exit:
self.remove_job("scheduler_check")
#time.sleep(30)
except Exception as exception:
self.logger.error('Exception:%s', exception)
self.logger.error(traceback.format_exc())
def shutdown(self):
self.sched.shutdown()
def kill_scheduler(self, job_id):
try:
self.sched.remove_job(job_id)
except JobLookupError as err:
self.logger.debug("fail to stop Scheduler: {err}".format(err=err))
self.logger.debug(traceback.format_exc())
def add_job_instance(self, job_instance, run=True):
if self.frame.config['run_flask']:
if not self.is_include(job_instance.job_id):
job_instance.run = run
Scheduler.job_list.append(job_instance)
if job_instance.is_interval:
self.sched.add_job(job_instance.job_function, 'interval', minutes=job_instance.interval, seconds=job_instance.interval_seconds, id=job_instance.job_id, args=(None))
elif job_instance.is_cron:
self.sched.add_job(job_instance.job_function, CronTrigger.from_crontab(job_instance.interval), id=job_instance.job_id, args=(None))
job = self.sched.get_job(job_instance.job_id)
if run and job_instance.is_interval:
tmp = randint(5, 20)
job.modify(next_run_time=datetime.now(timezone('Asia/Seoul')) + timedelta(seconds=tmp))
def execute_job(self, job_id):
self.logger.debug('execute_job:%s', job_id)
job = self.sched.get_job(job_id)
tmp = randint(5, 20)
job.modify(next_run_time=datetime.now(timezone('Asia/Seoul')) + timedelta(seconds=tmp))
def is_include(self, job_id):
job = self.sched.get_job(job_id)
return (job is not None)
def remove_job(self, job_id):
try:
if self.is_include(job_id):
self.sched.remove_job(job_id)
job = self.get_job_instance(job_id)
if not job.is_running:
self.remove_job_instance(job_id)
self.logger.debug('remove job_id:%s', job_id)
return True
except JobLookupError as err:
self.logger.debug("fail to remove Scheduler: {err}".format(err=err))
self.logger.debug(traceback.format_exc())
return False
def get_job_instance(self, job_id):
for job in Scheduler.job_list:
if job.job_id == job_id:
return job
def is_running(self, job_id):
job = self.get_job_instance(job_id)
if job is None:
return False
else:
return job.is_running
# job에서만 호출한다..
def remove_job_instance(self, job_id):
# function이 실행중일때 제거하면..
# 실행중이나 목록에서 빠져버린다..
for job in Scheduler.job_list:
if job.job_id == job_id:
Scheduler.job_list.remove(job)
self.logger.debug('remove_job_instance : %s', job_id)
break
def get_job_list_info(self):
ret = []
idx = 0
job_list = self.sched.get_jobs()
#logger.debug('len jobs %s %s', len(jobs), len(Scheduler.job_list))
for j in job_list:
idx += 1
entity = {}
entity['no'] = idx
entity['id'] = j.id
entity['next_run_time'] = j.next_run_time.strftime('%m-%d %H:%M:%S')
remain = (j.next_run_time - datetime.now(timezone('Asia/Seoul')))
tmp = ''
if remain.days > 0:
tmp += '%s' % (remain.days)
remain = remain.seconds
if remain//3600 > 0:
tmp += '%s시간 ' % (remain//3600)
remain = remain % 3600
if remain // 60 > 0:
tmp += '%s' % (remain//60)
tmp += '%s' % (remain%60)
#entity['remain_time'] = (j.next_run_time - datetime.now(timezone('Asia/Seoul'))).seconds
entity['remain_time'] = tmp
job = self.get_job_instance(j.id)
if job is not None:
entity['count'] = job.count
entity['plugin'] = job.plugin
if job.is_cron:
entity['interval'] = job.interval
elif job.interval == 9999:
entity['interval'] = '항상 실행'
entity['remain_time'] = ''
else:
entity['interval'] = '%s%s' % (job.interval, job.interval_seconds)
entity['is_running'] = job.is_running
entity['description'] = job.description
entity['running_timedelta'] = job.running_timedelta.seconds if job.running_timedelta is not None else '-'
entity['make_time'] = job.make_time.strftime('%m-%d %H:%M:%S')
entity['run'] = job.run
else:
entity['count'] = ''
entity['plugin'] = ''
entity['interval'] = ''
entity['is_running'] = ''
entity['description'] = ''
entity['running_timedelta'] = ''
entity['make_time'] = ''
entity['run'] = True
ret.append(entity)
return ret
class Job(object):
def __init__(self, plugin, job_id, interval, target_function, description, args=None):
self.plugin = plugin
self.job_id = job_id
self.interval = '%s' % interval
self.interval_seconds = randint(1, 59)
self.target_function = target_function
self.description = description
self.is_running = False
self.thread = None
self.start_time = None
self.end_time = None
self.running_timedelta = None
self.status = None
self.count = 0
self.make_time = datetime.now(timezone('Asia/Seoul'))
if len(self.interval.strip().split(' ')) == 5:
self.is_cron = True
self.is_interval = False
else:
self.is_cron = False
self.is_interval = True
if self.is_interval:
if isinstance(self.interval, str):
self.interval = int(self.interval)
self.args = args
# true이고 interval이면 바로 실행
# false이면 스케쥴링시간이 되면 실행
# add_job_instance에서 true이면 20초 이내에 실행하려고 함.
# false이면 넣을 때는 실행하지 않고 다음 주기때 실행
self.run = True
def job_function(self):
try:
from framework import F
self.is_running = True
self.start_time = datetime.now(timezone('Asia/Seoul'))
if self.args is None:
self.thread = threading.Thread(target=self.target_function, args=())
else:
self.thread = threading.Thread(target=self.target_function, args=(self.args,))
self.thread.daemon = True
self.thread.start()
self.thread.join()
self.end_time = datetime.now(timezone('Asia/Seoul'))
self.running_timedelta = self.end_time - self.start_time
self.status = 'success'
if not F.scheduler.is_include(self.job_id):
F.scheduler.remove_job_instance(self.job_id)
self.count += 1
except Exception as exception:
self.status = 'exception'
F.logger.error('Exception:%s', exception)
F.logger.error(traceback.format_exc())
finally:
self.is_running = False
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+104
View File
@@ -0,0 +1,104 @@
body {
font-size: .850rem;
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.alert-minimalist {
background-color: rgb(241, 242, 240);
border-color: rgba(149, 149, 149, 0.3);
border-radius: 3px;
color: rgb(149, 149, 149);
padding: 10px;
}
.alert-minimalist > [data-notify="icon"] {
height: 50px;
margin-right: 12px;
}
.alert-minimalist > [data-notify="title"] {
color: rgb(51, 51, 51);
display: block;
font-weight: bold;
margin-bottom: 5px;
}
.alert-minimalist > [data-notify="message"] {
font-size: 80%;
}
textarea {
font-family: Courier
}
.loading { position: fixed; left: 45%; top: 50%; background: #00000000; }
.table > tbody > tr.collapse > td {
background-color: #009fff0d !important;
}
.tableRowHover tbody tr:not(.tableRowHoverOff):hover td {
background-color: #ffff0080 !important;
}
.table > tbody > tr > td { vertical-align: middle; }
.tab-pane {
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
border-bottom: 1px solid #ddd;
border-radius: 0px 0px 5px 5px;
padding: 10px;
}
.btn-toolbar { text-align: center; }
.nav-tabs { margin-bottom: 0; }
.navbar-nav li:hover>.dropdown-menu { display: block; }
.dropdown-toggle::after { display:none; }
.set-left { text-align: left; }
@media (min-width: 768px) {
.set-left { text-align: right; }
}
.badge-sm {
min-width: 1.8em;
padding: .25em !important;
margin-left: .1em;
margin-right: .1em;
color: white !important;
cursor: pointer;
}
@media all and (min-width: 992px) {
.dropdown-menu li{
position: relative;
}
.dropdown-menu .submenu{
display: none;
position: absolute;
left:100%; top:-7px;
}
.dropdown-menu .submenu-left{
right:100%; left:auto;
}
.dropdown-menu > li:hover{ background-color: #f1f1f1 }
.dropdown-menu > li:hover > .submenu{
display: block;
}
}
/* ============ desktop view .end// ============ */
/* ============ small devices ============ */
@media (max-width: 991px) {
.dropdown-menu .dropdown-menu{
margin-left:0.7rem; margin-right:0.7rem; margin-bottom: .5rem;
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
Binary file not shown.

After

Width:  |  Height:  |  Size: 318 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+296
View File
@@ -0,0 +1,296 @@
var tmp = window.location.pathname.split('/');
if (tmp.length == 2) {
var PACKAGE_NAME = tmp[1];
var MODULE_NAME = "";
var PAGE_NAME = "";
} else if (tmp.length == 3) {
var PACKAGE_NAME = tmp[1];
var MODULE_NAME = tmp[2];
var PAGE_NAME = "";
} else if (tmp.length == 4){
var PACKAGE_NAME = tmp[1];
var MODULE_NAME = tmp[2];
var PAGE_NAME = tmp[3];
}
var current_data = null;
console.log("NAME: [" + PACKAGE_NAME + '] [' + MODULE_NAME + '] [' + PAGE_NAME + ']');
$(window).on("load resize", function (event) {
var $navbar = $(".navbar");
var $body = $("body");
$body.css("padding-top", $navbar.outerHeight());
});
///////////////////////////////////////
// 사용 미확인
///////////////////////////////////////
// 알림
$.notify({
// options
icon: 'glyphicon glyphicon-ok',
title: 'SJVA',
message: '',
url: '',
target: '_blank'
},{
// settings
element: 'body',
position: null,
type: "info",
allow_dismiss: true,
newest_on_top: false,
showProgressbar: false,
placement: {
from: "top",
align: "right"
},
offset: 20,
spacing: 10,
z_index: 1031,
delay: 10000,
timer: 1000,
url_target: '_blank',
mouse_over: null,
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
},
onShow: null,
onShown: null,
onClose: null,
onClosed: null,
icon_type: 'class',
template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
'<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
'<span data-notify="icon"></span> ' +
'<span data-notify="title" style="word-break:break-all;">{1}</span> ' +
'<span data-notify="message" style="word-break:break-all;">{2}</span>' +
'<div class="progress" data-notify="progressbar">' +
'<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
'</div>' +
'<a href="{3}" target="{4}" data-notify="url"></a>' +
'</div>'
});
function notify(msg, type) {
$.notify('<strong>' + msg + '</strong>', {type: type});
}
// 메뉴 제거
function hideMenu() {
$("#menu_div").html('');
hideMenuModule();
hideMenuPage();
}
function hideMenuModule() {
$("#menu_module_div").html('');
}
function hideMenuPage() {
$("#menu_page_div").html('');
}
// 넓은 화면
function setWide() {
$('#main_container').attr('class', 'container-fluid');
}
function showModal(data='EMPTY', title='JSON', json=true) {
document.getElementById("modal_title").innerHTML = title;
if (json) {
data = JSON.stringify(data, null, 2);
}
document.getElementById("modal_body").innerHTML = "<pre>"+ data + "</pre>";;
$("#large_modal").modal();
}
///////////////////////////////////////
// camel
function get_formdata(form_id) {
// on, off 일수도 있으니 모두 True, False로 통일하고
// 밑에서는 False인 경우 값이 추가되지 않으니.. 수동으로 넣어줌
var checkboxs = $(form_id + ' input[type=checkbox]');
//for (var i in checkboxs) {
for (var i =0 ; i < checkboxs.length; i++) {
if ( $(checkboxs[i]).is(':checked') ) {
$(checkboxs[i]).val('True');
} else {
$(checkboxs[i]).val('False');
}
}
var formData = $(form_id).serialize();
$.each($(form_id + ' input[type=checkbox]')
.filter(function(idx) {
return $(this).prop('checked') === false
}),
function(idx, el) {
var emptyVal = "False";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
}
);
formData = formData.replace("&global_scheduler=True", "")
formData = formData.replace("&global_scheduler=False", "")
formData = formData.replace("global_scheduler=True&", "")
formData = formData.replace("global_scheduler=False&", "")
return formData;
}
function use_collapse(div, reverse=false) {
var ret = $('#' + div).prop('checked');
if (reverse) {
if (ret) {
$('#' + div + '_div').collapse('hide')
} else {
$('#' + div + '_div').collapse('show')
}
} else {
if (ret) {
$('#' + div + '_div').collapse('show')
} else {
$('#' + div + '_div').collapse('hide')
}
}
}
///////////////////////////////////////
// 유틸리티 - 프로젝트 관련성 없음
///////////////////////////////////////
function humanFileSize(bytes) {
var thresh = 1024;
if(Math.abs(bytes) < thresh) {
return bytes + ' B';
}
var units = ['KB','MB','GB','TB','PB','EB','ZB','YB']
var u = -1;
do {
bytes /= thresh;
++u;
} while(Math.abs(bytes) >= thresh && u < units.length - 1);
return bytes.toFixed(1)+' '+units[u];
}
function FormatNumberLength(num, length) {
var r = "" + num;
while (r.length < length) {
r = "0" + r;
}
return r;
}
function msToHMS( ms ) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
var minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
return (''+hours).padStart(2, "0")+":"+(''+minutes).padStart(2, "0")+":"+parseInt(seconds);
}
///////////////////////////////////////
// 사용 미확인
///////////////////////////////////////
function duration_str(duration) {
duration = duration / 100;
var minutes = parseInt(duration / 60);
var hour = parseInt(minutes / 60);
var min = parseInt(minutes % 60);
var sec = parseInt((duration/60 - parseInt(duration/60)) * 60);
return pad(hour, 2) + ':' + pad(min, 2) + ':' + pad(sec,2);
}
// 자리맞춤
function pad(n, width) {
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}
// jquery extend function
// post로 요청하면서 리다이렉트
// 푹 자동에서 푹 기본 검색할때 사용
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
//console.log(key);
//console.log(value);
value = value.split('"').join('\"')
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
+245
View File
@@ -0,0 +1,245 @@
// global socketio
$(document).ready(function(){
});
$(document).ready(function(){
$('.loading').hide();
})
.ajaxStart(function(){
$('.loading').show();
})
.ajaxStop(function(){
$('.loading').hide();
});
var protocol = window.location.protocol;
var frameSocket = io.connect(protocol + "//" + document.domain + ":" + location.port + "/framework");
frameSocket.on('notify', function(data){
$.notify({
message : data['msg'],
url: data['url'],
target: '_self'
},{
type: data['type'],
});
});
frameSocket.on('modal', function(data){
m_modal(data.data, data.title, false);
});
frameSocket.on('command_modal_add_text', function(data){
document.getElementById("command_modal_textarea").innerHTML += data ;
document.getElementById("command_modal_textarea").scrollTop = document.getElementById("command_modal_textarea").scrollHeight;
});
frameSocket.on('command_modal_show', function(data){
command_modal_show(data)
});
frameSocket.on('command_modal_clear', function(data){
document.getElementById("command_modal_textarea").innerHTML = ""
});
frameSocket.on('loading_hide', function(data){
$('#loading').hide();
});
frameSocket.on('refresh', function(data){
console.log('data')
window.location.reload();
});
///////////////////////////////////////
// Global - 버튼
///////////////////////////////////////
$("body").on('click', '#globalOpenBtn', function(e) {
e.preventDefault();
url = $(this).data('url')
window.open(url, "_blank");
});
$("body").on('click', '#globalLinkBtn', function(e) {
e.preventDefault();
url = $(this).data('url')
window.location.href = url;
});
// global_link_btn 모두 찾아 변경
$("body").on('click', '#globalSettingSaveBtn', function(e){
e.preventDefault();
globalSettingSave();
});
function globalSettingSave() {
var formData = get_formdata('#setting');
$.ajax({
url: '/' + PACKAGE_NAME + '/ajax/setting_save',
type: "POST",
cache: false,
data: formData,
dataType: "json",
success: function (ret) {
if (ret) {
$.notify('<strong>설정을 저장하였습니다.</strong>', {
type: 'success'
});
} else {
$.notify('<strong>설정 저장에 실패하였습니다.</strong>', {
type: 'warning'
});
}
}
});
}
$("body").on('click', '#globalEditBtn', function(e) {
e.preventDefault();
file = $(this).data('file');
console.log(file);
$.ajax({
url: '/global/ajax/is_available_edit',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
if (ret) {
window.location.href = '/flaskcode?open=' + file;
} else {
notify('편집기 플러그인을 설치해야 합니다.', 'warning');
}
}
});
});
///////////////////////////////////////
// Global - 함수
///////////////////////////////////////
function globalSendCommand(command, arg1, arg2, arg3, modal_title, callback) {
console.log("globalSendCommand [" + command + '] [' + arg1 + '] [' + arg2 + '] [' + arg3 + '] [' + modal_title + '] [' + callback);
console.log('/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command');
$.ajax({
url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command',
type: "POST",
cache: false,
data:{command:command, arg1:arg1, arg2:arg2, arg3},
dataType: "json",
success: function (ret) {
if (ret.msg != null) notify(ret.msg, ret.ret);
if (ret.modal != null) m_modal(ret.modal, modal_title, false);
if (ret.json != null) m_modal(ret.json, modal_title, true);
if (callback != null) callback(ret);
}
});
}
///////////////////////////////////////
// 파일 선택 모달
///////////////////////////////////////
var select_local_file_modal_callback = null;
function selectLocalFile(title, init_path, func) {
_selectLocalFileModal(title, init_path, false, func);
}
function selectLocalFolder(title, init_path, func) {
_selectLocalFileModal(title, init_path, true, func);
}
function _selectLocalFileModal(title, init_path, only_dir, func) {
if (init_path == '' || init_path == null)
init_path = '/';
document.getElementById("select_local_file_modal_title").innerHTML = title;
document.getElementById("select_local_file_modal_path").value = init_path;
document.getElementById("select_local_file_modal_only_dir").value = only_dir;
select_local_file_modal_callback = func;
$("#select_local_file_modal").modal();
listdir(init_path, only_dir);
}
$("body").on('click', '#global_select_local_file_load_btn', function(e) {
e.preventDefault();
let current_path = $('#select_local_file_modal_path').val().trim();
only_dir = $('#select_local_file_modal_only_dir').val().trim();
listdir(current_path, only_dir);
});
$("body").on('click', '#select_local_file_modal_confirm_btn', function(e) {
e.preventDefault();
if (select_local_file_modal_callback != null)
select_local_file_modal_callback($('#select_local_file_modal_path').val().trim());
$("#select_local_file_modal").modal('toggle');
});
let listdir = (path = '/', only_dir = true) => {
$.ajax({
url: `/global/ajax/listdir`,
type: 'POST',
cache: false,
data: {
path: path,
only_dir : only_dir
},
dataType: 'json'
}).done((datas) => {
console.log(datas)
if (datas.length == 0) {
return false;
}
let new_obj = ``;
const path_spliter = (path.indexOf('/')>=0)?'/':'\\';
$('#select_local_file_modal_list_group').empty();
for (let dt of datas) {
tmp = dt.split('|');
new_obj += `<a href='#' class="list-group-item list-group-item-action item_path" data-value="${tmp[1]}">${tmp[0]}</a>`;
}
$('#select_local_file_modal_list_group').append(new_obj);
$('.item_path').off('click').click((evt) => {
let new_path = '';
/*
if ($(evt.currentTarget).text() === '..'){
let split_path = '';
split_path = path.split(path_spliter);
split_path.pop();
new_path = split_path.join(path_spliter);
if (new_path.length === 0){
new_path = path_spliter
}
} else {
//new_path = (path !== path_spliter) ? path + path_spliter + $(evt.currentTarget).text() : path + $(evt.currentTarget).text();
new_path = $(evt.currentTarget).data('value');
console.log(new_path)
console.log(evt)
}
*/
new_path = $(evt.currentTarget).data('value');
$('#select_local_file_modal_path').val(new_path);
listdir(new_path, only_dir);
});
}).fail((datas) => {
$.notify('<strong>경로 읽기 실패</strong><br/>${add_path}', {type: 'danger'});
});
return false;
}
// 파일 선택 모달 End
///////////////////////////////////////
+265
View File
@@ -0,0 +1,265 @@
// javascript에서 화면 생성
function text_color(text, color='red') {
return '<span style="color:'+color+'; font-weight:bold">' + text + '</span>';
}
function m_table(id, heads) {
str += '<table id="result_table" class="table table-sm tableRowHover " ><thead class="thead-dark"><tr> \
<th style="width:10%;text-align:center;">NO</th> \
<th style="width:15%;text-align:center;">물어본 숫자</th> \
<th style="width:10%;text-align:center;">스트라이크</th> \
<th style="width:10%;text-align:center;"></th> \
<th style="width:15%;text-align:center;">가능한 숫자 </th> \
<th style="width:40%;text-align:center;">Action</th> \
</tr></thead><tbody id="list">';
}
function m_row_start(padding='10', align='center') {
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
return str;
}
function m_row_start_hover(padding='10', align='center') {
var str = '<div class="row my_hover" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
return str;
}
function m_row_start_top(padding='10') {
return m_row_start(padding, 'top');
}
function m_row_start_color(padding='10', align='center', color='') {
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+'; background-color:'+color+'">';
return str;
}
function m_row_start_color2(padding='10', align='center') {
var str = '<div class="row bg-dark text-white" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
return str;
}
function m_row_end() {
var str = '</div>';
return str;
}
//border
function m_col(w, h, align='left') {
var str = '<div class="col-sm-' + w + ' " style="text-align: '+align+'; word-break:break-all;">';
str += h
str += '</div>';
return str
}
function m_col2(w, h, align='left') {
var str = '<div class="col-sm-' + w + ' " style="padding:5px; margin:0px; text-align: '+align+'; word-break:break-all;">';
str += h
str += '</div>';
return str
}
function m_button_group(h) {
var str = '<div class="btn-group btn-group-sm flex-wrap mr-2" role="group">';
str += h
str += '</div>';
return str;
}
function m_button(id, text, data) {
var str = '<button id="'+id+'" name="'+id+'" class="btn btn-sm btn-outline-success" '
for ( var i in data) {
str += ' data-' + data[i].key + '="' + data[i].value+ '" '
}
str += '>' + text + '</button>';
return str;
}
function m_button2(id, text, data, outline_color) {
var str = '<button id="'+id+'" name="'+id+'" class="btn btn-sm btn-outline-'+outline_color+'" '
for ( var i in data) {
str += ' data-' + data[i].key + '="' + data[i].value+ '" '
}
str += '>' + text + '</button>';
return str;
}
function m_hr(margin='5') {
var str = '<hr style="width: 100%; margin:'+margin+'px;" />';
return str;
}
function m_hr_black() {
var str = '<hr style="width: 100%; color: black; height: 2px; background-color:black;" />';
return str;
}
// 체크박스는 자바로 하면 on/off 스크립트가 안먹힘.
function m_tab_head(name, active) {
if (active) {
var str = '<a class="nav-item nav-link active" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
} else {
var str = '<a class="nav-item nav-link" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
}
return str;
}
function m_tab_content(name, content, active) {
if (active) {
var str = '<div class="tab-pane fade show active" id="'+name+'" role="tabpanel" >';
} else {
var str = '<div class="tab-pane fade show" id="'+name+'" role="tabpanel" >';
}
str += content;
str += '</div>'
return str;
}
function m_progress(id, width, label) {
var str = '';
str += '<div class="progress" style="height: 25px;">'
str += '<div id="'+id+'" class="progress-bar" style="background-color:yellow;width:'+width+'%"></div>';
str += '<div id="'+id+'_label" class="justify-content-center d-flex w-100 position-absolute" style="margin-top:2px">'+label+'</div>';
str += '</div>'
return str;
}
function m_progress2(id, width, label) {
var str = '';
str += '<div class="progress" style="height: 25px;">'
str += '<div id="'+id+'" class="progress-bar" style="background-color:yellow;width:'+width+'%"></div>';
str += '<div id="'+id+'_label" class="justify-content-center d-flex w-100 position-absolute" style="margin:0px; margin-top:2px">'+label+'</div>';
str += '</div>'
return str;
}
function make_page_html(data) {
str = ' \
<div class="d-inline-block"></div> \
<div class="row mb-3"> \
<div class="col-sm-12"> \
<div class="btn-toolbar" style="justify-content: center;" role="toolbar" aria-label="Toolbar with button groups" > \
<div class="btn-group btn-group-sm mr-2" role="group" aria-label="First group">'
if (data.prev_page) {
str += '<button id="page" data-page="' + (data.start_page-1) + '" type="button" class="btn btn-secondary">&laquo;</button>'
}
for (var i = data.start_page ; i <= data.last_page ; i++) {
str += '<button id="page" data-page="' + i +'" type="button" class="btn btn-secondary" ';
if (i == data.current_page) {
str += 'disabled';
}
str += '>'+i+'</button>';
}
if (data.next_page) {
str += '<button id="page" data-page="' + (data.last_page+1) + '" type="button" class="btn btn-secondary">&raquo;</button>'
}
str += '</div> \
</div> \
</div> \
</div> \
'
document.getElementById("page1").innerHTML = str;
document.getElementById("page2").innerHTML = str;
}
function make_log(key, value, left=2, right=10) {
row = m_col(left, key, aligh='right');
row += m_col(right, value, aligh='left');
return row;
}
///////////////////////////////////////
// UI - 확장설정 - dropdown
///////////////////////////////////////
document.addEventListener("DOMContentLoaded", function(){
/////// Prevent closing from click inside dropdown
document.querySelectorAll('.dropdown-menu').forEach(function(element){
element.addEventListener('click', function (e) {
e.stopPropagation();
});
})
// make it as accordion for smaller screens
if (window.innerWidth < 992) {
// close all inner dropdowns when parent is closed
document.querySelectorAll('.navbar .dropdown').forEach(function(everydropdown){
everydropdown.addEventListener('hidden.bs.dropdown', function () {
// after dropdown is hidden, then find all submenus
this.querySelectorAll('.submenu').forEach(function(everysubmenu){
// hide every submenu as well
everysubmenu.style.display = 'none';
});
})
});
document.querySelectorAll('.dropdown-menu a').forEach(function(element){
element.addEventListener('click', function (e) {
let nextEl = this.nextElementSibling;
if(nextEl && nextEl.classList.contains('submenu')) {
// prevent opening link if link needs to open dropdown
e.preventDefault();
console.log(nextEl);
if(nextEl.style.display == 'block'){
nextEl.style.display = 'none';
} else {
nextEl.style.display = 'block';
}
}
});
})
}
// end if innerWidth
});
// DOMContentLoaded end
///////////////////////////////////////
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+675
View File
@@ -0,0 +1,675 @@
///////////////////////////////////////////////////////////////////////////////
// 공용 버튼
///////////////////////////////////////////////////////////////////////////////
// global_cache_confirm_btn => global_offcloud_cache_confirm_btn
$("body").on('click', '#global_offcloud_cache_confirm_btn', function(e){
e.preventDefault();
hash = $(this).data('hash');
$.ajax({
url: '/offcloud2/ajax/hash',
type: "POST",
cache: false,
data:{hash:hash},
dataType: "json",
success: function (data) {
if (data == 'true') {
$.notify('<strong>캐쉬 되어 있습니다.</strong>', {
type: 'success'
});
} else if (data == 'false') {
$.notify('<strong>캐쉬 되어 있지 않습니다.</strong>', {
type: 'warning'
});
} else if (data == 'fail') {
$.notify('<strong>캐쉬 확인 실패</strong>', {
type: 'warning'
});
}
}
});
//$(location).attr('href', '/offcloud/cache?magnet=' + hash)
});
//global_add_remote_btn -> global_offcloud_add_btn
$("body").on('click', '#global_offcloud_add_btn', function(e) {
e.preventDefault();
hash = $(this).data('hash');
$.ajax({
url: '/offcloud2/ajax/add_remote',
type: "POST",
cache: false,
data: {hash:hash},
dataType: "json",
success: function (data) {
m_modal(data)
}
});
});
$("body").on('click', '#global_downloader_add_btn', function(e){
e.preventDefault();
download_url = $(this).data('hash');
$.ajax({
url: '/downloader/ajax/add_download',
type: "POST",
cache: false,
data: {download_url:download_url},
dataType: "json",
success: function (data) {
show_result_add_download(data);
}
});
});
function command_modal_show(title) {
ClientHeight = window.innerHeight
document.getElementById("command_modal_title").innerHTML = title
$("#command_modal").height(ClientHeight-100);
$("#command_modal_textarea").height(ClientHeight-380);
$("#command_modal").modal();
}
// 토렌트 프로그램에 다운로드 추가할 결과를 보여주는
function show_result_add_download(data) {
try {
sub = ''
program = '토렌트'
if (data.default_torrent_program == '0') {
program = '트랜스미션에 토렌트'
sub = 'transmission'
} else if (data.default_torrent_program == '1') {
program = '다운로드스테이션에 토렌트'
sub = 'downloadstation'
} else if (data.default_torrent_program == '2') {
program = '큐빗토렌트다에 토렌트'
sub = 'qbittorrent'
} else if (data.default_torrent_program == '3') {
program = 'aria2에 토렌트'
sub = 'aria2'
} else if (data.default_torrent_program == '4') {
program = 'PikPak에 토렌트'
sub = 'pikpak'
}
}
catch {
}
if (data.ret == 'success') {
$.notify({message:'<strong>'+ program +'를 추가하였습니다.</strong><br>클릭시 다운로드 상태창으로 이동', url:'/downloader/'+sub+'/status',
target: '_self'}, {
type: 'success',
});
} else if (data.ret == 'success2') {
$.notify('<strong>일반 파일 다운로드를 시작하였습니다.</strong>', {
type: 'success'
});
} else if (data.ret == 'fail') {
$.notify('<strong>'+ program +' 추가에 실패하였습니다.</strong>', {
type: 'warning'
});
} else {
$.notify('<strong>'+ program +' 추가 에러<br>'+data.error+'</strong>', {
type: 'warning'
});
}
}
$("body").on('click', '#global_torrent_info_btn', function(e) {
e.preventDefault();
hash = $(this).data('hash');
$.ajax({
url: '/torrent_info/ajax/torrent_info',
type: "POST",
cache: false,
data: {hash:hash},
dataType: "json",
success: function (data) {
m_modal(data, "토렌트 정보")
}
});
});
function get_torrent_program_name(p) {
if (p == '0') return '트랜스미션'
else if (p == '1') return '다운로드스테이션'
else if (p == '2') return '큐빗토렌트'
else if (p == '3') return 'aria2'
else if (p == '4') return 'PikPak'
}
function global_relay_test(remote) {
$.ajax({
url: '/' + 'gd_share_client' + '/ajax/'+'base'+'/relay_test',
type: "POST",
cache: false,
data: {remote:remote},
dataType: "json",
success: function (data) {
if (data.ret == 'success') {
$.notify('<strong>릴레이 공유가 가능합니다.<strong>', {type: 'success'});
}else {
$.notify('<strong>설정이 잘못 되어 있습니다.</strong>', {type: 'warning'});
}
}
});
}
function shutdown_confirm() {
document.getElementById("confirm_title").innerHTML = "종료 확인";
document.getElementById("confirm_body").innerHTML = "종료 하시겠습니까?";
$('#confirm_button').attr('onclick', 'window.location.href = "/system/shutdown";');
$("#confirm_modal").modal();
}
$("#video_modal").on('hidden.bs.modal', function () {
document.getElementById("video_modal_video").pause();
//streaming_kill();
});
$("#video_modal").on('click', '#trailer_close_btn', function(e){
e.preventDefault();
document.getElementById("video_modal_video").pause();
//streaming_kill();
});
function streaming_kill(command, data={}) {
$.ajax({
url: '/' + 'ffmpeg' + '/ajax/streaming_kill',
type: "POST",
cache: false,
data:{},
dataType: "json",
success: function (data) {
}
});
}
///////////////////////////////////////////////////////////////////////////////
// Global.. JS 파일로 뺄것
///////////////////////////////////////////////////////////////////////////////
// 사용 on / off
$('#global_scheduler').change(function() {
var ret = $(this).prop('checked');
$.ajax({
url: '/'+package_name+'/ajax/scheduler',
type: "POST",
cache: false,
data: {scheduler : ret},
dataType: "json",
success: function (list) {
}
});
});
$('#global_scheduler_sub').change(function() {
var ret = $(this).prop('checked');
$.ajax({
url: '/'+package_name+'/ajax/scheduler',
type: "POST",
cache: false,
data: {scheduler : ret, sub:sub},
dataType: "json",
success: function (list) {
}
});
});
function global_setting_save_function() {
var formData = get_formdata('#setting');
$.ajax({
url: '/'+package_name+'/ajax/setting_save',
type: "POST",
cache: false,
data: formData,
dataType: "json",
success: function (ret) {
if (ret) {
$.notify('<strong>설정을 저장하였습니다.</strong>', {
type: 'success'
});
} else {
$.notify('<strong>설정 저장에 실패하였습니다.</strong>', {
type: 'warning'
});
}
}
});
}
$("#global_one_execute_btn").click(function(e) {
//$("body").on('click', '#one_execute_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/one_execute',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
if (ret=='scheduler' || ret=='thread') {
$.notify('<strong>작업을 시작하였습니다. ('+ret+')</strong>', {
type: 'success'
});
} else if (ret == 'is_running') {
$.notify('<strong>작업중입니다.</strong>', {
type: 'warning'
});
} else {
$.notify('<strong>작업 시작에 실패하였습니다.</strong>', {
type: 'warning'
});
}
}
});
});
$("#global_one_execute_sub_btn").click(function(e) {
//$("body").on('click', '#one_execute_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/one_execute',
type: "POST",
cache: false,
data: {sub:sub},
dataType: "json",
success: function (ret) {
if (ret=='scheduler' || ret=='thread') {
$.notify('<strong>작업을 시작하였습니다. ('+ret+')</strong>', {
type: 'success'
});
} else if (ret == 'is_running') {
$.notify('<strong>작업중입니다.</strong>', {
type: 'warning'
});
} else {
$.notify('<strong>작업 시작에 실패하였습니다.</strong>', {
type: 'warning'
});
}
}
});
});
$("body").on('click', '#global_immediately_execute_sub_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/immediately_execute',
type: "POST",
cache: false,
data: {sub:sub},
dataType: "json",
success: function (ret) {
if (ret.msg != null) notify(ret.msg, ret.ret);
}
});
});
$("body").on('click', '#global_reset_db_btn', function(e){
e.preventDefault();
document.getElementById("confirm_title").innerHTML = "DB 삭제";
document.getElementById("confirm_body").innerHTML = "전체 목록을 삭제 하시겠습니까?";
$('#confirm_button').attr('onclick', "global_db_delete();");
$("#confirm_modal").modal();
return;
});
function global_db_delete() {
$.ajax({
url: '/' + package_name + '/ajax/reset_db',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (data) {
if (data) {
$.notify('<strong>삭제하였습니다.</strong>', {
type: 'success'
});
} else {
$.notify('<strong>삭제에 실패하였습니다.</strong>',{
type: 'warning'
});
}
}
});
}
$("body").on('click', '#global_reset_db_sub_btn', function(e){
e.preventDefault();
document.getElementById("confirm_title").innerHTML = "DB 삭제";
document.getElementById("confirm_body").innerHTML = "전체 목록을 삭제 하시겠습니까?";
$('#confirm_button').attr('onclick', "global_db_delete_sub();");
$("#confirm_modal").modal();
return;
});
function global_db_delete_sub() {
$.ajax({
url: '/' + package_name + '/ajax/reset_db',
type: "POST",
cache: false,
data: {sub:sub},
dataType: "json",
success: function (data) {
if (data) {
$.notify('<strong>삭제하였습니다.</strong>', {
type: 'success'
});
} else {
$.notify('<strong>삭제에 실패하였습니다.</strong>',{
type: 'warning'
});
}
}
});
}
function global_sub_request_search(page, move_top=true) {
var formData = get_formdata('#form_search')
formData += '&page=' + page;
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/web_list',
type: "POST",
cache: false,
data: formData,
dataType: "json",
success: function (data) {
current_data = data;
if (move_top)
window.scrollTo(0,0);
make_list(data.list)
make_page_html(data.paging)
}
});
}
$("body").on('click', '#global_json_btn', function(e){
e.preventDefault();
var id = $(this).data('id');
for (i in current_data.list) {
if (current_data.list[i].id == id) {
m_modal(current_data.list[i])
}
}
});
$("body").on('click', '#global_reset_btn', function(e){
e.preventDefault();
document.getElementById("order").value = 'desc';
document.getElementById("option").value = 'all';
document.getElementById("search_word").value = '';
global_sub_request_search('1')
});
$("body").on('click', '#global_remove_btn', function(e) {
e.preventDefault();
id = $(this).data('id');
$.ajax({
url: '/'+package_name+'/ajax/'+sub+ '/db_remove',
type: "POST",
cache: false,
data: {id:id},
dataType: "json",
success: function (data) {
if (data) {
$.notify('<strong>삭제되었습니다.</strong>', {
type: 'success'
});
global_sub_request_search(current_data.paging.current_page, false)
} else {
$.notify('<strong>삭제 실패</strong>', {
type: 'warning'
});
}
}
});
});
//#######################################################
//플러그인 - 모듈 - 서브 구조하에서 서브 관련 함수
function global_send_command_sub(command, arg1, arg2, arg3, modal_title, callback) {
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/' + sub2 + '/command',
type: "POST",
cache: false,
data:{command:command, arg1:arg1, arg2:arg2, arg3},
dataType: "json",
success: function (ret) {
console.log(ret);
if (ret.msg != null) notify(ret.msg, ret.ret);
if (ret.modal != null) m_modal(ret.modal, modal_title, false);
if (ret.json != null) m_modal(ret.json, modal_title, true);
if (callback != null) callback(ret);
}
});
}
$("body").on('click', '#global_one_execute_sublogic_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/' + sub2 + '/one_execute',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
if (ret=='scheduler' || ret=='thread') {
$.notify('<strong>작업을 시작하였습니다. ('+ret+')</strong>', {
type: 'success'
});
} else if (ret == 'is_running') {
$.notify('<strong>작업중입니다.</strong>', {
type: 'warning'
});
} else {
$.notify('<strong>작업 시작에 실패하였습니다.</strong>', {
type: 'warning'
});
}
}
});
});
$("body").on('click', '#global_immediately_execute_sublogic_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/' + sub2 + '/immediately_execute',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
if (ret.msg != null) notify(ret.msg, ret.ret);
}
});
});
$('#global_scheduler_sublogic').change(function() {
var ret = $(this).prop('checked');
$.ajax({
url: '/'+package_name+'/ajax/' + sub + '/' + sub2 + '/scheduler',
type: "POST",
cache: false,
data: {scheduler : ret},
dataType: "json",
success: function (list) {
}
});
});
// 이동한 함수
function global_send_command(command, data={}) {
data['command'] = command;
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/command',
type: "POST",
cache: false,
data:data,
dataType: "json",
success: function (data) {
notify(data['msg'], data['ret']);
}
});
}
function global_send_command2(command, arg1, arg2, arg3, modal_title, callback) {
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/command',
type: "POST",
cache: false,
data:{command:command, arg1:arg1, arg2:arg2, arg3},
dataType: "json",
success: function (ret) {
if (ret.msg != null) notify(ret.msg, ret.ret);
if (ret.modal != null) m_modal(ret.modal, modal_title, false);
if (ret.json != null) m_modal(ret.json, modal_title, true);
if (callback != null) callback(ret);
}
});
}
+227
View File
@@ -0,0 +1,227 @@
function m_row_start(padding='10', align='center') {
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
return str;
}
function m_row_start_hover(padding='10', align='center') {
var str = '<div class="row my_hover" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
return str;
}
function m_row_start_top(padding='10') {
return m_row_start(padding, 'top');
}
function m_row_start_color(padding='10', align='center', color='') {
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+'; background-color:'+color+'">';
return str;
}
function m_row_start_color2(padding='10', align='center') {
var str = '<div class="row bg-dark text-white" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
return str;
}
function m_row_end() {
var str = '</div>';
return str;
}
//border
function m_col(w, h, align='left') {
var str = '<div class="col-sm-' + w + ' " style="text-align: '+align+'; word-break:break-all;">';
str += h
str += '</div>';
return str
}
function m_col2(w, h, align='left') {
var str = '<div class="col-sm-' + w + ' " style="padding:5px; margin:0px; text-align: '+align+'; word-break:break-all;">';
str += h
str += '</div>';
return str
}
function m_button_group(h) {
var str = '<div class="btn-group btn-group-sm flex-wrap mr-2" role="group">';
str += h
str += '</div>';
return str;
}
function m_button(id, text, data) {
var str = '<button id="'+id+'" name="'+id+'" class="btn btn-sm btn-outline-success" '
for ( var i in data) {
str += ' data-' + data[i].key + '="' + data[i].value+ '" '
}
str += '>' + text + '</button>';
return str;
}
function m_button2(id, text, data, outline_color) {
var str = '<button id="'+id+'" name="'+id+'" class="btn btn-sm btn-outline-'+outline_color+'" '
for ( var i in data) {
str += ' data-' + data[i].key + '="' + data[i].value+ '" '
}
str += '>' + text + '</button>';
return str;
}
function m_hr(margin='5') {
var str = '<hr style="width: 100%; margin:'+margin+'px;" />';
return str;
}
function m_hr_black() {
var str = '<hr style="width: 100%; color: black; height: 2px; background-color:black;" />';
return str;
}
// 체크박스는 자바로 하면 on/off 스크립트가 안먹힘.
function m_modal(data='EMPTY', title='JSON', json=true) {
document.getElementById("modal_title").innerHTML = title;
if (json) {
data = JSON.stringify(data, null, 2);
}
document.getElementById("modal_body").innerHTML = "<pre>"+ data + "</pre>";;
$("#large_modal").modal();
}
function m_tab_head(name, active) {
if (active) {
var str = '<a class="nav-item nav-link active" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
} else {
var str = '<a class="nav-item nav-link" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
}
return str;
}
function m_tab_content(name, content, active) {
if (active) {
var str = '<div class="tab-pane fade show active" id="'+name+'" role="tabpanel" >';
} else {
var str = '<div class="tab-pane fade show" id="'+name+'" role="tabpanel" >';
}
str += content;
str += '</div>'
return str;
}
function m_progress(id, width, label) {
var str = '';
str += '<div class="progress" style="height: 25px;">'
str += '<div id="'+id+'" class="progress-bar" style="background-color:yellow;width:'+width+'%"></div>';
str += '<div id="'+id+'_label" class="justify-content-center d-flex w-100 position-absolute" style="margin-top:2px">'+label+'</div>';
str += '</div>'
return str;
}
function m_progress2(id, width, label) {
var str = '';
str += '<div class="progress" style="height: 25px;">'
str += '<div id="'+id+'" class="progress-bar" style="background-color:yellow;width:'+width+'%"></div>';
str += '<div id="'+id+'_label" class="justify-content-center d-flex w-100 position-absolute" style="margin:0px; margin-top:2px">'+label+'</div>';
str += '</div>'
return str;
}
function make_page_html(data) {
str = ' \
<div class="d-inline-block"></div> \
<div class="row mb-3"> \
<div class="col-sm-12"> \
<div class="btn-toolbar" style="justify-content: center;" role="toolbar" aria-label="Toolbar with button groups" > \
<div class="btn-group btn-group-sm mr-2" role="group" aria-label="First group">'
if (data.prev_page) {
str += '<button id="page" data-page="' + (data.start_page-1) + '" type="button" class="btn btn-secondary">&laquo;</button>'
}
for (var i = data.start_page ; i <= data.last_page ; i++) {
str += '<button id="page" data-page="' + i +'" type="button" class="btn btn-secondary" ';
if (i == data.current_page) {
str += 'disabled';
}
str += '>'+i+'</button>';
}
if (data.next_page) {
str += '<button id="page" data-page="' + (data.last_page+1) + '" type="button" class="btn btn-secondary">&raquo;</button>'
}
str += '</div> \
</div> \
</div> \
</div> \
'
document.getElementById("page1").innerHTML = str;
document.getElementById("page2").innerHTML = str;
}
function use_collapse(div, reverse=false) {
var ret = $('#' + div).prop('checked');
if (reverse) {
if (ret) {
$('#' + div + '_div').collapse('hide')
} else {
$('#' + div + '_div').collapse('show')
}
} else {
if (ret) {
$('#' + div + '_div').collapse('show')
} else {
$('#' + div + '_div').collapse('hide')
}
}
}
document.addEventListener("DOMContentLoaded", function(){
/////// Prevent closing from click inside dropdown
document.querySelectorAll('.dropdown-menu').forEach(function(element){
element.addEventListener('click', function (e) {
e.stopPropagation();
});
})
// make it as accordion for smaller screens
if (window.innerWidth < 992) {
// close all inner dropdowns when parent is closed
document.querySelectorAll('.navbar .dropdown').forEach(function(everydropdown){
everydropdown.addEventListener('hidden.bs.dropdown', function () {
// after dropdown is hidden, then find all submenus
this.querySelectorAll('.submenu').forEach(function(everysubmenu){
// hide every submenu as well
everysubmenu.style.display = 'none';
});
})
});
document.querySelectorAll('.dropdown-menu a').forEach(function(element){
element.addEventListener('click', function (e) {
let nextEl = this.nextElementSibling;
if(nextEl && nextEl.classList.contains('submenu')) {
// prevent opening link if link needs to open dropdown
e.preventDefault();
console.log(nextEl);
if(nextEl.style.display == 'block'){
nextEl.style.display = 'none';
} else {
nextEl.style.display = 'block';
}
}
});
})
}
// end if innerWidth
});
// DOMContentLoaded end
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+68
View File
@@ -0,0 +1,68 @@
{% from "macro_menu.html" import menu, menu_module, menu_page with context %}
{% from "macro_include.html" import apply_theme, modals with context %}
{% import "macro.html" as macros %}
<!DOCTYPE html>
<html>
<head lang="ko">
{% block head %}
<title>{{get_web_title()}}</title>
{% endblock %}
<meta name="google" value="notranslate">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
<!--
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
-->
<link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
{% set theme = get_theme() %}
<link href="{{ url_for('static', filename='css/theme/'+theme+'_bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='css/animate.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='css/custom.css') }}" rel="stylesheet">
<link href="https://unpkg.com/balloon-css/balloon.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--<script src="{{ url_for('static', filename='js/popper.min.js') }}"></script>-->
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap-notify.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/sjva_ui14.js') }}"></script>
<script src="{{ url_for('static', filename='js/ff_common1.js') }}"></script>
<script src="{{ url_for('static', filename='js/ff_ui1.js') }}"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
<!-- 토글 -->
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.4.0/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.4.0/js/bootstrap4-toggle.min.js"></script>
<!-- end 토글 -->
</head>
<body class="body ">
{{ menu() }}
{{ menu_module() }}
<!--</nav>-->
<main id="main_container" role="main" class="container">
<div class="d-inline-block"></div>
{{ menu_page() }}
<div>
{% block content %}{% endblock %}
</div>
</main>
<div class="loading" id="loading">
<img src="/static/img/loading.gif" />
</div>
{{ modals() }}
</body>
</html>
<!-- 글로벌 버튼이 모두 나오고 처리-->
<script src="{{ url_for('static', filename='js/sjva_global1.js') }}"></script>
<script src="{{ url_for('static', filename='js/ff_global1.js') }}"></script>
+81
View File
@@ -0,0 +1,81 @@
{% extends "base.html" %}
{% block content %}
<div>
<nav>
{{ macros.m_tab_head_start() }}
{{ macros.m_tab_head('이전', true) }}
{{ macros.m_tab_head('실시간', false) }}
{{ macros.m_tab_head_end() }}
</nav>
<div class="tab-content" id="nav-tabContent">
{{ macros.m_tab_content_start('이전', true) }}
<div>
<textarea id="log" class="col-md-12" rows="30" charswidth="23" disabled style="background-color:#ffffff;visibility:hidden"></textarea>
</div>
{{ macros.m_tab_content_end() }}
{{ macros.m_tab_content_start('실시간', false) }}
<div>
<textarea id="add" class="col-md-12" rows="30" charswidth="23" disabled style="background-color:#ffffff;visibility:visible"></textarea>
</div>
<div class="form-inline">
<label class="form-check-label" for="auto_scroll">자동 스크롤</label>
<input id="auto_scroll" name="auto_scroll" class="form-control form-control-sm" type="checkbox" data-toggle="toggle" checked>
<span class='text-left' style="padding-left:25px; padding-top:0px">
<button id="clear" class="btn btn-sm btn-outline-success">리셋</button>
</span>
</div>
{{ macros.m_tab_content_end() }}
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
setWide();
$('#loading').show();
ResizeTextArea()
})
function ResizeTextArea() {
ClientHeight = window.innerHeight
$("#log").height(ClientHeight-240);
$("#add").height(ClientHeight-260);
}
$(window).resize(function() {
ResizeTextArea();
});
var protocol = window.location.protocol;
var socket = io.connect(protocol + "//" + document.domain + ":" + location.port + "/log");
socket.emit("start", {'package':'{{package}}'} );
socket.on('on_start', function(data){
document.getElementById("log").innerHTML += data.data;
document.getElementById("log").scrollTop = document.getElementById("log").scrollHeight;
document.getElementById("log").style.visibility = 'visible';
$('#loading').hide();
});
socket.on('add', function(data){
if (data.package == "{{package}}") {
var chk = $('#auto_scroll').is(":checked");
document.getElementById("add").innerHTML += data.data;
if (chk) document.getElementById("add").scrollTop = document.getElementById("add").scrollHeight;
}
});
$("#clear").click(function(e) {
e.preventDefault();
document.getElementById("add").innerHTML = '';
});
$("#auto_scroll").click(function(){
var chk = $(this).is(":checked");//.attr('checked');
});
</script>
{% endblock %}
File diff suppressed because it is too large Load Diff
+125
View File
@@ -0,0 +1,125 @@
{% import "macro.html" as macros %}
{% macro modals() %}
<!-- Modal -->
<div class="modal fade" id="large_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modal_title"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body" id="modal_body" style="word-break:break-all;">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">닫기</button>
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<div class="modal fade" id="normal_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="normal_modal_title"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body" id="normal_modal_body" style="word-break:break-all;">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">닫기</button>
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<div id="confirm_modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 id="confirm_title" class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div id="confirm_body" class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button id="confirm_button" type="button" class="btn btn-primary" data-dismiss="modal">확인</button>
<button id="confirm_cancel_button" type="button" class="btn btn-secondary" data-dismiss="modal">취소</button>
</div>
</div>
</div>
</div>
<!-- 경로 선택 모달 -->
<div class="modal fade" id="select_local_file_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="select_local_file_modal_title">경로 선택</h4>
</div>
<div class="modal-body" id="modal_body" style="word-break: break-all;">
<div class="row" style="padding-top: 10px; padding-bottom:10px; align-items: center;">
<div class="col-sm-1 set-left"><strong>Path</strong></div>
<div class="col-sm-11">
<div class="input-group col-sm-12">
<input id="select_local_file_modal_path" name="select_local_file_modal_path" type="text" class="form-control form-control-sm" value="/">
<div class="btn-group btn-group-sm flex-wrap mr-2" role="group" style="padding-left:5px; padding-top:0px">
<button id="global_select_local_file_load_btn" class="btn btn-sm btn-outline-success">Load</button>
<button type="button" id='select_local_file_modal_confirm_btn' class="btn btn-success" data-dismiss="modal">선택
</div>
</div>
<div style="padding-left:20px; padding-top:5px;"><em>입력한 경로를 불러옵니다.</em></div>
</div>
</div>
<input type="hidden" id="select_local_file_modal_only_dir" value="true" />
<input type="hidden" id="select_local_file_modal_callback" value="" />
<div class="list-group" id="select_local_file_modal_list_group">
</div>
</div>
<div class="modal-footer">
<button type="button" id='select_local_file_modal_confirm_btn' class="btn btn-success" data-dismiss="modal">선택
</button>
<button type="button" id='select_local_file_modal_cancel_btn' class="btn btn-default" data-dismiss="modal">닫기
</button>
</div>
</div>
</div>
</div>
<!-- 예고편 Player Modal: START -->
<div class="modal fade" id="video_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="video_modal_title" style="word-break:break-all;">예고편 재생: </h4>
</div>
<div class="modal-body" id="modal_body" style="word-break:break-all;">
<span id="video_player_body"></span>
</div>
<!--</div>-->
<div class="modal-footer">
<button type="button" id='video_close_btn' class="btn btn-default" data-dismiss="modal">닫기</button>
</div>
</div>
</div>
</div>
<!-- 예고편 Player Modal: END -->
<!--command modal-->
{{ macros.m_modal_start('command_modal', '', 'modal-lg') }}
<div>
<textarea id="command_modal_textarea" class="col-md-12" rows="30" disabled style="visibility:visible"></textarea>
</div>
{{ macros.m_modal_end() }}
<!--command modal end-->
<!-- Modal end -->
{% endmacro %}
+144
View File
@@ -0,0 +1,144 @@
{% macro menu() %}
<div id="menu_div">
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark flex-md-nowrap shadow" role="navigation">
<a class="navbar-brand" href="/">{{get_web_title()}}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample01" aria-controls="navbarsExample01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
{% for i in range(1) %}
<div class="collapse navbar-collapse w-100" id="navbarsExample01">
{% if i == 0 %}
<ul class="nav navbar-nav mr-auto">
{% else %}
<ul class="nav navbar-nav ml-auto">
{% endif %}
{% set menu = request.full_path | get_menu %}
{% set menu_map = get_menu_map() %}
{% for category in menu_map %}
{% if 'uri' in category and category['uri'].startswith('http') %}
<li class="nav-item"> <a class="nav-link" href="{{ category['uri']}}" target="_blank">{{category['name']}}</a></li>
{% else %}
<!--{{ category }}-->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{category['name']}}</a>
<ul class="dropdown-menu">
{% for category_child in category['list'] %}
{% if category_child['uri'] == 'setting' %}
<li><a class="dropdown-item" href="#" style="font-size: .850rem; font-weight:bold">{{category_child['name']}}</a>
<ul class="submenu dropdown-menu">
{% for item in category_child['list'] %}
<li><a class="dropdown-item" href="/{{item['uri']}}" style="font-size: .850rem; font-weight:bold">{{item['name']}}</a></li>
{% endfor %}
</ul>
</li>
{% elif category_child['uri'] == '-' %}
<div class="dropdown-divider"></div>
{% elif 'uri' in category_child and category_child['uri'].startswith('http') %}
{% if 'target' not in category_child or category_child['target'] == '_blank' %}
<a class="dropdown-item" href="{{ category_child['uri'] }}" target="_blank" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
{% else %}
<a class="dropdown-item" href="{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
{% endif %}
{% else %}
{% if category_child['uri'] == menu[0] %}
<a class="dropdown-item active" href="/{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
{% else %}
<a class="dropdown-item" href="/{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
{% endif %}
{% endif %}
{% endfor %}
</ul>
</li>
{% endif %}
{% endfor %}<!---->
</ul>
</div>
{% endfor %}
</nav>
</div>
{% endmacro %}
{% macro menu_module() %}
<div id='menu_module_div'>
{% set current_menu = request.full_path | get_menu %}
<!--{{ current_menu }}-->
{% set menu_map = get_menu_map() %}
{% for category in menu_map %}
{% for category_child in category['list'] %}
{% if current_menu[0] == category_child['uri'] %}
<ul class="nav nav-pills bg-light shadow text-dark" >
<li class="nav-item"><span class="nav-link">{{category['name']}} ➤ {{category_child['name']}}</span></li>
{% for module in category_child['list'] %}
<!--{{ module }}-->
{% if current_menu[0] == 'setting' %}
{% if current_menu[1] == module['uri'] or (current_menu[2] is not none and current_menu[1] + "/" + current_menu[2] == module['uri']) %}
<li class="nav-item"><a class="nav-link active" href="/{{module['uri']}}">{{module['name']}}</a></li>
{% else %}
<li class="nav-item"><a class="nav-link" href="/{{module['uri']}}">{{module['name']}}</a></li>
{% endif %}
{% else %}
{% if current_menu[1] == module['uri'] or (current_menu[2] is not none and current_menu[1] + "/" + current_menu[2] == module['uri']) %}
<li class="nav-item"><a class="nav-link active" href="/{{current_menu[0]}}/{{module['uri']}}">{{module['name']}}</a></li>
{% else %}
<li class="nav-item"><a class="nav-link" href="/{{current_menu[0]}}/{{module['uri']}}">{{module['name']}}</a></li>
{% endif %}
{% endif %}
{% endfor %}
</ul>
{% break %}
{% endif %}
{% endfor %}
{% endfor %}
</div>
{% endmacro %}
{% macro menu_page() %}
<div id='menu_page_div'>
{% set current_menu = request.full_path | get_menu %}
{% set menu_map = get_menu_map() %}
{% for category in menu_map %}
{% for plugin in category['list'] %}
{% if current_menu[0] == plugin['uri'] and 'list' in plugin %}
{% for module in plugin['list'] %}
{% if module['uri'] == current_menu[1] and 'list' in module%}
<!--{{ module }}-->
<ul class="nav nav-pills bg-light shadow text-dark">
{% for page in module['list'] %}
{% if current_menu[2] == page['uri'] %}
<li class="nav-item"><a class="nav-link active" href="/{{ current_menu[0] }}/{{ current_menu[1] }}/{{ page['uri'] }}">{{page['name']}}</a></li>
{% else %}
<li class="nav-item"><a class="nav-link" href="/{{ current_menu[0] }}/{{ current_menu[1] }}/{{ page['uri'] }}">{{page['name']}}</a></li>
{% endif %}
{% endfor %}
</ul>
<div class="d-inline-block"></div>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
</div>
{% endmacro %}
+30
View File
@@ -0,0 +1,30 @@
{% extends "base.html" %}
{% block content %}
{% filter markdown %}
{{ data }}
{% endfilter %}
<style type="text/css">
img{
display: block;
max-width: 100%;
margin-right: auto;
}
</style>
<div id="md_div" data-url="{{ arg }}"></div>
<div id="content_div" data-url="{{ arg }}"></div>
<script type="text/javascript">
$(document).ready(function(){
//$('#main_container').attr('class', 'container-fluid');
});
</script>
{% endblock %}
+6
View File
@@ -0,0 +1,6 @@
{% extends "base.html" %}
{% block content %}
<div class="">
<h3>{{title}}</h3>
</div>
{% endblock %}
+65
View File
@@ -0,0 +1,65 @@
<title>{{data['play_title']}}</title>
<script src="https://vjs.zencdn.net/7.11.4/video.min.js"></script>
<link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet" />
<body bgcolor='black'>
<video id=player width=960 height=540 class="video-js vjs-default-skin vjs-16-9" autoplay controls>
<source
src="{{data['play_source_src']}}"
type="{{data['play_source_type']}}" />
</video>
</body>
<script>
var subtitle_src = "{{data['play_subtitle_src']}}";
let options = {
html5: {
nativeTextTracks: false
},
playbackRates: [.5, .75, 1, 1.5, 2],
controls: true,
preload: "auto",
controlBar: {
playToggle: false,
pictureInPictureToggle: false,
remainingTimeDisplay: true,
qualitySelector: true,
}
};
let player = videojs('player', options);
player.ready(function(){
// set subtitle track
console.log(subtitle_src);
if (subtitle_src != "") {
var suburl = subtitle_src.replace(/&amp;/g, '&');
console.log(suburl);
let captionOption = {
kind: 'captions',
srclang: 'ko',
label: 'Korean',
src: suburl,
mode: 'showing'
};
player.addRemoteTextTrack(captionOption);
var settings = this.textTrackSettings;
settings.setValues({
"backgroundColor": "#000",
"backgroundOpacity": "0",
"edgeStyle": "uniform",
});
settings.updateDisplay();
}
else {
var tracks = player.textTracks();
console.log(tracks.length);
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
console.log(track);
}
}
});
player.play();
</script>
+138
View File
@@ -0,0 +1,138 @@

# -*- coding: utf-8 -*-
#########################################################
# python
import os
import json
import traceback
import platform
import subprocess
# third-party
from sqlalchemy.ext.declarative import DeclarativeMeta
# sjva 공용
from framework import app, logger
#########################################################
class Util(object):
@staticmethod
def db_list_to_dict(db_list):
"""
세팅DB에서 사용, (key, value) dict로 변환
"""
ret = {}
for item in db_list:
ret[item.key] = item.value
return ret
@staticmethod
def db_to_dict(db_list):
ret = []
for item in db_list:
ret.append(item.as_dict())
return ret
@staticmethod
def get_paging_info(count, current_page, page_size):
try:
paging = {}
paging['prev_page'] = True
paging['next_page'] = True
if current_page <= 10:
paging['prev_page'] = False
paging['total_page'] = int(count / page_size) + 1
if count % page_size == 0:
paging['total_page'] -= 1
paging['start_page'] = int((current_page-1)/10) * 10 + 1
paging['last_page'] = paging['total_page'] if paging['start_page'] + 9 > paging['total_page'] else paging['start_page'] + 9
if paging['last_page'] == paging['total_page']:
paging['next_page'] = False
paging['current_page'] = current_page
paging['count'] = count
logger.debug('paging : c:%s %s %s %s %s %s', count, paging['total_page'], paging['prev_page'], paging['next_page'] , paging['start_page'], paging['last_page'])
return paging
except Exception as exception:
logger.debug('Exception:%s', exception)
logger.debug(traceback.format_exc())
@staticmethod
def save_from_dict_to_json(d, filename):
from tool_base import ToolUtil
ToolUtil.save_dict(d, filename)
@staticmethod
def change_text_for_use_filename(text):
from tool_base import ToolBaseFile
return ToolBaseFile.text_for_filename(text)
# 토렌트 인포에서 최대 크기 파일과 폴더명을 리턴한다
@staticmethod
def get_max_size_fileinfo(torrent_info):
try:
ret = {}
max_size = -1
max_filename = None
for t in torrent_info['files']:
if t['size'] > max_size:
max_size = t['size']
max_filename = str(t['path'])
t = max_filename.split('/')
ret['filename'] = t[-1]
if len(t) == 1:
ret['dirname'] = ''
elif len(t) == 2:
ret['dirname'] = t[0]
else:
ret['dirname'] = max_filename.replace('/%s' % ret['filename'], '')
ret['max_size'] = max_size
return ret
except Exception as exception:
logger.error('Exception:%s', exception)
logger.error(traceback.format_exc())
# 압축할 폴더 경로를 인자로 받음. 폴더명.zip 생성
@staticmethod
def makezip(zip_path, zip_extension='zip'):
import zipfile
try:
if os.path.isdir(zip_path):
zipfilename = os.path.join(os.path.dirname(zip_path), '%s.%s' % (os.path.basename(zip_path), zip_extension))
fantasy_zip = zipfile.ZipFile(zipfilename, 'w')
for f in os.listdir(zip_path):
#if f.endswith('.jpg') or f.endswith('.png'):
src = os.path.join(zip_path, f)
fantasy_zip.write(src, os.path.basename(src), compress_type = zipfile.ZIP_DEFLATED)
fantasy_zip.close()
import shutil
shutil.rmtree(zip_path)
return True
except Exception as exception:
logger.error('Exception:%s', exception)
logger.error(traceback.format_exc())
return False
@staticmethod
def make_apikey(url):
from framework import SystemModelSetting
url = url.format(ddns=SystemModelSetting.get('ddns'))
if SystemModelSetting.get_bool('auth_use_apikey'):
if url.find('?') == -1:
url += '?'
else:
url += '&'
url += 'apikey=%s' % SystemModelSetting.get('auth_apikey')
return url