-
-
Save helloong/e668eb5d1bdb823ef88958a65fba19da to your computer and use it in GitHub Desktop.
AllFilesForYou
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
************************************************************************* | |
1. Title : The method to share of Fileis(Webhard) to other people | |
2. Writer : hElLoOnG | |
3. Date : 2018.04.11(Wed) | |
4. ETC : | |
5. History | |
- Add, 2018.04.11, helloong, First Created. | |
- Add, 2018.04.22, helloong, Add function if the file is downloaded bot will notice that to the requester. | |
- Add, 2018.04.25, helloong, Modify URL encoding error for the Iphone safari browser. | |
- Add, 2018.05.10, helloong, Remove error if search result is empty. | |
- Add, 2018.05.14, helloong, Add function, Remove files in the download directory if the file is the day after 5 days its created. | |
************************************************************************* | |
""" | |
import telebot | |
from telebot import types | |
import pickle | |
import sys | |
import os | |
import fileis | |
from fileis import get_trace_this_point | |
import requests | |
import fileis_logger | |
from fileis_helpmsg import * | |
# from fileis_utils import * | |
from filelock import Timeout, FileLock | |
import win32gui | |
import win32com | |
from time import sleep as delay | |
import datetime | |
import urllib3 | |
import socket | |
import sqlite3 | |
import urllib.parse | |
from apscheduler.schedulers.background import BackgroundScheduler | |
TOKEN = u"" | |
bot = telebot.TeleBot(TOKEN) | |
MASTER_USER = [] | |
LOCAL_USER = [] | |
ADMIN_USER = {} # {12341234: {user_type: "S"}} # S: 슈퍼유저, N: 일반유저 | |
PENDING_USER_INFO = {} # {'12341234': {'user_name': 'SHIM MAL DDONG', 'mobile_phone': '+82100001234'}} | |
USER_INFO = {} # {'12341234': {'user_name': 'SHIM MAL DDONG', 'mobile_phone': '+82100001234'}} | |
USER_STEP = {} # {12341234: func_name} | |
WEBCTRL = win32com.client.Dispatch("WebControl.WebBBS.1") | |
SESS = requests.Session() | |
SCHED = BackgroundScheduler() | |
CHILD_WHND = [] | |
FDL_PID = None | |
USER_ID = u"" | |
USER_PW = u"" | |
HASH_PW = u"" | |
def check_downloaded(f): | |
# logger.debug(get_trace_this_point(9)) | |
if os.path.exists(f): | |
try: | |
os.rename(f, f) | |
return 1 | |
except OSError as e: | |
return 0 | |
else: | |
return -1 | |
def check_down_n_noti(): | |
logger.debug(get_trace_this_point(9)) | |
# 완료목록 삭제버튼 클릭 | |
fileis.click_rm_comp_lists_btn(u"Button") | |
file_lists = fileis.get_down_n_noti_file() | |
# logger.debug(str(len(file_lists))) | |
if len(file_lists) <= 0: | |
return 0 | |
for file_info in file_lists: | |
if check_downloaded(file_info) != 1: | |
continue | |
comp_file_path = os.path.split(file_info)[0] | |
comp_file_name = os.path.split(file_info)[1] | |
logger.debug(u"comp_file_path: " + str(comp_file_path)) | |
logger.debug(u"comp_file_name: " + str(comp_file_name)) | |
conn = sqlite3.connect(u"fileis.db") | |
with conn: | |
cur = conn.cursor() | |
sql = u"SELECT rgst_date" \ | |
u" , chat_id" \ | |
u" , file_id" \ | |
u" , file_name" \ | |
u" , order_id" \ | |
u" , user_name" \ | |
u" , mobile_phone" \ | |
u" , title_name" \ | |
u" , file_size" \ | |
u" , down_yn" \ | |
u" , noti_yn " \ | |
u" FROM TM_FILE_DOWN " \ | |
u" WHERE down_yn = 'N' " \ | |
u" AND rgst_date >= :rgst_date " \ | |
u" AND file_name = :file_name " | |
where = {u"rgst_date": (datetime.date.today() - datetime.timedelta(1)).strftime(u"%Y%m%d"), | |
u"file_name": comp_file_name} | |
cur.execute(sql, where) | |
rows = cur.fetchall() | |
logger.debug(rows) | |
if len(rows) <= 0: | |
logger.debug(u"다운로드 체크 대상 없음!!") | |
continue | |
for row in rows: | |
logger.debug(str(row)) | |
db_rgst_date = row[0] | |
db_cid = row[1] | |
db_file_id = row[2] | |
db_file_name = row[3] | |
db_order_id = row[4] | |
db_user_name = row[5] | |
db_mobile_phone = row[6] | |
db_title_name = row[7] | |
db_file_size = row[8] | |
db_down_yn = row[9] | |
db_noti_yn = row[10] | |
sql = u"UPDATE TM_FILE_DOWN " \ | |
u" SET down_yn = 'Y' " \ | |
u" , noti_yn = 'Y' " \ | |
u" WHERE down_yn = 'N' " \ | |
u" AND chat_id = :chat_id " \ | |
u" AND rgst_date = :rgst_date " \ | |
u" AND file_name = :file_name " \ | |
u" AND file_id = :file_id " | |
where = {u"chat_id": db_cid, | |
u"rgst_date": db_rgst_date, | |
u"file_name": comp_file_name, | |
u"file_id": db_file_id | |
} | |
conn.execute(sql, where) | |
if db_cid == u"webdown": | |
logger.debug(u"web 경로로 이동") | |
ret_path = fileis.move_comp_file(comp_file_path, | |
u"D:\\Download\\FileIs\\web\\", | |
comp_file_name) | |
else: | |
logger.debug(u"comp 경로로 이동") | |
ret_path = fileis.move_comp_file(comp_file_path, | |
u"D:\\Download\\FileIs\\comp\\" + str(db_cid), | |
comp_file_name) | |
ret_file_path = os.path.split(ret_path)[0] | |
ret_file_name = os.path.split(ret_path)[1] | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
# file_down_link_local = comp_file_path.replace(u"D:\\Download\\FileIs", u"http://192.168.0.8:5002").replace(u"\\", u"/") + u"/" + comp_file_name | |
file_down_link_local = ret_file_path.replace(u"D:\\Download\\FileIs", | |
u"http://192.168.0.8:5002").replace(u"\\", | |
u"/") + u"/" + urllib.parse.quote(ret_file_name) | |
logger.debug(u"file_down_link_local: " + str(file_down_link_local)) | |
btn_down_local_link = types.InlineKeyboardButton(u"로컬다운로드", url=file_down_link_local) | |
# file_down_link = comp_file_path.replace(u"D:\\Download\\FileIs", u"http://helloong.ipdisk.co.kr:5002").replace(u"\\", u"/") + u"/" + comp_file_name | |
file_down_link = ret_file_path.replace(u"D:\\Download\\FileIs", | |
u"http://helloong.ipdisk.co.kr:5002").replace(u"\\", | |
u"/") + u"/" + urllib.parse.quote(ret_file_name) | |
logger.debug(u"file_down_link: " + str(file_down_link)) | |
btn_down_link = types.InlineKeyboardButton(u"다운로드", url=file_down_link) | |
if db_cid in LOCAL_USER: | |
inline_btn_markup.row(btn_down_local_link, btn_down_link) | |
else: | |
inline_btn_markup.row(btn_down_link) | |
inline_btn_markup.row(btn_cancel) | |
send_msg = (u"[알림]다운로드 완료[유효기간: 5일]\n" | |
u"제목: {}\n" | |
u"파일명: {}\n" | |
u"용량: {}".format(db_title_name, db_file_name, db_file_size)) | |
bot.send_message(db_cid, send_msg, parse_mode=u"HTML", reply_markup=inline_btn_markup) | |
logger.debug(u"다운로드 체크 및 알림 완료!!") | |
return 0 | |
def str_format(string, width, align=u"<", fill=u" "): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
주어진 문자열을 오와 열을 맞추어 이쁘게 되돌려준다. | |
:param string: | |
:param width: | |
:param align: | |
:param fill: | |
:return: | |
""" | |
import unicodedata | |
# logger.debug(string) | |
# logger.debug(type(string)) | |
if type(string) != str: | |
string = str(string) | |
count = (width - sum(1 + (unicodedata.east_asian_width(str(c)) in "WF") | |
for c in string)) | |
return { | |
u">": lambda s: fill * count + s, | |
u"<": lambda s: s + fill * count, | |
u"^": lambda s: fill * (count / 2) + s + fill * (count / 2 + count % 2) | |
}[align](string) | |
def save_all_data(): | |
logger.debug(get_trace_this_point(9)) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
global PENDING_USER_INFO | |
# logger.debug(u"ADMIN_USER: ") | |
# logger.debug(str(ADMIN_USER)) | |
# logger.debug(u"USER_INFO: ") | |
# logger.debug(str(USER_INFO)) | |
# logger.debug(u"USER_STEP: ") | |
# logger.debug(str(USER_STEP)) | |
# logger.debug(u"PENDING_USER_INFO: ") | |
# logger.debug(str(PENDING_USER_INFO)) | |
admin_user_path = u"f_admin_info.dat" | |
admin_user_lock_path = admin_user_path + u".lock" | |
admin_user_lock = FileLock(admin_user_lock_path, timeout=5) | |
user_info_path = u"f_user_info.dat" | |
user_info_lock_path = user_info_path + u".lock" | |
user_info_lock = FileLock(user_info_lock_path, timeout=5) | |
user_step_path = u"f_user_step.dat" | |
user_step_lock_path = user_step_path + u".lock" | |
user_step_lock = FileLock(user_step_lock_path, timeout=5) | |
pending_user_path = u"f_pending_user.dat" | |
pending_user_lock_path = pending_user_path + u".lock" | |
pending_user_lock = FileLock(pending_user_lock_path, timeout=5) | |
try: | |
with admin_user_lock: | |
with open(admin_user_path, "wb") as f: | |
pickle.dump(ADMIN_USER, f) | |
with user_info_lock: | |
with open(user_info_path, "wb") as f: | |
pickle.dump(USER_INFO, f) | |
with user_step_lock: | |
with open(user_step_path, "wb") as f: | |
pickle.dump(USER_STEP, f) | |
with pending_user_lock: | |
with open(pending_user_path, "wb") as f: | |
pickle.dump(PENDING_USER_INFO, f) | |
logger.debug(u"서버환경설정 파일 저장완료.") | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.debug(u"서버환경설정 파일 저장에 실패하였습니다.") | |
return 0 | |
def get_pickle_load(file_name): | |
logger.debug(get_trace_this_point(9)) | |
logger.debug(file_name) | |
if os.path.isfile(file_name): | |
with open(file_name, "rb") as f: | |
return_value = pickle.load(f, encoding="utf-8") | |
return return_value | |
else: | |
with open(file_name, "wb") as f: | |
pickle.dump({}, f) | |
return {} | |
def load_all_data(): | |
logger.debug(get_trace_this_point(9)) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
global PENDING_USER_INFO | |
ADMIN_USER = get_pickle_load(u"f_admin_info.dat") | |
USER_INFO = get_pickle_load(u"f_user_info.dat") | |
USER_STEP = get_pickle_load(u"f_user_step.dat") | |
PENDING_USER_INFO = get_pickle_load(u"f_pending_user.dat") | |
if len(USER_INFO): | |
# logger.debug(u"Admin list.") | |
# logger.debug(str(ADMIN_USER)) | |
# logger.debug(u"User list.") | |
# logger.debug(str(USER_INFO)) | |
# logger.debug(u"User step.") | |
# logger.debug(str(USER_STEP)) | |
# logger.debug(u"Pending user.") | |
# logger.debug(str(PENDING_USER_INFO)) | |
pass | |
else: | |
logger.debug(u"No one is in this room at this time.") | |
# logger.debug(u"Admin list.") | |
# logger.debug(str(ADMIN_USER)) | |
# logger.debug(u"User list.") | |
# logger.debug(str(USER_INFO)) | |
# logger.debug(u"User step.") | |
# logger.debug(str(USER_STEP)) | |
# logger.debug(u"Pending user.") | |
# logger.debug(str(PENDING_USER_INFO)) | |
if len(USER_INFO) > 0: | |
for cid in MASTER_USER: | |
bot.send_message(cid, u"[알림]서비스가 재개 되었습니다.") | |
def telegram_polling(): | |
""" | |
logger.debug(get_trace_this_point(9)) | |
bot.polling(none_stop=True, interval=0, timeout=30) | |
""" | |
while True: | |
try: | |
logger.debug(get_trace_this_point(9)) | |
bot.polling(none_stop=True, interval=0, timeout=30) | |
except requests.exceptions.ReadTimeout as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
delay(30) | |
except urllib3.exceptions.ReadTimeoutError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
delay(30) | |
except socket.timeout as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
delay(30) | |
def stop_service(): | |
logger.debug(get_trace_this_point(9)) | |
logger.debug(u"Stopping of the all file that you want service..") | |
save_all_data() | |
SCHED.shutdown() | |
bot.stop_polling() | |
sys.exit(1) | |
def keep_alive(m, user_id, user_pw): | |
global SESS | |
global ADMIN_USER | |
cid = str(m.chat.id) | |
if not fileis.chk_is_login(SESS): | |
logger.debug(u"Login status check failed. Trying to reloggin...") | |
if not fileis.login_to_fileis(SESS, user_id, user_pw): | |
logger.debug(u"Login failed again..") | |
bot.send_message(cid, (u"인증정보가 올바르지 않아 작업을 진행 할 수 없습니다.\n" | |
u"오류정보를 관리자에게 전달합니다.\n")) | |
for admin_cid in ADMIN_USER: | |
bot.send_message(admin_cid, u"인증에 문제가 발생하였습니다.") | |
bot.send_message(cid, u"관리자에게 오류내역이 전달 되었습니다.") | |
return False | |
return True | |
def keep_alive_apsche(): | |
logger.debug(get_trace_this_point(9)) | |
global SESS | |
global USER_ID | |
global USER_PW | |
global MASTER_USER | |
cid = MASTER_USER[0] | |
if not fileis.chk_is_login(SESS): | |
logger.debug(u"Login status check failed. Trying to reloggin...") | |
if not fileis.login_to_fileis(SESS, USER_ID, USER_PW): | |
logger.debug(u"Login failed again..") | |
bot.send_message(cid, (u"인증정보가 올바르지 않아 작업을 진행 할 수 없습니다.\n" | |
u"오류정보를 관리자에게 전달합니다.\n")) | |
return False | |
return True | |
# only used for console output now | |
def listener(messages): | |
""" | |
When new messages arrive TeleBot will call this function. | |
""" | |
for m in messages: | |
if m.content_type == u"text": | |
# print the sent message to the console | |
logger.debug(str(m.chat.first_name) + u" [" + str(m.chat.id) + u"]: " + str(m.text)) | |
def proc_user_auth_step(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
global PENDING_USER_INFO | |
global ADMIN_USER | |
global MASTER_USER | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug("USER_STEP[cid]: " + str(USER_STEP[cid])) | |
if m.text == u"거부": | |
user_keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True) | |
request_phone = types.KeyboardButton(u"동의", request_contact=True) | |
cancel_btn = types.KeyboardButton(u"거부") | |
user_keyboard.add(request_phone, cancel_btn) | |
msg = bot.send_message(cid, u"인증전에는 명령이나 메세지를 입력할 수 없습니다.", reply_markup=user_keyboard) | |
bot.register_next_step_handler(msg, proc_user_auth_step) | |
return | |
logger.debug(u"#############################USER_INFO#############################") | |
logger.debug(USER_INFO) | |
logger.debug(u"#############################USER_INFO#############################") | |
if cid in USER_INFO: | |
bot.send_message(cid, u"이미 로그인된 상태입니다.[STEP01]", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
try: | |
contact = m.contact.phone_number | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
user_keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True) | |
request_phone = types.KeyboardButton(u"동의", request_contact=True) | |
cancel_btn = types.KeyboardButton(u"거부") | |
user_keyboard.add(request_phone, cancel_btn) | |
msg = bot.send_message(cid, u"인증전에는 명령이나 메세지를 입력할 수 없습니다.", reply_markup=user_keyboard) | |
bot.register_next_step_handler(msg, proc_user_auth_step) | |
return | |
# +821063044385 | |
# 821031802131 | |
# print contact | |
logger.debug(str(contact)) | |
if cid not in USER_INFO.keys(): | |
if m.contact.last_name is None: | |
temp_last_name = "" | |
else: | |
temp_last_name = m.contact.last_name | |
if m.contact.first_name is None: | |
temp_first_name = "" | |
else: | |
temp_first_name = m.contact.first_name | |
PENDING_USER_INFO[cid] = { | |
u"user_name": temp_last_name + u" " + temp_first_name, | |
u"mobile_phone": contact | |
} | |
save_all_data() | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
btn_yes = types.InlineKeyboardButton(u"승인", callback_data=u"user_auth" + u"!#%%#!" | |
+ str([u"1", cid])) | |
btn_no = types.InlineKeyboardButton(u"거절", callback_data=u"user_auth" + u"!#%%#!" | |
+ str([u"0", cid])) | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
inline_btn_markup.row(btn_yes, btn_no, btn_cancel) | |
if m.contact.last_name is None: | |
temp_last_name = "" | |
else: | |
temp_last_name = m.contact.last_name | |
if m.contact.first_name is None: | |
temp_first_name = "" | |
else: | |
temp_first_name = m.contact.first_name | |
send_msg = u"[{}/{}]님이 올파일포유 사용 승인을 요청합니다.\n승인 하시겠습니까?".format( | |
str(temp_last_name + u" " + temp_first_name), | |
str(contact) | |
) | |
for admin_cid in ADMIN_USER: | |
if admin_cid in MASTER_USER: | |
continue | |
bot.send_message(admin_cid, send_msg, parse_mode=u"HTML", reply_markup=inline_btn_markup) | |
for master_cid in MASTER_USER: | |
bot.send_message(master_cid, send_msg, parse_mode=u"HTML", reply_markup=inline_btn_markup) | |
bot.send_message(cid, (u"관리자에게 사용자 인증을 요청하였습니다.\n" | |
u"관리자가 승인하면 알림메세지로 알려드립니다.\n"), | |
reply_markup=types.ReplyKeyboardRemove()) | |
else: | |
if m.contact.last_name is None: | |
temp_last_name = "" | |
else: | |
temp_last_name = m.contact.last_name | |
if m.contact.first_name is None: | |
temp_first_name = "" | |
else: | |
temp_first_name = m.contact.first_name | |
USER_INFO[cid] = { | |
u"user_name": temp_last_name + u" " + temp_first_name, | |
u"mobile_phone": contact | |
} | |
save_all_data() | |
logger.debug(str(USER_INFO)) | |
save_all_data() | |
bot.send_message(cid, u"{0}님의 사용자 인증이 완료되었습니다.".format(USER_INFO[cid][u'user_name']), | |
reply_markup=types.ReplyKeyboardRemove()) | |
bot.send_message(cid, (u"지금 즉시 모든 서비스 사용이 가능합니다.\n명령창에 \"/도움말\"을 입력하시어" | |
u" 사용가능한 명령어를 확인하세요."), | |
reply_markup = types.ReplyKeyboardRemove()) | |
def proc_rgst_admin(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
if args[0] == u"/작업취소": | |
logger.debug(u"작업취소 명령으로 인한 사용자 작업취소!!") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug(u"bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"작업이 취소 되었습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if (cid not in ADMIN_USER) and (cid not in MASTER_USER): | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug("bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"작업이 취소 되었습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
logger.debug(args) | |
args = u"".join(args) | |
logger.debug(args) | |
args_admin_option = args.split(u"/") | |
logger.debug(args_admin_option) | |
if args_admin_option[1] in ADMIN_USER: | |
bot.send_message(cid, u"{} 사용자는 이미 관리자 등록이 되어 있습니다.".format(args_admin_option[0])) | |
ADMIN_USER[args_admin_option[1]] = { | |
u"user_type": args_admin_option[3] | |
} | |
logger.debug(u"ADMIN_USER list: ") | |
logger.debug(str(ADMIN_USER)) | |
save_all_data() | |
bot.send_message(cid, u"{}님이 {}타입의 관리자로 등록되었습니다.".format(args_admin_option[0], | |
args_admin_option[3])) | |
if args_admin_option[3] == u"S": | |
admin_type = u"S" | |
type_name = u"슈퍼유저" | |
else: | |
admin_type = u"N" | |
type_name = u"관리자" | |
if len(USER_INFO) > 0: | |
# 인라인키보드 생성 및 화면 출력 | |
markup = types.ReplyKeyboardMarkup(one_time_keyboard=False) | |
for key in USER_INFO: | |
markup_text = u"" | |
if key in ADMIN_USER: | |
logger.debug("[{}]기등록 관리자 제외".format(key)) | |
continue | |
if admin_type == u"S": | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key]["user_name"], key, u"관리자등록", u"S") | |
else: | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key]["user_name"], key, u"관리자등록", u"N") | |
markup.add(markup_text) | |
markup.add(u"/작업취소") | |
msg = bot.reply_to(m, (u"계속해서 {}로 등록할 사용자를 선택 하여주세요.\n" | |
u"더이상 없으시면 작업취소 버튼을 눌러주세요.").format(type_name), reply_markup=markup) | |
bot.register_next_step_handler(msg, proc_rgst_admin) | |
else: | |
bot.send_message(cid, u"{}로 등록할 사용자가 존재하지 않습니다.".format(type_name)) | |
return 0 | |
def proc_del_admin(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
if args[0] == u"/작업취소": | |
logger.debug(u"작업취소 명령으로 인한 사용자 작업취소!!") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug("bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"작업이 취소 되었습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if (cid not in ADMIN_USER) and (cid not in MASTER_USER): | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug(u"bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
return 0 | |
logger.debug(args) | |
args = u"".join(args) | |
logger.debug(args) | |
args_admin_option = args.split(u"/") | |
logger.debug(args_admin_option) | |
if args_admin_option[1] in ADMIN_USER: | |
ADMIN_USER.pop(args_admin_option[1]) | |
bot.send_message(cid, u"{} 사용자의 관리자 권한이 삭제되었습니다.".format(args_admin_option[0])) | |
else: | |
bot.send_message(cid, u"{} 사용자는 관리자로 등록 되어있지 않습니다.".format(args_admin_option[0])) | |
logger.debug(str(ADMIN_USER)) | |
save_all_data() | |
add_cnt = 0 | |
if len(ADMIN_USER) > 0: | |
# 인라인키보드 생성 및 화면 출력 | |
markup = types.ReplyKeyboardMarkup(one_time_keyboard=False) | |
for key in ADMIN_USER: | |
markup_text = u"" | |
if ADMIN_USER[key][u"user_type"] == u"S": | |
continue | |
else: | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key][u"user_name"], key, u"관리자삭제", u"N") | |
if len(markup_text) > 0: | |
markup.add(markup_text) | |
add_cnt += 1 | |
if add_cnt <= 0: | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug("bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"삭제할 관리자가 존재하지 않습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
markup.add(u"/작업취소") | |
msg = bot.reply_to(m, u"삭제할 관리자를 선택 하여주세요.", reply_markup=markup) | |
bot.register_next_step_handler(msg, proc_del_admin) | |
else: | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug("bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"삭제할 관리자가 존재하지 않습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
def proc_kick_a_user(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
if args[0] == u"/작업취소": | |
logger.debug(u"작업취소 명령으로 인한 사용자 작업취소!!") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug("bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"작업이 취소 되었습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if (cid not in ADMIN_USER) and (cid not in MASTER_USER): | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug(u"bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
return 0 | |
logger.debug(args) | |
args = u"".join(args) | |
logger.debug(args) | |
args_option = args.split(u"/") | |
logger.debug(args_option) | |
if args_option[1] in USER_INFO: | |
USER_INFO.pop(args_option[1]) | |
if args_option[1] in USER_STEP: | |
USER_STEP.pop(args_option[1]) | |
if args_option[1] in ADMIN_USER: | |
ADMIN_USER.pop(args_option[1]) | |
bot.send_message(args_option[1], (u"[알림]서비스 이용중 불편 드려 죄송합니다.\n" | |
u"{} 사용자의 로그인 인증이 {} 관리자에 의해 취소 되었습니다.\n" | |
u"다시 사용을 원하시면 /시작 명령을 통해 재인증 후 사용 하여주세요.\n" | |
u"감사합니다.".format(args_option[0], USER_INFO[cid][u"user_name"]))) | |
bot.send_message(cid, u"{} 사용자 인증이 취소 되었습니다.".format(args_option[0])) | |
logger.debug(str(USER_INFO)) | |
save_all_data() | |
add_cnt = 0 | |
if len(USER_INFO) > 0: | |
# 인라인키보드 생성 및 화면 출력 | |
markup = types.ReplyKeyboardMarkup(one_time_keyboard=False) | |
for key in USER_INFO: | |
markup_text = u"" | |
if key in ADMIN_USER: | |
if ADMIN_USER[key][u"user_type"] == u"S": | |
logger.debug(u"[{}]슈퍼유저 제외".format(key)) | |
continue | |
if key in MASTER_USER: | |
logger.debug(u"[{}]마스터유저 제외".format(key)) | |
continue | |
user_type = "관리자" | |
else: | |
user_type = "일반" | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key][u"user_name"], key, u"인증취소", user_type) | |
if len(markup_text) > 0: | |
markup.add(markup_text) | |
add_cnt += 1 | |
if add_cnt <= 0: | |
bot.send_message(cid, u"인증 취소할 사용자가 존재하지 않습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
markup.add(u"/작업취소") | |
msg = bot.reply_to(m, u"인증 취소할 사용자를 선택 하여주세요.", reply_markup=markup) | |
bot.register_next_step_handler(msg, proc_kick_a_user) | |
else: | |
bot.send_message(cid, u"인증 취소할 사용자가 존재하지 않습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
# handle the "/start" command | |
@bot.message_handler(commands=[u"시작", u"start"]) | |
def cmd_start(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = "" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug("args: " + str(args)) | |
if cid in USER_STEP: logger.debug("USER_STEP[cid]: " + str(USER_STEP[cid])) | |
noti_msg = u""" | |
올파일포유 서비스에 오신것을 환영합니다. | |
올파일포유 서비스는 관리자에의해 승인된 사용자만 사용 가능합니다. | |
올파일포유 서비스는 서비스제공을 위하여 텔레그램 메신져를 이용하며, 이에따른 개인정보 수집, 이용에 관한 사용자 동의가 필요합니다. | |
원치 않으시면 이 채팅방을 나가시면 됩니다. | |
<개인정보 수집, 이용안내> | |
1. 수집하는 개인정보 항목: 성명, 전화번호 | |
2. 수집목적: 올파일포유 서비스 제공 | |
3. 보유 및 이용기간: 로그아웃시까지 | |
올파일포유 서비스 이용을 위해 개인정보 수집, 이용 안내에 대해서 동의하십니까? | |
""" | |
if cid not in USER_INFO: | |
bot.send_message(cid, noti_msg) | |
cmd_user_auth(m) | |
else: | |
bot.send_message(cid, (u"{0}님은 이미 로그인된 상태입니다.\n" | |
u"/도움말을 입력하시면 사용가능한 명령어 확인이 가능합니다.").format( | |
USER_INFO[cid][u"user_name"] | |
)) | |
@bot.message_handler(commands=[u"로그아웃"]) | |
def cmd_user_logout(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global ADMIN_USER | |
global PENDING_USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 유저리스트 로그아웃처리 | |
logger.debug(u"User signed out.") | |
if cid in USER_INFO.keys(): | |
USER_INFO.pop(cid) | |
if cid in ADMIN_USER.keys(): | |
ADMIN_USER.pop(cid) | |
if cid in PENDING_USER_INFO.keys(): | |
PENDING_USER_INFO.pop(cid) | |
if cid in USER_STEP.keys(): | |
USER_STEP.pop(cid) | |
save_all_data() | |
bot.send_message(cid, u"로그아웃 되었습니다.\n다시 시작을 원하시면 /시작 명령을 내려주세요.") | |
# help page | |
@bot.message_handler(commands=[u"도움말", u"help"]) | |
def cmd_help(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
rpt_cnt = 30 | |
help_text = u"사용자 명령어 리스트: \n\n" | |
for key in main_cmd_list: | |
if main_cmd_list[key] == u"#": | |
help_text += u"#" * rpt_cnt + u"\n" | |
else: | |
help_text += u"/" + key + u": " | |
help_text += main_cmd_list[key] + u"\n" | |
bot.send_message(cid, help_text) | |
if cid in ADMIN_USER: | |
help_text = u"관리자 명령어 리스트: \n\n" | |
for key in admin_cmd_list: | |
if admin_cmd_list[key] == u"#": | |
help_text += u"#" * rpt_cnt + u"\n" | |
else: | |
help_text += u"/" + key + u": " | |
help_text += admin_cmd_list[key] + u"\n" | |
bot.send_message(cid, help_text) | |
@bot.message_handler(commands=[u"인증요청"]) | |
def cmd_user_auth(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
user_keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True) | |
request_phone = types.KeyboardButton(u"동의", request_contact=True) | |
cancel_btn = types.KeyboardButton(u"거부") | |
user_keyboard.add(request_phone, cancel_btn) | |
msg = bot.send_message(cid, (u"개인정보 수집, 이용안내에 동의하시고 사용자 인증을 원하시면 아래 " | |
u"동의 버튼을 눌러주세요.\n원치않으시면 이방을 나가시면 됩니다."), | |
reply_markup=user_keyboard) | |
bot.register_next_step_handler(msg, proc_user_auth_step) | |
@bot.message_handler(commands=[u"누구"]) | |
def command_show_whos_in(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = "" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in ADMIN_USER: | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
return 0 | |
if len(USER_INFO) <= 0: | |
bot.send_message(cid, u"현재 서비스를 이용중인 사용자가 없습니다.") | |
return 0 | |
bot.send_message(cid, u"참여자 리스트") | |
# USER_INFO = {} # {'287456840': {'user_name': 'SHIM YUN-BO', 'mobile_phone': '+821031802131'}} | |
return_text = u"" | |
for idx, key in enumerate(USER_INFO): | |
return_text += u"{}, {}, {}\n".format(str(idx + 1), key, USER_INFO[key][u"user_name"]) | |
bot.send_message(cid, return_text) | |
bot.send_message(cid, u"참여자 리스트 조회가 완료 되었습니다.") | |
@bot.message_handler(commands=[u"내아이디"]) | |
def command_show_my_id(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = "" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if len(USER_INFO) <= 0: | |
bot.send_message(cid, u"현재 서비스를 이용중인 사용자가 없습니다.") | |
return 0 | |
bot.send_message(cid, u"나의 텔레그램 ID는") | |
# USER_INFO = {} # {'287456840': {'user_name': 'SHIM YUN-BO', 'mobile_phone': '+821031802131'}} | |
return_text = u"" | |
return_text += u"{}, {}\n".format(cid, USER_INFO[cid][u"user_name"]) | |
bot.send_message(cid, return_text) | |
bot.send_message(cid, u"내아이디 조회가 완료 되었습니다.") | |
@bot.message_handler(commands=[u"셧다운"]) | |
def cmd_shutdown_server(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in MASTER_USER: | |
bot.send_message(cid, u"입력하신 명령어는 운영자만 사용 가능한 명령입니다.") | |
return 0 | |
if len(USER_INFO) > 0: | |
for user_cid in USER_INFO.keys(): | |
bot.send_message(user_cid, u"[알림]운영자의 셧다운 명령으로 서비스를 종료합니다.") | |
else: | |
logger.debug(u"종료 메세지를 보낼 참여자가 없습니다.") | |
stop_service() | |
@bot.message_handler(commands=[u"관리자등록"]) | |
def cmd_rgst_admin(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global MASTER_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# if len(args) < 2: | |
# bot.send_message(cid, u"명령어 형식이 올바르지 않습니다.") | |
# return 0 | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in ADMIN_USER and cid not in MASTER_USER: | |
if not (datetime.datetime.now().strftime("%H") + u"12570" + datetime.datetime.now().strftime("%d") + u"2131" in args[1]): | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
return 0 | |
if len(args) >= 2 and args[1] == u"S" and cid in MASTER_USER: | |
if cid not in MASTER_USER: | |
bot.send_message(cid, u"슈퍼유저로의 관리자 등록은 운영자만 가능합니다.") | |
return 0 | |
admin_type = u"S" | |
type_name = u"슈퍼유저" | |
else: | |
admin_type = u"N" | |
type_name = u"관리자" | |
if len(USER_INFO) > 0: | |
# 인라인키보드 생성 및 화면 출력 | |
markup = types.ReplyKeyboardMarkup(one_time_keyboard=False) | |
for key in USER_INFO: | |
markup_text = u"" | |
if key in ADMIN_USER: | |
logger.debug("[{}]기등록 관리자 제외".format(key)) | |
continue | |
if admin_type == u"S": | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key][u"user_name"], key, u"관리자등록", u"S") | |
else: | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key][u"user_name"], key, u"관리자등록", u"N") | |
markup.add(markup_text) | |
markup.add(u"/작업취소") | |
msg = bot.reply_to(m, u"{}로 등록할 사용자를 선택 하여주세요.".format(type_name), reply_markup=markup) | |
bot.register_next_step_handler(msg, proc_rgst_admin) | |
else: | |
bot.send_message(cid, u"{}로 등록할 사용자가 존재하지 않습니다.".format(type_name)) | |
return 0 | |
@bot.message_handler(commands=[u"관리자삭제"]) | |
def cmd_del_admin(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in ADMIN_USER: | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
return 0 | |
add_cnt = 0 | |
if len(ADMIN_USER) > 0: | |
# 인라인키보드 생성 및 화면 출력 | |
markup = types.ReplyKeyboardMarkup(one_time_keyboard=False) | |
for key in ADMIN_USER: | |
markup_text = u"" | |
if ADMIN_USER[key][u"user_type"] == u"S": | |
continue | |
else: | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key][u"user_name"], key, u"관리자삭제", u"N") | |
if len(markup_text) > 0: | |
markup.add(markup_text) | |
add_cnt += 1 | |
if add_cnt <= 0: | |
bot.send_message(cid, u"삭제할 관리자가 존재하지 않습니다.") | |
return 0 | |
markup.add(u"/작업취소") | |
msg = bot.reply_to(m, u"삭제할 관리자를 선택 하여주세요.", reply_markup=markup) | |
bot.register_next_step_handler(msg, proc_del_admin) | |
else: | |
bot.send_message(cid, u"삭제할 관리자가 존재하지 않습니다.") | |
return 0 | |
@bot.message_handler(commands=[u"인증취소"]) | |
def cmd_kick_a_user(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in ADMIN_USER: | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
return 0 | |
add_cnt = 0 | |
if len(USER_INFO) > 0: | |
# 인라인키보드 생성 및 화면 출력 | |
markup = types.ReplyKeyboardMarkup(one_time_keyboard=False) | |
for key in USER_INFO: | |
markup_text = u"" | |
if key in ADMIN_USER: | |
if ADMIN_USER[key][u"user_type"] == u"S": | |
logger.debug(u"[{}]슈퍼유저 제외".format(key)) | |
continue | |
if key in MASTER_USER: | |
logger.debug(u"[{}]마스터유저 제외".format(key)) | |
continue | |
user_type = "관리자" | |
else: | |
user_type = "일반" | |
markup_text += u"{}/{}/{}/{}".format(USER_INFO[key][u"user_name"], key, u"인증취소", user_type) | |
if len(markup_text) > 0: | |
markup.add(markup_text) | |
add_cnt += 1 | |
if add_cnt <= 0: | |
bot.send_message(cid, u"인증 취소할 사용자가 존재하지 않습니다.") | |
return 0 | |
markup.add(u"/작업취소") | |
msg = bot.reply_to(m, u"인증 취소할 사용자를 선택 하여주세요.", reply_markup=markup) | |
bot.register_next_step_handler(msg, proc_kick_a_user) | |
else: | |
bot.send_message(cid, u"인증 취소할 사용자가 존재하지 않습니다.") | |
return 0 | |
@bot.message_handler(commands=[u"환경저장"]) | |
def cmd_save_env_immediately(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in ADMIN_USER: | |
bot.send_message(cid, u"입력하신 명령어는 관리자만 사용 가능한 명령입니다.") | |
return 0 | |
save_all_data() | |
bot.send_message(cid, u"환경 저장이 완료되었습니다.") | |
@bot.message_handler(commands=[u"검색"]) | |
def cmd_fileis_search(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global SESS | |
global USER_ID | |
global USER_PW | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
# 02. 파라메터 형식 체크 | |
if len(args) <= 1: | |
bot.send_message(cid, (u"명령어 형식이 올바르지 않습니다.\n" | |
u"/검색 [키워드] 형식으로 사용하여주세요!!")) | |
return 0 | |
if args[len(args)-1] == u"성인제외": | |
except_adult = u"Y" | |
else: | |
except_adult = u"N" | |
if except_adult == u"Y": | |
keyword = u" ".join(args[1:len(args)-1]) | |
else: | |
keyword = u" ".join(args[1:]) | |
logger.debug(u"keyword: " + str(keyword)) | |
if len(keyword.strip()) < 2: | |
bot.send_message(cid, u"검색 키워드는 2글자 이상이어야 합니다.") | |
return 0 | |
if not keep_alive(m, USER_ID, USER_PW): | |
return 0 | |
# 검색 | |
search_results = fileis.search_in_fileis(SESS, keyword, 25, except_adult) | |
logger.debug(u"search_results: " + str(search_results)) | |
cur_page_num = search_results[1] | |
last_page_num = search_results[2] | |
search_results = search_results[0] | |
if len(search_results) <= 0: | |
bot.send_message(cid, u"입력하신 키워드로 검색되는 결과가 없습니다.") | |
return 0 | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
for idx, x in enumerate(search_results): | |
btn_result = types.InlineKeyboardButton(text=str(idx + 1) + u", " + str_format(str(x[1]), 50, fill=u"_"), | |
callback_data=u"file_info" + u"!#%%#!" + str(x[0])) | |
inline_btn_markup.row(btn_result) | |
logger.debug(u"cur_page_num: " + cur_page_num) | |
logger.debug(u"last_page_num: " + last_page_num) | |
if int(last_page_num) > 1: | |
btn_prev_page = types.InlineKeyboardButton(u"이전페이지", | |
callback_data=u"sn" + u"!#%%#!" | |
+ str([int(cur_page_num) - 1, keyword, except_adult])) | |
btn_next_page = types.InlineKeyboardButton(u"다음페이지", | |
callback_data=u"sn" + u"!#%%#!" | |
+ str([int(cur_page_num) + 1, keyword, except_adult])) | |
callback_prev = len(str(u"sn" + u"!#%%#!" + str([int(cur_page_num) - 1, keyword, except_adult])).encode("utf-8")) | |
callback_next = len(str(u"sn" + u"!#%%#!" + str([int(cur_page_num) + 1, keyword, except_adult])).encode("utf-8")) | |
logger.debug(u"callback_prev: " + str(callback_prev)) | |
logger.debug(u"callback_next: " + str(callback_next)) | |
if callback_prev > 60 or callback_next > 60: | |
bot.send_message(cid, u"검색 키워드가 너무 길어 다음페이지를 표시할 수 없습니다.") | |
else: | |
if int(last_page_num) > 1: | |
if int(cur_page_num) == 1: | |
inline_btn_markup.row(btn_next_page) | |
elif 1 < int(cur_page_num) < int(last_page_num): | |
inline_btn_markup.row(btn_prev_page, btn_next_page) | |
elif int(cur_page_num) == int(last_page_num): | |
inline_btn_markup.row(btn_prev_page) | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
inline_btn_markup.row(btn_cancel) | |
bot.send_message(cid, u"[{}] 키워드로 검색이 완료 되었습니다.".format(keyword), parse_mode=u"HTML", | |
reply_markup=inline_btn_markup) | |
@bot.message_handler(commands=[u"파일정보"]) | |
def cmd_get_file_info(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global SESS | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if len(args) <= 1: | |
bot.send_message(cid, (u"명령어 형식이 올바르지 않습니다.\n" | |
u"/파일정보 [파일번호] 형식으로 사용하여주세요!!")) | |
return 0 | |
if not str(args[1]).isdigit(): | |
bot.send_message(cid, u"파일번호는 숫자로만 이루어져야 합니다.") | |
return 0 | |
if not keep_alive(m, USER_ID, USER_PW): | |
return 0 | |
search_results = fileis.get_files_info(SESS, str(args[1])) | |
return_text = u"" | |
for idx, file_info in enumerate(search_results): | |
return_text += (u"순번: {}\n" | |
u"파일명: {}\n" | |
u"용량: {}\n" | |
u"화질: {}\n" | |
u"해상도: [{}]\n\n".format(str(idx), | |
str(file_info[0]).strip(), | |
str(file_info[1]).strip(), | |
str(file_info[2]).strip(), | |
str(file_info[3]).strip())) | |
logger.debug(str(return_text)) | |
if not (idx % 5): | |
bot.send_message(cid, return_text) | |
return_text = u"" | |
if len(str(return_text).strip()) > 0: | |
bot.send_message(cid, return_text) | |
bot.send_message(cid, u"[{}]번 파일정보 조회가 완료 되었습니다.".format(str(args[1]))) | |
# @bot.message_handler(commands=[u"다운로더실행"]) | |
def cmd_exec_fileis_fdl(): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
global FDL_PID | |
cid = MASTER_USER[0] | |
# try: | |
# args = m.text.split() | |
# except AttributeError as e: | |
# logger.error(get_trace_this_point(0)) | |
# logger.error(get_trace_this_point(1)) | |
# logger.error(get_trace_this_point(2)) | |
# logger.error(e.args) | |
# args = u"" | |
# if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
# logger.debug(u"args: " + str(args)) | |
# if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# | |
# bot.send_chat_action(cid, u"typing") | |
# | |
# # 01. 인증여부체크 | |
# if cid not in USER_INFO: | |
# bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
# reply_markup=types.ReplyKeyboardRemove()) | |
# return 0 | |
# | |
# if cid not in MASTER_USER: | |
# bot.send_message(cid, u"입력하신 명령어는 운영자만 사용 가능한 명령입니다.") | |
# return 0 | |
try: | |
fileis_hwnd = win32gui.FindWindow("Fileis_class_down", None) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"다운로더 검색중 오류가 발생하였습니다.") | |
bot.send_message(cid, u"다운로더 검색중 오류가 발생하였습니다.") | |
return 0 | |
if fileis_hwnd != 0: | |
logger.debug(u"Fileis downloader is already executed!!") | |
bot.send_message(cid, u"파일 다운로더가 이미 실행중입니다.") | |
for idx, x in enumerate(fileis.get_fdl_status()): | |
logger.debug(str(idx) + u"\n" + str(x[0]) + u"\n" + str(x[1]) + u"\n" + str(x[2])) | |
else: | |
bot.send_message(cid, u"다운로더가 대기중입니다.") | |
pass | |
return -1 | |
try: | |
FDL_PID = fileis.run_directly_fdl(USER_ID, HASH_PW) | |
delay(2) | |
if not win32gui.FindWindow("Fileis_class_down", None): | |
bot.send_message(cid, u"다운로더 실행에 실패하였습니다.") | |
return 0 | |
for idx, x in enumerate(fileis.get_fdl_status()): | |
logger.debug(str(idx) + u"\n" + str(x[0]) + u"\n" + str(x[1]) + u"\n" + str(x[2])) | |
bot.send_message(cid, u"다운로더 실행이 완료 되었습니다.") | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
bot.send_message(cid, u"파일 다운로더 실행에 실패하였습니다.") | |
return 0 | |
# @bot.message_handler(commands=[u"다운로더중지"]) | |
def cmd_kill_fileis_fdl(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global FDL_PROC | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if cid not in MASTER_USER: | |
bot.send_message(cid, u"입력하신 명령어는 운영자만 사용 가능한 명령입니다.") | |
return 0 | |
try: | |
fileis_hwnd = win32gui.FindWindow(u"Fileis_class_down", None) | |
except Exception as e: | |
bot.send_message(cid, u"실행중인 파일다운로더가 없습니다.") | |
return 0 | |
if fileis_hwnd <= 0: | |
logger.debug(u"File downloader is not running..") | |
bot.send_message(cid, u"실행중인 파일다운로더가 없습니다.") | |
return -1 | |
try: | |
FDL_PROC.kill() | |
FDL_PROC = None | |
if not FDL_PROC: | |
logger.error(u"File downloader closing failed.") | |
bot.send_message(cid, u"파일 다운로더 종료에 실패하였습니다.") | |
return -1 | |
bot.send_message(cid, u"파일 다운로더 종료를 완료하였습니다.") | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
bot.send_message(cid, u"파일 다운로더 종료에 실패하였습니다.") | |
return -1 | |
@bot.message_handler(commands=[u"다운예약"]) | |
def cmd_download_directely(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global SESS | |
global WEBCTRL | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return -1 | |
if len(args) < 2: | |
bot.send_message(cid, (u"명령어 형식이 올바르지 않습니다.\n" | |
u"/직접다운 [파일번호] 형식으로 입력하셔야 합니다." | |
u"예) /직접다운 7287563")) | |
return -1 | |
if not str(args[1]).isdigit(): | |
bot.send_message(cid, (u"파일번호는 숫자만 입력하셔야 합니다." | |
u"예) /직접다운 7287563")) | |
return -1 | |
if not keep_alive(m, USER_ID, USER_PW): | |
return -1 | |
ret_value = fileis.get_download(SESS, WEBCTRL, USER_ID, args[1], cid, USER_INFO[cid][u"user_name"], | |
USER_INFO[cid][u"mobile_phone"], u"telegram", u"127.0.0.1") | |
if ret_value != "E": | |
bot.send_message(cid, (u"파일 다운로드 예약이 완료되었습니다.\n" | |
u"다운로드 예약 상태가 궁금하시면 /서버상태 " | |
u"명령으로 확인 하실 수 있습니다.\n")) | |
else: | |
logger.debug(str(ret_value)) | |
bot.send_message(cid, u"다운로드 예약에 실패하였습니다.") | |
return -1 | |
fld_status = fileis.get_fdl_status() | |
bot.send_message(cid, u"현재 다운로더 상태는...") | |
for idx, x in enumerate(fld_status): | |
idx += 1 | |
return_text = u"" | |
if idx >= len(fld_status) - 1: | |
return_text += (u"순번: {}\n" | |
u"파일명: {}\n" | |
u"용량: {}\n" | |
u"상태: {}".format(str(idx), | |
x[0].decode(u"euc-kr"), | |
x[1].decode(u"euc-kr"), | |
x[2].decode(u"euc-kr"))) | |
logger.debug(return_text) | |
bot.send_message(cid, return_text) | |
else: | |
continue | |
bot.send_message(cid, u"다운로더 상태출력을 완료 하였습니다.") | |
@bot.message_handler(commands=[u"서버상태"]) | |
def cmd_get_status_of_fdl(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
fileis_hwnd = win32gui.FindWindow("Fileis_class_down", None) | |
if fileis_hwnd == 0: | |
logger.debug(u"Fileis downloader is not existed!!") | |
bot.send_message(cid, u"실행중인 파일 다운로더가 없습니다.") | |
return 0 | |
fld_status = fileis.get_fdl_status() | |
if len(fld_status) <= 0: | |
bot.send_message(cid, u"다운로드중인 파일이 없습니다.") | |
return 0 | |
bot.send_message(cid, u"현재 다운로더 상태는...") | |
for idx, x in enumerate(fld_status): | |
idx += 1 | |
return_text = u"" | |
if idx >= len(fld_status) - 1: | |
return_text += (u"순번: {}\n" | |
u"파일명: {}\n" | |
u"용량: {}\n" | |
u"상태: {}\n".format(str(idx), | |
x[0].decode(u"euc-kr"), | |
x[1].decode(u"euc-kr"), | |
x[2].decode(u"euc-kr"))) | |
logger.debug(return_text) | |
bot.send_message(cid, return_text) | |
else: | |
continue | |
bot.send_message(cid, u"다운로더 상태출력을 완료 하였습니다.") | |
return 0 | |
@bot.message_handler(commands=[u"다시받기"]) | |
def cmd_get_status_of_fdl(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
file_lists = fileis.get_downfile_list(path=u"D:\\Download\\FileIs\\comp\\" + str(cid)) | |
logger.debug(str(len(file_lists))) | |
if len(file_lists) <= 0: | |
bot.send_message(cid, u"다시받기 가능한 파일이 없습니다.") | |
return 0 | |
page_num = 0 | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
last_print_flag = False | |
for idx, file_item in enumerate(file_lists): | |
idx += 1 | |
file_path, file_name = os.path.split(file_item) | |
if len(args) > 1 and args[1] == u"로컬": | |
file_down_link = file_path.replace(u"D:\\Download\\FileIs", | |
u"http://192.168.0.8:5002").replace(u"\\", u"/") + u"/" + urllib.parse.quote(file_name) | |
else: | |
file_down_link = file_path.replace(u"D:\\Download\\FileIs", | |
u"http://helloong.ipdisk.co.kr:5002").replace(u"\\", u"/") + u"/" + urllib.parse.quote(file_name) | |
logger.debug(u"file_down_link quoted: " + file_down_link) | |
btn_down_link = types.InlineKeyboardButton(str_format((str(idx) + u" " + file_name), width=50, fill=u"_"), | |
url=file_down_link) | |
inline_btn_markup.row(btn_down_link) | |
if not (idx % 10): | |
inline_btn_markup.row(btn_cancel) | |
bot.send_message(cid, u"다시받기 가능 리스트[{}]".format(str(page_num)), parse_mode=u"HTML", | |
reply_markup=inline_btn_markup) | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
page_num += 1 | |
last_print_flag = False | |
else: | |
last_print_flag = True | |
if last_print_flag: | |
page_num += 1 | |
inline_btn_markup.row(btn_cancel) | |
bot.send_message(cid, u"다시받기 가능 리스트[{}]".format(str(page_num)), parse_mode=u"HTML", | |
reply_markup=inline_btn_markup) | |
return 0 | |
@bot.message_handler(commands=[u"작업취소", u"취소", u"종료", u"cancel", u"exit"]) | |
def cmd_cancel(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
if m.chat.id in bot.pre_message_subscribers_next_step: | |
logger.debug(u"bot.pre_message_subscribers_next_step[cid]: " | |
+ str(bot.pre_message_subscribers_next_step[m.chat.id])) | |
bot.clear_step_handler(m) | |
bot.send_message(cid, u"작업이 취소 되었습니다.", reply_markup=types.ReplyKeyboardRemove()) | |
# @bot.message_handler(commands=[u"다운로드테스트"]) | |
def cmd_down_test(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
check_down_n_noti() | |
@bot.message_handler(commands=[u"브라우저", u"브라우저다운", u"브라우저다운로드", u"다운로드브라우저"]) | |
def cmd_download_browser(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.send_chat_action(cid, u"typing") | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
file_exists = os.path.isfile(u"D:\\Download\\FileIs\\web\\browser\\AllFilesForYou_Patched.exe") | |
logger.debug(str(file_exists)) | |
if not file_exists: | |
bot.send_message(cid, u"다운로드 가능한 전용 브라우저 파일이 없습니다.") | |
return 0 | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
if len(args) > 1 and args[1] == u"로컬": | |
file_down_link = u"http://192.168.0.8:5002/web/browser/" + urllib.parse.quote(u"AllFilesForYou_Patched.exe") | |
else: | |
file_down_link = u"http://helloong.ipdisk.co.kr:5002/web/browser/" + urllib.parse.quote(u"AllFilesForYou_Patched.exe") | |
logger.debug(u"file_down_link quoted: " + file_down_link) | |
btn_down_link = types.InlineKeyboardButton(u"브라우저 다운로드", url=file_down_link) | |
inline_btn_markup.row(btn_down_link) | |
inline_btn_markup.row(btn_cancel) | |
bot.send_message(cid, u"전용브라우저 다운로드\n[{}]".format(str(file_down_link)), parse_mode=u"HTML", | |
reply_markup=inline_btn_markup) | |
return 0 | |
# default handler for every other text | |
@bot.message_handler(func=lambda message: True, content_types=[u"text"]) | |
def cmd_default(m): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(m) | |
global USER_INFO | |
global USER_STEP | |
cid = str(m.chat.id) | |
try: | |
args = m.text.split() | |
except AttributeError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
args = u"" | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# this is the standard reply to a normal message | |
bot.send_message(m.chat.id, (u"요청 사항을 이해하지 못했습니다.\n" | |
"올파일포유 서비스 사용법이 궁금하시면 /도움말을 입력하시어 " | |
"아래와 같은 도움말을 언제든지 보실 수 있습니다.")) | |
@bot.callback_query_handler(func=lambda call: call.data[0:str(call.data).find(u"!#%%#!")] == u"sn") | |
def inline_search_next(call): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(call) | |
global USER_INFO | |
global USER_STEP | |
cid = str(call.message.chat.id) | |
uid = str(call.from_user.id) | |
mid = str(call.message.message_id) | |
# logger.debug(call.message.chat) | |
# logger.debug(call.from_user) | |
# logger.debug(call.message) | |
# logger.debug(call.data) | |
params = str(call.data).split(u"!#%%#!") | |
lnline_name = params[0] | |
args = eval(params[1]) | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
# delete message | |
bot.delete_message(cid, mid) | |
# 검색 | |
keyword = args[1] | |
search_results = fileis.parse_search_in_fileis(SESS, keyword, str(args[0]), 25, args[2]) | |
logger.debug(u"search_results: " + str(search_results)) | |
cur_page_num = search_results[1] | |
last_page_num = search_results[2] | |
search_results = search_results[0] | |
if len(search_results) <= 0: | |
bot.send_message(cid, u"입력하신 키워드로 검색되는 결과가 없습니다.") | |
return 0 | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
for idx, x in enumerate(search_results): | |
btn_result = types.InlineKeyboardButton(text=str(idx + 1) + u", " + str_format(str(x[1]), 50, fill=u"_"), | |
callback_data=u"file_info" + u"!#%%#!" + str(x[0])) | |
inline_btn_markup.row(btn_result) | |
logger.debug(u"cur_page_num: " + cur_page_num) | |
logger.debug(u"last_page_num: " + last_page_num) | |
if int(last_page_num) > 1: | |
btn_prev_page = types.InlineKeyboardButton(u"이전페이지", | |
callback_data=u"sn" + u"!#%%#!" | |
+ str([int(cur_page_num) - 1, keyword, args[2]])) | |
btn_next_page = types.InlineKeyboardButton(u"다음페이지", | |
callback_data=u"sn" + u"!#%%#!" | |
+ str([int(cur_page_num) + 1, keyword, args[2]])) | |
callback_prev = len(str(u"sn" + u"!#%%#!"+ str([int(cur_page_num) - 1, keyword, args[2]])).encode("utf-8")) | |
callback_next = len(str(u"sn" + u"!#%%#!"+ str([int(cur_page_num) + 1, keyword, args[2]])).encode("utf-8")) | |
logger.debug(u"callback_prev: " + str(callback_prev)) | |
logger.debug(u"callback_next: " + str(callback_next)) | |
if callback_prev > 60 or callback_next > 60: | |
bot.send_message(cid, u"검색키워드가 너무 길어 다음페이지를 표시할 수 없습니다.") | |
else: | |
if int(last_page_num) > 1: | |
if int(cur_page_num) == 1: | |
inline_btn_markup.row(btn_next_page) | |
elif 1 < int(cur_page_num) < int(last_page_num): | |
inline_btn_markup.row(btn_prev_page, btn_next_page) | |
elif int(cur_page_num) == int(last_page_num): | |
inline_btn_markup.row(btn_prev_page) | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
inline_btn_markup.row(btn_cancel) | |
bot.send_message(cid, u"[{}] 페이지 검색이 완료 되었습니다.".format(cur_page_num), parse_mode=u"HTML", | |
reply_markup=inline_btn_markup) | |
@bot.callback_query_handler(func=lambda call: call.data[0:str(call.data).find(u"!#%%#!")] == u"file_info") | |
def inline_file_info(call): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(str(call)) | |
global USER_INFO | |
global USER_STEP | |
cid = str(call.message.chat.id) | |
uid = str(call.from_user.id) | |
mid = str(call.message.message_id) | |
# logger.debug(call.message.chat) | |
# logger.debug(call.from_user) | |
# logger.debug(call.message) | |
# logger.debug(call.data) | |
params = str(call.data).split(u"!#%%#!") | |
lnline_name = params[0] | |
args = eval(params[1]) | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
search_results = fileis.get_files_info(SESS, str(args)) | |
logger.debug(u"search_results: " + str(search_results)) | |
return_text = u"" | |
is_deleted = False | |
for idx, file_info in enumerate(search_results): | |
idx += 1 | |
if u"해당 컨텐츠는 삭제된 컨텐츠입니다." in str(file_info[0]): | |
is_deleted = True | |
break | |
return_text += (u"순번: {}\n" | |
u"파일명: {}\n" | |
u"용량: {}\n" | |
u"화질: {}\n" | |
u"해상도: [{}]\n\n".format(str(idx), | |
str(file_info[0]).strip(), | |
str(file_info[1]).strip(), | |
str(file_info[2]).strip(), | |
str(file_info[3]).strip())) | |
logger.debug(str(return_text)) | |
if not (idx % 5): | |
bot.send_message(cid, return_text) | |
return_text = u"" | |
if not is_deleted: | |
if len(str(return_text).strip()) > 0: | |
bot.send_message(cid, return_text) | |
inline_btn_markup = types.InlineKeyboardMarkup() | |
btn_result = types.InlineKeyboardButton(text=u"다운예약", | |
callback_data=u"file_down" + u"!#%%#!" + str(args)) | |
btn_cancel = types.InlineKeyboardButton(u"취소", callback_data=u"btn_cancel") | |
inline_btn_markup.row(btn_result, btn_cancel) | |
bot.send_message(cid, u"[{}]번 파일정보 조회가 완료 되었습니다.".format(str(args)), parse_mode=u"HTML", | |
reply_markup=inline_btn_markup) | |
else: | |
bot.send_message(cid, search_results[0][0]) | |
@bot.callback_query_handler(func=lambda call: call.data[0:str(call.data).find(u"!#%%#!")] == u"file_down") | |
def inline_file_down(call): | |
logger.debug(get_trace_this_point(9)) | |
cid = str(call.message.chat.id) | |
uid = str(call.from_user.id) | |
mid = str(call.message.message_id) | |
# logger.debug(call.message.chat) | |
# logger.debug(call.from_user) | |
# logger.debug(call.message) | |
# logger.debug(call.data) | |
params = str(call.data).split(u"!#%%#!") | |
lnline_name = params[0] | |
args = eval(params[1]) | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
# 01. 인증여부체크 | |
if cid not in USER_INFO: | |
bot.send_message(cid, u"사용자 미인증 상태입니다.\n/시작 명령을 입력하여 사용자 인증 후 재시도 하여주세요.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
ret_value = fileis.get_download(SESS, WEBCTRL, USER_ID, str(args), cid, USER_INFO[cid][u"user_name"], | |
USER_INFO[cid][u"mobile_phone"], u"telegram", u"127.0.0.1") | |
if ret_value != "E": | |
# delete message if download request succeed!! | |
bot.delete_message(cid, mid) | |
bot.send_message(cid, (u"파일 다운로드 예약이 완료되었습니다.\n" | |
u"다운로드 예약 상태가 궁금하시면 /서버상태 " | |
u"명령으로 확인 하실 수 있습니다.\n")) | |
fld_status = fileis.get_fdl_status() | |
bot.send_message(cid, u"현재 다운로더 상태는...") | |
for idx, x in enumerate(fld_status): | |
idx += 1 | |
return_text = u"" | |
if idx >= len(fld_status) - 1: | |
return_text += (u"순번: {}\n" | |
u"파일명: {}\n" | |
u"용량: {}\n" | |
u"상태: {}".format(str(idx), | |
x[0].decode(u"euc-kr"), | |
x[1].decode(u"euc-kr"), | |
x[2].decode(u"euc-kr"))) | |
logger.debug(return_text) | |
bot.send_message(cid, return_text) | |
else: | |
continue | |
bot.send_message(cid, u"다운로더 상태출력을 완료 하였습니다.") | |
else: | |
logger.debug(str(ret_value)) | |
bot.send_message(cid, u"다운로드 예약에 실패하였습니다.") | |
return -1 | |
return 0 | |
@bot.callback_query_handler(func=lambda call: call.data[0:str(call.data).find(u"!#%%#!")] == u"user_auth") | |
def inline_user_auth(call): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(str(call)) | |
global USER_INFO | |
global USER_STEP | |
global PENDING_USER_INFO | |
global ADMIN_USER | |
global MASTER_USER | |
cid = str(call.message.chat.id) | |
uid = str(call.from_user.id) | |
mid = str(call.message.message_id) | |
# logger.debug(call.message.chat) | |
# logger.debug(call.from_user) | |
# logger.debug(call.message) | |
# logger.debug(call.data) | |
params = str(call.data).split(u"!#%%#!") | |
lnline_name = params[0] | |
args = eval(params[1]) | |
if cid in USER_INFO: USER_STEP[cid] = get_trace_this_point(2) | |
logger.debug(u"args: " + str(args)) | |
if cid in USER_STEP: logger.debug(u"USER_STEP[cid]: " + str(USER_STEP[cid])) | |
bot.delete_message(cid, mid) | |
# 01. 인증여부체크 | |
if (cid not in ADMIN_USER) and (cid not in MASTER_USER): | |
bot.send_message(cid, u"사용자 인증요청 승인은 관리자만 가능합니다.", | |
reply_markup=types.ReplyKeyboardRemove()) | |
return 0 | |
if args[0] == u"1": | |
# approved | |
if args[1] not in USER_INFO: | |
temp_user_info = PENDING_USER_INFO[args[1]] | |
USER_INFO[args[1]] = temp_user_info | |
if args[1] in PENDING_USER_INFO: | |
del(PENDING_USER_INFO[args[1]]) | |
noti_msg = (u"[{}]님이 [{}]님의 인증요청을 승인 하였습니다.".format( | |
USER_INFO[cid][u"user_name"], | |
USER_INFO[args[1]]["user_name"] | |
)) | |
save_all_data() | |
bot.send_message(args[1], noti_msg) | |
bot.send_message(args[1], (u"지금 즉시 모든 서비스 사용이 가능합니다.\n명령창에 \"/도움말\"을 입력하시어 " | |
u"사용가능한 명령어를 확인하세요.")) | |
for admin_cid in ADMIN_USER: | |
if admin_cid in MASTER_USER: | |
continue | |
bot.send_message(admin_cid, noti_msg) | |
for master_cid in MASTER_USER: | |
bot.send_message(master_cid, noti_msg) | |
else: | |
bot.send_message(cid, u"이미 다른 관리자에 의해 인증요청이 승인된 사용자입니다.") | |
else: | |
# rejected | |
if args[1] not in USER_INFO: | |
noti_msg = (u"[{}]님이 [{}]님의 인증요청을 거부 하였습니다.".format( | |
USER_INFO[cid][u"user_name"], | |
PENDING_USER_INFO[args[1]]["user_name"] | |
)) | |
try: | |
del(PENDING_USER_INFO[args[1]]) | |
except Exception as e: | |
pass | |
save_all_data() | |
bot.send_message(args[1], noti_msg) | |
bot.send_message(args[1], u"인증해달라고 조른후 다시 시도해주세요!!") | |
for admin_cid in ADMIN_USER: | |
if admin_cid in MASTER_USER: | |
continue | |
bot.send_message(admin_cid, noti_msg) | |
for master_cid in MASTER_USER: | |
bot.send_message(master_cid, noti_msg) | |
return -1 | |
else: | |
bot.send_message(cid, (u"[{}]님은 이미 다른 관리자에 의해 승인되었습니다.\n" | |
u"승인을 취소하시고 싶으시면 /인증취소 명령을 사용하여 주세요.".format( | |
USER_INFO[args[1]][u"user_name"] | |
))) | |
return -1 | |
return 0 | |
@bot.callback_query_handler(func=lambda call: call.data == u"btn_cancel") | |
def inline_cancel(call): | |
logger.debug(get_trace_this_point(9)) | |
# logger.debug(str(call)) | |
cid = str(call.message.chat.id) | |
uid = str(call.from_user.id) | |
mid = str(call.message.message_id) | |
# logger.debug(call.message) | |
# logger.debug(call.data) | |
# logger.debug(str(cid) + u"/" + str(uid) + u"/" + str(mid)) | |
try: | |
bot.delete_message(cid, mid) | |
except Exception as e: | |
logger.error(e) | |
def clean_day_off(): | |
logger.debug(get_trace_this_point(9)) | |
global FDL_PID | |
global USER_ID | |
global HASH_PW | |
fileis.clean_all_system(u"D:\\Download\\FileIs", FDL_PID) | |
# FDL_PID = fileis.run_directly_fdl(USER_ID, HASH_PW) | |
if __name__ == "__main__": | |
logger = fileis_logger.get_logger("allfilesforyou") | |
# 메인 시작!! | |
logger.debug(get_trace_this_point(9)) | |
cmd_exec_fileis_fdl() | |
# FileIs Login | |
if not fileis.login_to_fileis(SESS, USER_ID, USER_PW): | |
logger.debug(u"Failed to sign in to the fileis site!!") | |
sys.exit() | |
SCHED.add_job(keep_alive_apsche, "interval", seconds=1800, coalesce=True) | |
SCHED.add_job(check_down_n_noti, "interval", seconds=60, coalesce=True) | |
SCHED.add_job(clean_day_off, "cron", hour='3', coalesce=True) | |
SCHED.start() | |
bot.set_update_listener(listener) # register listener | |
logger.debug("Starting of Allfilesforyou service..") | |
load_all_data() | |
updates = bot.get_updates() | |
if updates: | |
last_update_id = updates[-1] | |
bot.get_updates(offset=last_update_id.update_id) | |
telegram_polling() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
************************************************************************* | |
1. Title : A wrapper about core of Fileis site's function | |
2. Writer : hElLoOnG | |
3. Date : 2018.04.11(Wed) | |
4. ETC : | |
5. History | |
- 2018.04.11, helloong, First Created. | |
************************************************************************* | |
""" | |
import win32com.client | |
from win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PROCESS_ALL_ACCESS | |
import win32con | |
import win32api | |
import win32gui | |
import win32process | |
import win32security | |
from commctrl import LVM_GETITEMTEXT, LVM_GETITEMCOUNT | |
# import requests | |
import datetime | |
# import random | |
import urllib | |
import urllib.parse | |
import re | |
import lxml.etree | |
import lxml.html | |
import shlex | |
import subprocess | |
import struct | |
import ctypes | |
from ctypes import * | |
import os | |
from time import sleep as delay | |
# import sys | |
import sqlite3 | |
import traceback | |
import shutil | |
import psutil | |
import datetime | |
import fileis_logger | |
import queue | |
import threading | |
from multiprocessing import Pool | |
import fileis_ftplib as ftplib | |
# from fileis_utils import * | |
# webctrl = win32com.client.Dispatch("WebControl.WebBBS.1") | |
# sess = requests.Session() | |
# child_hwnds = [] | |
logger = fileis_logger.get_logger("fileis") | |
FILE_QUEUE = queue.Queue() | |
lock = threading.Lock() | |
def get_trace_this_point(type_gb): | |
""" | |
Add, 2018.01.04, SYB, 호출되어진 포인트의 트레이스 정보를 이쁘게 돌려준다. | |
:param type_gb: 0:"FILENAME", 1:"CODELINE", 2:"FUNCNAME", 3:"TEXT", 9:"ALL" | |
:return: 0:"FILENAME", 1:"CODELINE", 2:"FUNCNAME", 3:"TEXT", 9:"ALL" | |
""" | |
if 4 < type_gb < 0: | |
return u"" | |
try: | |
stack = traceback.extract_stack() | |
if type_gb == 9: | |
return stack[-2] | |
else: | |
return stack[-2][type_gb] | |
except Exception as e: | |
logger.error(e.args) | |
logger.error(u"[get_trace_this_point]실행중 오류가 발생하였습니다.") | |
return u"" | |
def chk_is_login(s): | |
logger.debug(get_trace_this_point(9)) | |
url = u"http://fileis.com/" | |
try: | |
r = s.get(url) | |
if r.status_code != 200: | |
# occur exception to login!! | |
logger.debug(u"login status check error!![code: {}]".format(r.status_code)) | |
return False | |
if u"btn_logout" not in r.text: | |
logger.debug(u"Login check failed!!") | |
return False | |
return True | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
return False | |
def login_to_fileis(s, user_id, user_pw): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
try to sing in to the fileis site. | |
:param s: | |
:param user_id: | |
:param user_pw: | |
:return: | |
""" | |
header_data = { | |
"Accept": "application/json, text/javascript, */*; q=0.01", | |
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", | |
"X-Requested-With": "XMLHttpRequest", | |
"Accept-Language": "ko-KR", | |
"Accept-Encoding": "gzip, deflate", | |
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", | |
"Host": "fileis.com", | |
"Content-Length": "116", | |
"DNT": "1", | |
"Connection": "Keep-Alive", | |
"Pragma": "no-cache", | |
} | |
post_data = { | |
"caller": "main", | |
"location": "main", | |
"nowPage": "%252Findex.php", | |
"nowHost": "fileis.com", | |
"test": "", | |
"m_id": user_id, | |
"m_pwd": user_pw, | |
"sslLogin": "on" | |
} | |
login_url = u"http://fileis.com/member/loginCheck.php" | |
try: | |
r = s.post(login_url, headers=header_data, data=post_data) | |
if r.status_code != 200: | |
# occur exception to login!! | |
logger.debug(u"Login error!![code: {}]".format(r.status_code)) | |
return False | |
return True | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
return False | |
def search_in_fileis(s, keyword, rows=25, except_adult=u"N"): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
for idx, x in enumerate(search_in_fileis(s, u"안녕하세요")): | |
print idx, x[0], x[1] | |
""" | |
quote_keyword = urllib.parse.quote(str(keyword).encode(u"utf-8")) | |
logger.debug(quote_keyword) | |
search_url = u"http://fileis.com/contents/search.php?category1=&s_column=title&sCode=&emCopy=N&s_word=" + quote_keyword + u"&rows=" + str(rows) | |
if except_adult == u"Y": | |
logger.debug(u"성인컨텐츠 제외") | |
search_url += u"&viewList=Y" | |
pattern_of_content = u"viewContentsOpen\('\d+?',\s'(\d+?)',\s.+?title=\"(.+?)\"\sclass" | |
pattern_of_pagenum = u"'\d+?', page_num, '(\d+?)'" | |
logger.debug(search_url) | |
logger.debug(pattern_of_content) | |
r = s.get(search_url) | |
if r.status_code != 200: | |
# exception of error!! | |
logger.debug(u"Error: {}".format(r.status_code)) | |
return [[], u"1", u"1"] | |
html_src = r.text | |
# logger.debug(html_src) | |
if u"단어의 철자가 정확한지 확인해주세요" in html_src: | |
logger.debug(u"Not Found any result!!!") | |
return [[], u"1", u"1"] | |
search_results = re.findall(pattern_of_content, html_src) | |
last_page_num = re.findall(pattern_of_pagenum, html_src) | |
logger.debug(u"search_results: " + str(search_results)) | |
if len(last_page_num) > 0: | |
logger.debug(u"last_page_num: " + str(last_page_num[0])) | |
else: | |
last_page_num = [u"1"] | |
if len(search_results) <= 0: | |
# Not found any result | |
logger.debug(u"Not found any result!") | |
return [[], u"1", u"1"] | |
return [search_results, u"1", last_page_num[0]] | |
def parse_search_in_fileis(s, keyword, page_num=u"1", rows=25, except_adult=u"N"): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
for idx, x in enumerate(search_in_fileis(s, u"안녕하세요")): | |
print idx, x[0], x[1] | |
http://fileis.com/contents/search.php?category1=&category2=&s_word=%ED%83%80%EC%9D%B4%ED%83%80%EB%8B%89&show_type=0&emCopy=N&viewTab=new&viewList=&rows=25&page= | |
""" | |
quote_keyword = urllib.parse.quote(str(keyword).encode(u"utf-8")) | |
logger.debug(quote_keyword) | |
search_url = u"http://fileis.com/contents/search.php?category1=&category2=&s_word=" + quote_keyword + u"&show_type=0&emCopy=N&viewTab=new&viewList=" + str(except_adult) + "&rows=" + str(rows) + u"&page=" + str(page_num) | |
pattern_of_content = u"viewContentsOpen\('\d+?',\s'(\d+?)',\s.+?title=\"(.+?)\"\sclass" | |
pattern_of_pagenum = u"'\d+?', page_num, '(\d+?)'" | |
logger.debug(search_url) | |
logger.debug(pattern_of_content) | |
r = s.get(search_url) | |
if r.status_code != 200: | |
# exception of error!! | |
logger.debug(u"Error: {}".format(r.status_code)) | |
return [[], page_num, page_num] | |
html_src = r.text | |
# logger.debug(html_src) | |
search_results = re.findall(pattern_of_content, html_src) | |
last_page_num = re.findall(pattern_of_pagenum, html_src) | |
logger.debug(u"search_results: " + str(search_results)) | |
if len(last_page_num) > 0: | |
logger.debug(u"last_page_num: " + str(last_page_num[0])) | |
else: | |
last_page_num = [u"1"] | |
if len(search_results) <= 0: | |
# Not found any result | |
logger.debug(u"Not found any result!") | |
return [[], page_num, last_page_num[0]] | |
return [search_results, page_num, last_page_num[0]] | |
def get_files_info(s, file_id): | |
logger.debug(get_trace_this_point(9)) | |
check_url = u"http://fileis.com/contents/view.htm?idx=" + str(file_id) + u"&viewPageNum=" | |
logger.debug(check_url) | |
r = s.get(check_url) | |
if r.status_code != 200: | |
logger.debug(u"Download check Error: {}".format(r.status_code)) | |
return [] | |
# html_src = r.text.encode("utf-8") | |
html_src = r.text | |
# logger.debug(html_src) | |
if u"location.replace('warning.htm?idx=" in html_src: | |
logger.debug(u"[{}]해당 컨텐츠는 삭제된 컨텐츠입니다.".format(str(file_id))) | |
return [[u"[{}]해당 컨텐츠는 삭제된 컨텐츠입니다.".format(str(file_id)), u"", u"", u""], ] | |
parser = lxml.html.fromstring(html_src) | |
name_pattern = u'<div class="ftb_name">(.+?)</div>' | |
file_name = re.findall(name_pattern, html_src) | |
file_size = parser.xpath('//*[@id="filelist"]/table/tr/td[2]') | |
file_size = [x.text.strip() for idx, x in enumerate(file_size) if idx > 0] | |
file_qulity = parser.xpath('//*[@id="filelist"]/table/tr/td[3]') | |
file_qulity = [x.text.strip() for idx, x in enumerate(file_qulity) if idx > 0] | |
file_resolution = parser.xpath('//*[@id="filelist"]/table/tr/td[4]') | |
file_resolution = [x.text.strip() for idx, x in enumerate(file_resolution) if idx > 0] | |
logger.debug(str(file_name)) | |
logger.debug(str(file_size)) | |
logger.debug(str(file_qulity)) | |
logger.debug(str(file_resolution)) | |
if len(file_name) == len(file_size) == len(file_qulity) == len(file_resolution): | |
return list(zip(file_name, file_size, file_qulity, file_resolution)) | |
else: | |
logger.debug(u"Get files info error occur!!") | |
return [] | |
def make_down_history(cid, file_id, order_id, user_name, user_mobile, channel, ip_adrs, html_src): | |
logger.debug(get_trace_this_point(9)) | |
parser = lxml.html.fromstring(html_src) | |
rgst_date = datetime.datetime.now().strftime("%Y%m%d") | |
chat_id = cid | |
file_id = file_id | |
order_id = order_id | |
user_name = user_name | |
mobile_phone = user_mobile | |
title_name = parser.xpath(u'//*[@id="view_tot"]/div[2]/div[1]/div/div[2]/div[1]/li[1]/text()') | |
if len(title_name) <= 0: | |
title_name = parser.xpath(u'//*[@id="view_tot"]/div[2]/div[1]/div/div[2]/div[1]/li[2]/text()') | |
if len(title_name) > 0: | |
title_name = str(title_name[0]).replace(u"\r\n", u"").strip() | |
logger.debug(title_name) | |
file_name = re.findall(u'<div class="ftb_name">(.+?)</div>', html_src) | |
logger.debug(file_name) | |
file_size = parser.xpath(u'//*[@id="filelist"]/table/tr/td[2]') | |
logger.debug(file_size) | |
file_size = [x.text.strip() for idx, x in enumerate(file_size) if idx > 0] | |
logger.debug(file_size) | |
down_yn = u"N" | |
noti_yn = u"N" | |
err_cnt = 0 | |
up_dttm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
cr_dttm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
rows = () | |
file_infos = list(zip(file_name, file_size)) | |
for f_n, f_s in file_infos: | |
list_row = [rgst_date, chat_id, file_id, f_n, order_id, user_name, mobile_phone, title_name, f_s, down_yn, | |
noti_yn, err_cnt, up_dttm, cr_dttm, channel, ip_adrs] | |
rows += (tuple(list_row), ) | |
logger.debug(rows) | |
sql = u"INSERT INTO TM_FILE_DOWN (rgst_date, chat_id, file_id, file_name, order_id, user_name, mobile_phone, title_name, file_size, down_yn, noti_yn, err_cnt, up_dttm, cr_dttm, channel, ip_adrs) " \ | |
u"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" | |
conn = sqlite3.connect(u"fileis.db") | |
with conn: | |
conn.executemany(sql, rows) | |
return rows | |
def web_download(s, wc, file_id, user_id=u"starcraft4", cid=u"webdown", user_name=u"webdown", user_mobile=u"0100001234", channel=u"web", ip_adrs=u"127.0.0.1"): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
http://fileis.com/contents/view.htm?idx=6865597&viewPageNum= | |
""" | |
check_url = u"http://fileis.com/contents/view.htm?idx=" + str(file_id) + u"&viewPageNum=" | |
redown_pattern = u".do_redown\('(\d+?)',\s'(.+?)'\)" # order_id, user_id | |
fastdown_pattern = u".do_down_confirm\('(\d+?)',\s'(.+?)'," # file_id, user_id | |
r = s.get(check_url) | |
if r.status_code != 200: | |
logger.debug(u"Download check Error: {}".format(r.status_code)) | |
return list(["E"]) | |
html_src = r.text | |
# logger.debug(str(html_src)) | |
if u"location.replace('warning.htm?idx=" in html_src: | |
logger.debug(u"해당 컨텐츠는 삭제된 컨텐츠 입니다.") | |
return list(["E"]) | |
search_results = re.findall(redown_pattern, html_src) | |
logger.debug(u"redown search_results:" + str(search_results)) | |
if len(search_results) > 0: | |
# redown load | |
logger.debug(u"Redown target!!") | |
# return [u"R", search_results[0][0], search_results[0][1]] | |
order_id = re_download(s, wc, user_id, search_results[0][0]) | |
if int(order_id) > 0: | |
down_files_info = make_down_history(cid, file_id, order_id, user_name, user_mobile, channel, ip_adrs, html_src) | |
return list(["R", down_files_info]) | |
else: | |
return list(["E"]) | |
search_results = re.findall(fastdown_pattern, html_src) | |
logger.debug(u"fastdown search_results:" + str(search_results)) | |
if len(search_results) > 0: | |
# fastdown load | |
logger.debug(u"New fastdown target!!") | |
# return [u"F", search_results[0][0], search_results[0][1]] | |
order_id = fast_download(s, wc, user_id, file_id) | |
if int(order_id) > 0: | |
down_files_info = make_down_history(cid, file_id, order_id, user_name, user_mobile, channel, ip_adrs, html_src) | |
return list(["F", down_files_info]) | |
else: | |
return list(["E"]) | |
# if reach process that is an error!! | |
return list(["E"]) | |
def get_download(s, wc, user_id, file_id, cid, user_name, user_mobile, channel=u"telegram", ip_adrs=u"127.0.0.1"): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
http://fileis.com/contents/view.htm?idx=6865597&viewPageNum= | |
""" | |
check_url = u"http://fileis.com/contents/view.htm?idx=" + str(file_id) + u"&viewPageNum=" | |
redown_pattern = u".do_redown\('(\d+?)',\s'(.+?)'\)" # order_id, user_id | |
fastdown_pattern = u".do_down_confirm\('(\d+?)',\s'(.+?)'," # file_id, user_id | |
r = s.get(check_url) | |
if r.status_code != 200: | |
logger.debug(u"Download check Error: {}".format(r.status_code)) | |
return u"E" | |
html_src = r.text | |
# logger.debug(str(html_src)) | |
if u"location.replace('warning.htm?idx=" in html_src: | |
logger.debug(u"해당 컨텐츠는 삭제된 컨텐츠 입니다.") | |
return u"E" | |
search_results = re.findall(redown_pattern, html_src) | |
logger.debug(u"redown search_results:" + str(search_results)) | |
if len(search_results) > 0: | |
# redown load | |
logger.debug(u"Redown target!!") | |
# return [u"R", search_results[0][0], search_results[0][1]] | |
order_id = re_download(s, wc, user_id, search_results[0][0]) | |
if int(order_id) > 0: | |
make_down_history(cid, file_id, order_id, user_name, user_mobile, channel, ip_adrs, html_src) | |
if order_id == u"12121212": | |
return u"C" | |
else: | |
return u"R" | |
else: | |
return u"E" | |
search_results = re.findall(fastdown_pattern, html_src) | |
logger.debug(u"fastdown search_results:" + str(search_results)) | |
if len(search_results) > 0: | |
# fastdown load | |
logger.debug(u"New fastdown target!!") | |
# return [u"F", search_results[0][0], search_results[0][1]] | |
order_id = fast_download(s, wc, user_id, file_id) | |
if int(order_id) > 0: | |
make_down_history(cid, file_id, order_id, user_name, user_mobile, channel, ip_adrs, html_src) | |
if order_id == u"12121212": | |
return u"C" | |
else: | |
return u"F" | |
else: | |
return u"E" | |
# if reach process that is an error!! | |
return u"E" | |
def fast_download(s, wc, user_id, file_id): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
http://fileis.com/contents/down_confirm_layer.php?nIdx=6865597&nUser=starcraft4&nMethod=2 | |
http://fileis.com/contents/down_init.php?idx=6865597&emType=&list_view_page= | |
""" | |
# Method=5 포인트, Method=2 정액제 | |
url = u"http://fileis.com/contents/down_confirm_layer.php?nIdx=" + str(file_id) + u"&nUser=" + str(user_id) + u"&nMethod=2" | |
r = s.get(url) | |
if r.status_code != 200: | |
logger.debug(u"Fast download confirm error: {}".format(r.status_code)) | |
return -1 | |
# http://fileis.com/contents/down_init.php?idx=6865597&emType=&list_view_page= | |
# 정액제 | |
""" | |
http://fileis.com/contents/down_init.php?idx=7738274&emType=&list_view_page= | |
nfile_download("starcraft4", "094cbbbf5fcff95a314d765d04e28fed8dbf6a39442f98047c825689691f9ed0", "7738274", "11369756", "") | |
""" | |
url = u"http://fileis.com/contents/down_init.php?idx=" + str(file_id) + u"&emType=&list_view_page=" | |
logger.debug(u"fast_download url: " + url) | |
r = s.get(url) | |
if r.status_code != 200: | |
logger.debug(u"Fast download init error: {}".format(r.status_code)) | |
return -1 | |
html_src = r.text | |
# logger.debug(str(html_src)) | |
if u"이미 다운로드 받으신 컨텐츠 입니다." in html_src: | |
logger.error(u"This contents is already downloaded. So recall download action!!") | |
if get_download(s, user_id, file_id) == u"E": | |
logger.error(u"Download failed!!") | |
return -1 | |
else: | |
logger.debug(u"Download succeed!!") | |
return 0 | |
search_results = re.findall(u'nfile_download\("(.+?)",\s?"(.+?)",\s?"(\d+?)",\s?"(\d+?)",\s?"(.*?)"\)', html_src) | |
logger.debug(u"search_results: " + str(search_results)) | |
if len(search_results) != 1 or len(search_results[0]) != 5: | |
# fast download error!! | |
logger.debug(u"Not found purchase pattern during fast downloading!!") | |
return -1 | |
user_id = search_results[0][0] | |
user_pw = search_results[0][1] | |
file_id = search_results[0][2] | |
purchase_id = search_results[0][3] | |
ftp_type = search_results[0][4] | |
chk_file_exists = get_file_exists(file_id) | |
logger.debug(u"chk_file_exists: " + str(chk_file_exists)) | |
if len(chk_file_exists) > 0: | |
t = threading.Thread(target=thread_copy).start() | |
for chat_id, file_name, order_id in chk_file_exists: | |
FILE_QUEUE.put([u"D:\\Download\\FileIs\\comp\\" + chat_id + u"\\" + file_name, | |
u"D:\\Download\\FileIs\\"]) | |
logger.debug(str([u"D:\\Download\\FileIs\\comp\\" + chat_id + u"\\" + file_name, | |
u"D:\\Download\\FileIs\\"])) | |
FILE_QUEUE.join() | |
purchase_id = u"12121212" | |
else: | |
logger.debug(u"wc.Download: " + str(search_results)) | |
wc.DownLoad(user_id, user_pw, 0, file_id, purchase_id, ftp_type, 1) | |
# send_msg_to_fdl(file_id, purchase_id, ftp_type) | |
return purchase_id | |
def re_download(s, wc, user_id, order_id): | |
logger.debug(get_trace_this_point(9)) | |
url = u"http://fileis.com/contents/redown.php?idx=" + str(order_id) | |
logger.debug(u"re_download url: " + url) | |
r = s.get(url) | |
if r.status_code != 200: | |
# redownload error!! | |
logger.debug(u"Redownload error!!") | |
return -1 | |
html_src = r.text | |
# logger.debug(str(html_src)) | |
search_results = re.findall(u'nfile_download\("(.+?)",\s?"(.+?)",\s?"(\d+?)",\s?"(\d+?)",\s?"(.*?)"\)', html_src) | |
logger.debug(u"search_results: " + str(search_results)) | |
if len(search_results) != 1 or len(search_results[0]) != 5: | |
# fast download error!! | |
logger.debug(u"Not Found purchase pattern in redownloading") | |
return -1 | |
user_id = search_results[0][0] | |
user_pw = search_results[0][1] | |
file_id = search_results[0][2] | |
purchase_id = search_results[0][3] | |
ftp_type = search_results[0][4] | |
chk_file_exists = get_file_exists(file_id) | |
logger.debug(u"chk_file_exists: " + str(chk_file_exists)) | |
if len(chk_file_exists) > 0: | |
t = threading.Thread(target=thread_copy).start() | |
for chat_id, file_name, order_id in chk_file_exists: | |
FILE_QUEUE.put([u"D:\\Download\\FileIs\\comp\\" + chat_id + u"\\" + file_name, | |
u"D:\\Download\\FileIs\\"]) | |
logger.debug(str([u"D:\\Download\\FileIs\\comp\\" + chat_id + u"\\" + file_name, | |
u"D:\\Download\\FileIs\\"])) | |
FILE_QUEUE.join() | |
purchase_id = u"12121212" | |
else: | |
logger.debug(u"wc.Download: " + str(search_results)) | |
wc.DownLoad(user_id, user_pw, 0, file_id, purchase_id, ftp_type, 1) | |
# send_msg_to_fdl(file_id, purchase_id, ftp_type) | |
return purchase_id | |
def readListViewItems(hwnd, column_index=0): | |
logger.debug(get_trace_this_point(9)) | |
GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId | |
VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx | |
VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx | |
OpenProcess = ctypes.windll.kernel32.OpenProcess | |
WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory | |
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory | |
memcpy = ctypes.cdll.msvcrt.memcpy | |
# Allocate virtual memory inside target process | |
pid = ctypes.create_string_buffer(4) | |
p_pid = ctypes.addressof(pid) | |
GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd | |
hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack("i", pid)[0]) | |
pLVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) | |
pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) | |
# Prepare an LVITEM record and write it to target process memory | |
lvitem_str = struct.pack('iiiiiiiii', *[0, 0, column_index, 0, 0, pBuffer, 4096, 0, 0]) | |
lvitem_buffer = ctypes.create_string_buffer(lvitem_str) | |
copied = ctypes.create_string_buffer(4) | |
p_copied = ctypes.addressof(copied) | |
WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied) | |
# iterate items in the SysListView32 control | |
num_items = win32gui.SendMessage(hwnd, LVM_GETITEMCOUNT) | |
item_texts = [] | |
for item_index in range(num_items): | |
win32gui.SendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI) | |
target_buff = ctypes.create_string_buffer(4096) | |
ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied) | |
item_texts.append(target_buff.value) | |
VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE) | |
VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE) | |
win32api.CloseHandle(hProcHnd) | |
return item_texts | |
def get_nt_exe(hwnd): | |
logger.debug(get_trace_this_point(9)) | |
"""Finds the name of the executable that the given window handle belongs to.""" | |
# Request privileges to enable "debug process", so we can later use PROCESS_VM_READ, retardedly required to GetModuleFileNameEx() | |
priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY | |
hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess(), priv_flags) | |
# enable "debug process" | |
privilege_id = win32security.LookupPrivilegeValue (None, win32security.SE_DEBUG_NAME) | |
old_privs = win32security.AdjustTokenPrivileges (hToken, 0, [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)]) | |
# Open the process, and query it's filename | |
processid = win32process.GetWindowThreadProcessId(hwnd) | |
pshandle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, processid[1]) | |
exename = win32process.GetModuleFileNameEx(pshandle, 0) | |
# clean up | |
win32api.CloseHandle(pshandle) | |
win32api.CloseHandle(hToken) | |
return exename | |
def get_all_process_info(hwnd, extra): | |
logger.debug(get_trace_this_point(9)) | |
win_info = extra | |
if win32gui.IsWindowVisible(hwnd): | |
win_info[str(hwnd)] = [ | |
hwnd, | |
win32gui.GetWindowText(hwnd), | |
win32gui.GetClassName(hwnd), | |
win32gui.GetWindowRect(hwnd), | |
win32process.GetWindowThreadProcessId(hwnd), | |
get_nt_exe(hwnd) | |
] | |
def get_win_rect_by_pname(pname): | |
logger.debug(get_trace_this_point(9)) | |
windows_info = {} | |
ret_lists = [] | |
win32gui.EnumWindows(get_all_process_info, (windows_info)) | |
for x in windows_info: | |
# logger.debug("{}: {}".format(x, windows_info[x])) | |
if windows_info[x][1] == pname: | |
ret_lists.append(windows_info[x][3]) | |
return ret_lists | |
def get_window_info(hwnd, lparam): | |
# logger.debug(get_trace_this_point(9)) | |
if win32gui.IsWindowVisible(hwnd): | |
child_hwnds.append([ | |
hwnd, | |
win32gui.GetWindowText(hwnd), | |
win32gui.GetClassName(hwnd), | |
win32gui.GetWindowRect(hwnd) | |
]) | |
def click_rm_comp_lists_btn(classname): | |
try: | |
retval = get_child_win_info_by_class(classname) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"[click_rm_comp_lists_btn]자식 윈도우 정보를 가져오는데 오류가 발생하였습니다.") | |
return -1 | |
if len(retval) > 10: | |
hwnd = retval[9] | |
logger.debug(u"완료목록삭제: " + str(hwnd)) | |
win32gui.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, None, None) | |
delay(0.2) | |
win32gui.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, None) | |
delay(0.2) | |
return 0 | |
def get_child_win_info_by_class(classname): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
list_hwnd = get_child_win_info_by_class("SysListView32") | |
if len(list_hwnd) != 1: | |
logger.debug(u"Unknow error occur!!") | |
return -1 | |
""" | |
global child_hwnds | |
ret_lists = [] | |
try: | |
fileis_hwnd = win32gui.FindWindow("Fileis_class_down", None) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"01. 자식 윈도우 정보를 가져오는데 오류가 발생하였습니다.") | |
return [] | |
if fileis_hwnd <= 0: | |
logger.debug(u"Not found fileis downloader window") | |
return [] | |
child_hwnds = [] | |
try: | |
win32gui.EnumChildWindows(fileis_hwnd, get_window_info, None) | |
# logger.debug(u"child_hwnds: " + str(child_hwnds)) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"02. 자식 윈도우 정보를 가져오는데 오류가 발생하였습니다.") | |
return [] | |
for x in child_hwnds: | |
# logger.debug("{}".format(str(x))) | |
if x[2] == classname: | |
ret_lists.append(x[0]) | |
logger.debug("get_child_win_info_by_class.ret_lists: {}".format(str(ret_lists))) | |
return ret_lists | |
def get_fdl_status(): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
for idx, x in enumerate(get_fdl_status()): | |
print idx, x[0], x[1], x[2] | |
""" | |
fileis_hwnd = win32gui.FindWindow("Fileis_class_down", None) | |
win32gui.ShowWindow(fileis_hwnd, win32con.SW_SHOW) | |
try: | |
win32gui.SetForegroundWindow(fileis_hwnd) | |
except Exception as e: | |
logger.error(e.args) | |
logger.error(u"SetForegroundWindow 오류가 발생하였습니다.") | |
pass | |
list_hwnd = get_child_win_info_by_class("SysListView32") | |
if list_hwnd == -1 or len(list_hwnd) <= 0: | |
logger.debug(u"Unknow error occur!!") | |
return [] | |
try: | |
file_lists = readListViewItems(list_hwnd[0], 0) | |
size_lists = readListViewItems(list_hwnd[0], 1) | |
status_lists = readListViewItems(list_hwnd[0], 2) | |
logger.debug("file_lists: " + str(file_lists)) | |
logger.debug("size_lists: " + str(size_lists)) | |
logger.debug("status_lists: " + str(status_lists)) | |
return list(zip(file_lists, size_lists, status_lists)) | |
except IndexError as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"[1]서버상태를 가져오는데 오류가 발생하였습니다.") | |
return [] | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"[2]서버상태를 가져오는데 오류가 발생하였습니다.") | |
return [] | |
def run_directly_fdl(user_id, hashpw, param1=u"1"): | |
logger.debug(get_trace_this_point(9)) | |
path = u"FileisDown.exe " + user_id + " " + hashpw + " " + param1 | |
os.chdir(u"C:\\Program Files (x86)\\Fileis") | |
pid = subprocess.Popen(path, creationflags=0x00000008).pid | |
os.chdir(u"D:\\python_src\\FileIs") | |
return pid | |
def send_msg_to_fdl(file_id, order_id, ftp): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
0#<8641664#<2985849#<R | |
""" | |
fileis_hwnd = win32gui.FindWindow("Fileis_class_down", None) | |
if fileis_hwnd <= 0: | |
logger.debug("Not Found Fileis Downloader!!") | |
return -1 | |
if len(str(file_id).strip()) <= 0 or len(str(order_id).strip()) <= 0: | |
logger.debug("File id and order id should be inputted!!") | |
return -1 | |
class CDS(Structure): | |
_fields_ = [ | |
("dwData", c_void_p), | |
("cbData", c_ulong), | |
("lpData", c_char_p) | |
] | |
msg = u"0#" + str(file_id) + u"#<" + str(order_id) + u"#<" + str(ftp) | |
print(msg) | |
print(type(msg)) | |
msg = bytes(msg, "ms949") | |
print(msg) | |
print(type(msg)) | |
msg_buf = create_string_buffer(msg) | |
print(msg_buf) | |
msg_adrs = CDS(0, len(msg_buf), msg_buf.raw) | |
print(msg_adrs) | |
win32api.SendMessage(fileis_hwnd, win32con.WM_COPYDATA, 0, addressof(msg_adrs)) | |
return 0 | |
def upload_to_ftp(files): | |
logger.debug(get_trace_this_point(9)) | |
""" | |
pool = Pool(10) # submit 10 at once | |
pool.map(upload,infiles) | |
""" | |
ftp = ftplib.FTP() | |
logger.debug(ftp.connect("helloong.ipdisk.co.kr", 1212)) | |
logger.debug(ftp.login("upload", "upload1234!")) | |
logger.debug(ftp.cwd("/HDD1/Upload")) | |
logger.debug(ftp.voidcmd("TYPE I")) | |
file_path = os.path.split(files)[0] | |
file_name = os.path.split(files)[1] | |
remote_file_size = 0 | |
try: | |
remote_file_size = ftp.size(file_name) | |
except Exception as e: | |
logger.debug("Not exists file in the ftp server!!") | |
remote_file_size = 0 | |
local_file_size = os.path.getsize(file_name) | |
logger.debug("{}".format(remote_file_size)) | |
logger.debug("{}".format(local_file_size)) | |
if remote_file_size == local_file_size: | |
logger.debug("File already exists in the ftp server!!") | |
return 100 | |
with open(files, "rb") as f: | |
ftp.storbinary("STOR {}".format(file_name), f) | |
ftp.quit() | |
return 0 | |
def move_comp_file(src_dir, dst_dir, file_name): | |
""" | |
Add, 2018.04.25, helloong, 소스 경로에서 파일을 찾아 목적지폴더로 이쁘게 복사해준다. | |
fileis.move_comp_file(u"D:\\Download\\FileIs", u"D:\\Download\\FileIs\\comp\\287456840", u"대국민 토크쇼 안녕하세요.E362.180423.720p-NEXT.mp4") | |
:param src_dir: | |
:param dst_dir: | |
:param file_name: | |
:return: | |
""" | |
try: | |
if not os.path.exists(dst_dir): | |
logger.debug(u"디렉토리 생성: " + str(dst_dir)) | |
os.makedirs(dst_dir) | |
src_file = os.path.join(src_dir, file_name) | |
dst_file = os.path.join(dst_dir, file_name) | |
logger.debug(u"src_file: " + str(src_file)) | |
logger.debug(u"dst_file: " + str(dst_file)) | |
if os.path.exists(dst_file): | |
logger.debug(u"기파일삭제: " + str(dst_file)) | |
os.remove(dst_file) | |
logger.debug(u"파일복사[대상파일/대상경로]: {}/{}".format(str(src_file), str(dst_dir))) | |
shutil.move(src_file, dst_dir) | |
return u"\\".join([dst_dir, file_name]) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"파일복사에 실패하였습니다.") | |
return u"" | |
def get_down_n_noti_file(path=u"D:\\Download\\FileIs", except_files=[u"index.html", u"50x.html"]): | |
file_lists = [] | |
for dirname, dirnames, filenames in os.walk(path): | |
if u"D:\\Download\\FileIs\\comp" in dirname: | |
continue | |
if u"D:\\Download\\FileIs\\web" in dirname: | |
continue | |
for filename in filenames: | |
if filename in except_files: | |
continue | |
file_lists.append(os.path.join(dirname, filename)) | |
return file_lists | |
def get_downfile_list(path=u"D:\\Download\\FileIs\\comp", except_files=[u"index.html", u"50x.html"]): | |
file_lists = [] | |
for dirname, dirnames, filenames in os.walk(path): | |
for filename in filenames: | |
if filename in except_files: | |
continue | |
file_lists.append(os.path.join(dirname, filename)) | |
return file_lists | |
def get_file_created_time(file_name): | |
return datetime.datetime.fromtimestamp(os.path.getctime(file_name)).strftime(u"%Y%m%d") | |
def get_file_modified_time(file_name): | |
return datetime.datetime.fromtimestamp(os.path.getmtime(file_name)).strftime(u"%Y%m%d") | |
def get_date_add(format_str=u"%Y%m%d", addday=0): | |
""" | |
Add, 2017.11.22, SYB, 오늘을 기준으로 주어진 addday 만큼의 전, 후 일자를 이쁘게 돌려준다. | |
:param format_str: | |
:param addday: | |
:return: | |
""" | |
return (datetime.date.today() + datetime.timedelta(days=addday)).strftime(format_str) | |
def clean_all_system(path=u"D:\\Download\\FileIs", fdl_pid=None): | |
logger.debug(get_trace_this_point(9)) | |
# Add, 2018.05.12, hElLoOnG, Remove empty directory.[ADDING HERE] | |
logger.debug(u"Remove empty directory.") | |
for dirname, dirnames, filenames in os.walk(path): | |
if u"D:\\Download\\FileIs\\web" in dirname: | |
continue | |
if dirnames == [] and filenames == []: | |
try: | |
os.rmdir(dirname) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"[{}]디렉토리 정리에 실패 하였습니다.".format(dirname)) | |
pass | |
# Add, 2018.05.12, hElLoOnG, Remove files after 5 days its created | |
logger.debug(u"Remove files after 5 days its created") | |
if str(dirname).startswith(u"D:\\Download\\FileIs\\comp") or \ | |
str(dirname).startswith(u"D:\\Download\\FileIs\\web"): | |
for filename in filenames: | |
f_cr_time = get_file_modified_time(os.path.join(dirname, filename)) | |
base_date = get_date_add(u"%Y%m%d", -5) | |
cur_filename = os.path.join(dirname, filename) | |
if f_cr_time < base_date: | |
logger.debug(u"{} / {}".format(f_cr_time, cur_filename)) | |
try: | |
os.remove(cur_filename) | |
except Exception as e: | |
logger.error(get_trace_this_point(0)) | |
logger.error(get_trace_this_point(1)) | |
logger.error(get_trace_this_point(2)) | |
logger.error(e.args) | |
logger.error(u"[{} / {}] 5일 이상 파일 정리 실패!!".format(f_cr_time, cur_filename)) | |
pass | |
# Add, 2018.05.12, hElLoOnG, Kill the fileis download luancher.[ADDING HERE] | |
# logger.debug(u"Kill the fileis download luancher.") | |
# if not fdl_pid: | |
# try: | |
# proc = psutil.Process(fdl_pid) | |
# proc.terminate() | |
# except Exception as e: | |
# logger.error(get_trace_this_point(0)) | |
# logger.error(get_trace_this_point(1)) | |
# logger.error(get_trace_this_point(2)) | |
# logger.error(e.args) | |
# logger.error(u"다운로드 프로세스 재실행에 실패 하였습니다.") | |
# pass | |
return 0 | |
def thread_copy(): | |
while True: | |
file_from, file_to = FILE_QUEUE.get() | |
shutil.copy(file_from, file_to) | |
FILE_QUEUE.task_done() | |
with lock: | |
logger.debug(u"File Copyed!!") | |
def get_file_exists(file_id): | |
""" | |
:param file_id: | |
:return: | |
""" | |
conn = sqlite3.connect(u"fileis.db") | |
with conn: | |
cur = conn.cursor() | |
sql = u""" | |
select chat_id, file_name, order_id | |
from TM_FILE_DOWN | |
where rgst_date >= strftime("%Y%m%d", 'now', '-4 days','localtime') | |
and file_id = :file_id | |
and chat_id = (select max(S1.chat_id) | |
from TM_FILE_DOWN S1 | |
where S1.rgst_date >= strftime("%Y%m%d", 'now', '-4 days','localtime') | |
and S1.file_id = :file_id | |
and S1.down_yn = 'Y') | |
and down_yn = 'Y' | |
group by chat_id, file_name; | |
""" | |
where = {u"file_id": file_id} | |
cur.execute(sql, where) | |
rows = cur.fetchall() | |
logger.debug(rows) | |
if len(rows) <= 0: | |
logger.debug(u"동일 파일 다운로드 기록 없음!!") | |
return () | |
avail_file = u"D:\\Download\\FileIs\\comp\\" + str(rows[0][0]) + u"\\" + str(rows[0][1]) | |
if not os.path.isfile(avail_file): | |
logger.debug(u"{}위치에 해당 파일이 없습니다.!!".format(avail_file)) | |
return () | |
return rows | |
if __name__ == "__main__": | |
# upload_to_ftp("D:\\python_src\\FileIs_Diary\\filedown.pcapng") | |
# file_lists = [] | |
# for dirname, dirnames, filenames in os.walk('D:\\Download\\FileIs'): | |
# # print path to all subdirectories first. | |
# # for subdirname in dirnames: | |
# # print(os.path.join(dirname, subdirname)) | |
# | |
# # print path to all filenames. | |
# for filename in filenames: | |
# file_lists.append(os.path.join(dirname, filename)) | |
# | |
# # Advanced usage: | |
# # editing the 'dirnames' list will stop os.walk() from recursing into there. | |
# if '.git' in dirnames: | |
# # don't go into any .git directories. | |
# dirnames.remove('.git') | |
# | |
# for x in file_lists: | |
# print(os.path.split(x)[0].replace(u"D:\\Download\\FileIs", u"http://35.194.151.139:8282").replace(u"\\", u"/") + u"/" + os.path.split(x)[1]) | |
# | |
# | |
# print(get_downfile_list()) | |
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
************************************************************************* | |
1. Title : The method to share of Fileis(Webhard) to other people | |
2. Writer : hElLoOnG | |
3. Date : 2018.04.11(Wed) | |
4. ETC : | |
5. History | |
- 2018.05.04, helloong, First Created. | |
************************************************************************* | |
""" | |
from flask import Flask, request, jsonify, render_template, Response, redirect | |
import win32gui | |
import win32com | |
import fileis | |
import requests | |
import urllib | |
import sqlite3 | |
import pickle | |
import os | |
import fileis_logger | |
from fileis import get_trace_this_point | |
import sys | |
BUILD_NUM = u"201805180001" | |
MASTER_USER = [] | |
LOCAL_USER = [] | |
ADMIN_USER = {} # {12341234: {user_type: "S"}} # S: 슈퍼유저, N: 일반유저 | |
PENDING_USER_INFO = {} # {'12341234': {'user_name': 'SHIM MAL DDONG', 'mobile_phone': '+82100001234'}} | |
USER_INFO = {} # {'12341234': {'user_name': 'SHIM MAL DDONG', 'mobile_phone': '+82100001234'}} | |
USER_ID = u"" | |
USER_PW = u"" | |
HASH_PW = u"" | |
SESSION = requests.Session() | |
FILEISDCTL = win32com.client.Dispatch("WebControl.WebBBS.1") | |
app = Flask(__name__) | |
def get_pickle_load(file_name): | |
logger.debug(get_trace_this_point(9)) | |
logger.debug(file_name) | |
if os.path.isfile(file_name): | |
with open(file_name, "rb") as f: | |
return_value = pickle.load(f, encoding="utf-8") | |
return return_value | |
else: | |
with open(file_name, "wb") as f: | |
pickle.dump({}, f) | |
return {} | |
def load_all_data(): | |
logger.debug(get_trace_this_point(9)) | |
global ADMIN_USER | |
global USER_INFO | |
global USER_STEP | |
global PENDING_USER_INFO | |
ADMIN_USER = get_pickle_load(u"f_admin_info.dat") | |
USER_INFO = get_pickle_load(u"f_user_info.dat") | |
USER_STEP = get_pickle_load(u"f_user_step.dat") | |
PENDING_USER_INFO = get_pickle_load(u"f_pending_user.dat") | |
if len(USER_INFO): | |
# logger.debug(u"Admin list.") | |
# logger.debug(str(ADMIN_USER)) | |
# logger.debug(u"User list.") | |
# logger.debug(str(USER_INFO)) | |
# logger.debug(u"User step.") | |
# logger.debug(str(USER_STEP)) | |
# logger.debug(u"Pending user.") | |
# logger.debug(str(PENDING_USER_INFO)) | |
logger.debug(u"Env load complete.") | |
else: | |
logger.debug(u"No one is in this room at this time.") | |
# logger.debug(u"Admin list.") | |
# logger.debug(str(ADMIN_USER)) | |
# logger.debug(u"User list.") | |
# logger.debug(str(USER_INFO)) | |
# logger.debug(u"User step.") | |
# logger.debug(str(USER_STEP)) | |
# logger.debug(u"Pending user.") | |
# logger.debug(str(PENDING_USER_INFO)) | |
if len(USER_INFO) > 0: | |
for cid in MASTER_USER: | |
pass | |
# bot.send_message(cid, u"[알림]서비스가 재개 되었습니다.") | |
@app.route(u"/ping") | |
def ping(): | |
retmsg = u"Y" | |
return retmsg | |
@app.route(u"/buildnum") | |
def get_buildnum(): | |
global BUILD_NUM | |
retmsg = BUILD_NUM | |
return retmsg | |
@app.route(u"/contents/view.htm") | |
def contents_view(): | |
logger.debug(get_trace_this_point(9)) | |
global SESSION | |
idx = request.args.get(u"idx", default=u"", type=str) | |
page_num = request.args.get(u"viewPageNum", default=u"", type=str) | |
logger.debug(u"idx: " + idx) | |
logger.debug(u"page_num: " + page_num) | |
search_url = u"http://fileis.com/contents/view.htm?idx=" + idx + u"&viewPageNum=" + page_num | |
logger.debug(u"search_url: " + search_url) | |
r = SESSION.get(search_url) | |
if r.status_code != 200: | |
# exception of error!! | |
logger.debug(u"Error: {}".format(r.status_code)) | |
return u"페이지를 찾을 수 없습니다." | |
html_src = r.text | |
if u"단어의 철자가 정확한지 확인해주세요" in html_src: | |
logger.debug(u"Not Found any result!!!") | |
return u"페이지를 찾을 수 없습니다." | |
# logger.debug(html_src) | |
html_src = html_src.replace(u"\"/", u"\"http://fileis.com/") | |
html_src = html_src.replace(u"'/", u"'http://fileis.com/") | |
return html_src | |
@app.route(u"/serfe_url") | |
def serfe_url(): | |
logger.debug(get_trace_this_point(9)) | |
global SESSION | |
url = request.args.get(u"url", default=u"", type=str) | |
idx = request.args.get(u"idx", default=u"", type=str) | |
page_num = request.args.get(u"viewPageNum", default=u"", type=str) | |
logger.debug(u"url: " + url) | |
logger.debug(u"idx: " + idx) | |
logger.debug(u"page_num: " + page_num) | |
if url == u"": | |
search_url = u"http://fileis.com/contents/view.htm?idx=" + idx + u"&viewPageNum=" + page_num | |
else: | |
if str(url).startswith(u"http://"): | |
search_url = url | |
else: | |
search_url = u"http://fileis.com" + str(url) | |
# logger.debug(u"search_url: " + search_url) | |
r = SESSION.get(search_url) | |
if r.status_code != 200: | |
# exception of error!! | |
logger.debug(u"Error: {}".format(r.status_code)) | |
return u"페이지를 찾을 수 없습니다." | |
html_src = r.text | |
# logger.debug(html_src) | |
if u"단어의 철자가 정확한지 확인해주세요" in html_src: | |
logger.debug(u"Not Found any result!!!") | |
return u"페이지를 찾을 수 없습니다." | |
# logger.debug(html_src) | |
html_src = html_src.replace(u"\"/", u"\"http://fileis.com/") | |
html_src = html_src.replace(u"'/", u"'http://fileis.com/") | |
return html_src | |
@app.route(u"/search_signedin/<file_id>/<chat_id>/<mobile_phone>/<user_name>") | |
def search_signedin(file_id, chat_id, mobile_phone, user_name): | |
logger.debug(get_trace_this_point(9)) | |
global SESSION | |
search_url = u"http://fileis.com/contents/view.htm?idx=" + str(file_id) + u"&viewPageNum=" | |
r = SESSION.get(search_url) | |
if r.status_code != 200: | |
# exception of error!! | |
logger.debug(u"Error: {}".format(r.status_code)) | |
return u"페이지를 찾을 수 없습니다." | |
html_src = r.text | |
# logger.debug(html_src) | |
if u"단어의 철자가 정확한지 확인해주세요" in html_src: | |
logger.debug(u"Not Found any result!!!") | |
return u"페이지를 찾을 수 없습니다." | |
# logger.debug(html_src) | |
if str(request.remote_addr).startswith(u"192.168.0"): | |
str_down_link = u"http://192.168.0.8:5003/web_login_down/" + file_id + u"/" + chat_id + u"/" + mobile_phone + u"/" + user_name | |
else: | |
str_down_link = u"http://helloong.ipdisk.co.kr:5003/web_login_down/" + file_id + u"/" + chat_id + u"/" + mobile_phone + u"/" + user_name | |
html_src = html_src.replace(u"\"/", u"\"http://fileis.com/") | |
html_src = html_src.replace(u"'/", u"'http://fileis.com/") | |
html_src = html_src.replace(u"찜하기</a>", u"찜하기</a><span id=\"topBtnFake2\" class=\"btn_dv_quickdown\" style=\"cursor:pointer;display:none;\"> 찜하기</span> <a href=\"" + str_down_link + "\" id=\"AllFilesForYou\" class=\"btn_dv_quickdown\">올파일포유다운</a>") | |
return html_src | |
@app.route(u"/waiting") | |
def waiting(): | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> | |
<style> | |
h1{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: center; | |
margin-bottom: 15px; | |
} | |
h2{ | |
font-size: 15px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
h3{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
text-align: center; | |
font-weight: bold; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
table{ | |
width:100%; | |
table-layout: fixed; | |
} | |
.tbl-header{ | |
background-color: rgba(255,255,255,0.3); | |
} | |
.tbl-content{ | |
height:300px; | |
overflow-x:auto; | |
margin-top: 0px; | |
border: 1px solid rgba(255,255,255,0.3); | |
} | |
th{ | |
padding: 20px 15px; | |
text-align: left; | |
font-weight: 500; | |
font-size: 12px; | |
color: #fff; | |
text-transform: uppercase; | |
} | |
td{ | |
padding: 15px; | |
text-align: left; | |
vertical-align:middle; | |
font-weight: 300; | |
font-size: 12px; | |
color: #fff; | |
border-bottom: solid 1px rgba(255,255,255,0.1); | |
} | |
/* demo styles */ | |
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700); | |
body{ | |
background: -webkit-linear-gradient(left, #25c481, #25b7c4); | |
background: linear-gradient(to right, #25c481, #25b7c4); | |
font-family: 'Roboto', sans-serif; | |
} | |
section{ | |
margin: 50px; | |
} | |
/* follow me template */ | |
.made-with-love { | |
margin-top: 40px; | |
padding: 10px; | |
clear: left; | |
text-align: center; | |
font-size: 10px; | |
font-family: arial; | |
color: #fff; | |
} | |
.made-with-love i { | |
font-style: normal; | |
color: #F50057; | |
font-size: 14px; | |
position: relative; | |
top: 2px; | |
} | |
.made-with-love a { | |
color: #fff; | |
text-decoration: none; | |
} | |
.made-with-love a:hover { | |
text-decoration: underline; | |
} | |
/* for custom scrollbar for webkit browser*/ | |
::-webkit-scrollbar { | |
width: 6px; | |
} | |
::-webkit-scrollbar-track { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
::-webkit-scrollbar-thumb { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
</style> | |
</head> | |
<body> | |
<section> | |
<h3>텔레그램 "/내아이디" 명령어로 본인 아이디 확인 후 로그인</h3> | |
</section> | |
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> | |
<script> | |
// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width . | |
$(window).on("load resize ", function() { | |
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width(); | |
$('.tbl-header').css({'padding-right':scrollWidth}); | |
}).resize(); | |
</script> | |
</body> | |
</html> | |
""" | |
return retmsg | |
@app.route(u"/login/<chat_id>") | |
def login(chat_id): | |
logger.debug(u"User trying to sing in from web browser.") | |
if chat_id in USER_INFO: | |
logger.debug(u"Login succeed!!") | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You Login</title> | |
</head> | |
<body> | |
[Y/{}/{}/{}] | |
</body> | |
</html> | |
""".format(chat_id, USER_INFO[chat_id][u"user_name"], USER_INFO[chat_id][u"mobile_phone"]) | |
else: | |
logger.debug(u"Login failed!!") | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You Login</title> | |
</head> | |
<body> | |
N | |
</body> | |
</html> | |
""" | |
return retmsg | |
@app.route(u"/web_down/<file_id>") | |
def web_down(file_id): | |
global SESSION | |
global USER_ID | |
global USER_PW | |
global FILEISDCTL | |
# [rgst_date, chat_id, file_id, f_n, order_id, user_name, mobile_phone, title_name, f_s, down_yn, noti_yn, err_cnt, up_dttm, cr_dttm] | |
retval = fileis.web_download(SESSION, FILEISDCTL, str(file_id), USER_ID, u"webdown", str(request.remote_addr), u"0100001234") | |
if retval[0] in [u"F", u"R"]: | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> | |
<style> | |
h1{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: center; | |
margin-bottom: 15px; | |
} | |
h2{ | |
font-size: 15px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
table{ | |
width:100%; | |
table-layout: fixed; | |
} | |
.tbl-header{ | |
background-color: rgba(255,255,255,0.3); | |
} | |
.tbl-content{ | |
height:300px; | |
overflow-x:auto; | |
margin-top: 0px; | |
border: 1px solid rgba(255,255,255,0.3); | |
} | |
th{ | |
padding: 20px 15px; | |
text-align: left; | |
font-weight: 500; | |
font-size: 12px; | |
color: #fff; | |
text-transform: uppercase; | |
} | |
td{ | |
padding: 15px; | |
text-align: left; | |
vertical-align:middle; | |
font-weight: 300; | |
font-size: 12px; | |
color: #fff; | |
border-bottom: solid 1px rgba(255,255,255,0.1); | |
} | |
/* demo styles */ | |
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700); | |
body{ | |
background: -webkit-linear-gradient(left, #25c481, #25b7c4); | |
background: linear-gradient(to right, #25c481, #25b7c4); | |
font-family: 'Roboto', sans-serif; | |
} | |
section{ | |
margin: 50px; | |
} | |
/* follow me template */ | |
.made-with-love { | |
margin-top: 40px; | |
padding: 10px; | |
clear: left; | |
text-align: center; | |
font-size: 10px; | |
font-family: arial; | |
color: #fff; | |
} | |
.made-with-love i { | |
font-style: normal; | |
color: #F50057; | |
font-size: 14px; | |
position: relative; | |
top: 2px; | |
} | |
.made-with-love a { | |
color: #fff; | |
text-decoration: none; | |
} | |
.made-with-love a:hover { | |
text-decoration: underline; | |
} | |
/* for custom scrollbar for webkit browser*/ | |
::-webkit-scrollbar { | |
width: 6px; | |
} | |
::-webkit-scrollbar-track { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
::-webkit-scrollbar-thumb { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
</style> | |
</head> | |
<body> | |
<section> | |
<h1>올파일포유 다운로드 리스트</h1> | |
<h2>[예약하신 파일은 서버 혼잡 상태에 따라 잠시 뒤 DOWNLINK에서 바로보기 혹은 다운로드가 가능합니다.]</h2> | |
<div class="tbl-header"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<thead> | |
<tr> | |
<th width="20%">파일아이디</th> | |
<th width="30%">파일명</th> | |
<th>공유링크</th> | |
</tr> | |
</thead> | |
</table> | |
</div> | |
<div class="tbl-content"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<tbody> | |
""" | |
for file_info in retval[1]: | |
retmsg += u""" | |
<tr> | |
<td width="20%">{}</td> | |
<td width="30%">{}</td> | |
<td><a href="{}">바로보기</a> <a href="{}" download>다운로드</a></td> | |
</tr> | |
""".format(file_info[2], | |
file_info[3], | |
u"http://helloong.ipdisk.co.kr:5002/web/" + urllib.parse.quote(file_info[3]), | |
u"http://helloong.ipdisk.co.kr:5002/web/" + urllib.parse.quote(file_info[3])) | |
retmsg += u""" | |
</tbody> | |
</table> | |
</div> | |
</section> | |
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> | |
<script> | |
// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width . | |
$(window).on("load resize ", function() { | |
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width(); | |
$('.tbl-header').css({'padding-right':scrollWidth}); | |
}).resize(); | |
</script> | |
</body> | |
</html> | |
""" | |
else: | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> | |
<style> | |
h1{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: center; | |
margin-bottom: 15px; | |
} | |
h2{ | |
font-size: 15px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
h3{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: bold; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
table{ | |
width:100%; | |
table-layout: fixed; | |
} | |
.tbl-header{ | |
background-color: rgba(255,255,255,0.3); | |
} | |
.tbl-content{ | |
height:300px; | |
overflow-x:auto; | |
margin-top: 0px; | |
border: 1px solid rgba(255,255,255,0.3); | |
} | |
th{ | |
padding: 20px 15px; | |
text-align: left; | |
font-weight: 500; | |
font-size: 12px; | |
color: #fff; | |
text-transform: uppercase; | |
} | |
td{ | |
padding: 15px; | |
text-align: left; | |
vertical-align:middle; | |
font-weight: 300; | |
font-size: 12px; | |
color: #fff; | |
border-bottom: solid 1px rgba(255,255,255,0.1); | |
} | |
/* demo styles */ | |
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700); | |
body{ | |
background: -webkit-linear-gradient(left, #25c481, #25b7c4); | |
background: linear-gradient(to right, #25c481, #25b7c4); | |
font-family: 'Roboto', sans-serif; | |
} | |
section{ | |
margin: 50px; | |
} | |
/* follow me template */ | |
.made-with-love { | |
margin-top: 40px; | |
padding: 10px; | |
clear: left; | |
text-align: center; | |
font-size: 10px; | |
font-family: arial; | |
color: #fff; | |
} | |
.made-with-love i { | |
font-style: normal; | |
color: #F50057; | |
font-size: 14px; | |
position: relative; | |
top: 2px; | |
} | |
.made-with-love a { | |
color: #fff; | |
text-decoration: none; | |
} | |
.made-with-love a:hover { | |
text-decoration: underline; | |
} | |
/* for custom scrollbar for webkit browser*/ | |
::-webkit-scrollbar { | |
width: 6px; | |
} | |
::-webkit-scrollbar-track { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
::-webkit-scrollbar-thumb { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
</style> | |
</head> | |
<body> | |
<section> | |
<h1>올파일포유 다운로드 리스트</h1> | |
<h3>파일 다운로드 예약에 실패하였습니다.</h2> | |
<h3>잠시 후 다시 시도 하여주세요</h3> | |
<div class="tbl-header"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<thead> | |
<tr> | |
<th width="20%">파일아이디</th> | |
<th width="30%">파일명</th> | |
<th>공유링크</th> | |
</tr> | |
</thead> | |
</table> | |
</div> | |
<div class="tbl-content"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<tbody> | |
<tr> | |
<td width="20%"></td> | |
<td width="30%"></td> | |
<td><a href="http://www.google.com">바로보기</a> <a href="http://www.google.com" download>다운로드</a></td> | |
</tr> | |
</tbody> | |
</table> | |
</div> | |
</section> | |
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> | |
<script> | |
// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width . | |
$(window).on("load resize ", function() { | |
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width(); | |
$('.tbl-header').css({'padding-right':scrollWidth}); | |
}).resize(); | |
</script> | |
</body> | |
</html> | |
""" | |
return retmsg | |
@app.route(u"/web_login_down/<file_id>/<chat_id>/<mobile_phone>/<user_name>") | |
def web_login_down(file_id, chat_id, mobile_phone, user_name): | |
global SESSION | |
global USER_ID | |
global USER_PW | |
global FILEISDCTL | |
# [rgst_date, chat_id, file_id, f_n, order_id, user_name, mobile_phone, title_name, f_s, down_yn, noti_yn, err_cnt, up_dttm, cr_dttm] | |
retval = fileis.web_download(SESSION, FILEISDCTL, str(file_id), USER_ID, str(chat_id), str(user_name), str(mobile_phone), u"web", str(request.remote_addr)) | |
if retval[0] in [u"F", u"R"]: | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> | |
<style> | |
h1{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: center; | |
margin-bottom: 15px; | |
} | |
h2{ | |
font-size: 15px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
h3{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: bold; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
table{ | |
width:100%; | |
table-layout: fixed; | |
} | |
.tbl-header{ | |
background-color: rgba(255,255,255,0.3); | |
} | |
.tbl-content{ | |
height:300px; | |
overflow-x:auto; | |
margin-top: 0px; | |
border: 1px solid rgba(255,255,255,0.3); | |
} | |
th{ | |
padding: 20px 15px; | |
text-align: left; | |
font-weight: 500; | |
font-size: 12px; | |
color: #fff; | |
text-transform: uppercase; | |
} | |
td{ | |
padding: 15px; | |
text-align: left; | |
vertical-align:middle; | |
font-weight: 300; | |
font-size: 12px; | |
color: #fff; | |
border-bottom: solid 1px rgba(255,255,255,0.1); | |
} | |
/* demo styles */ | |
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700); | |
body{ | |
background: -webkit-linear-gradient(left, #25c481, #25b7c4); | |
background: linear-gradient(to right, #25c481, #25b7c4); | |
font-family: 'Roboto', sans-serif; | |
} | |
section{ | |
margin: 50px; | |
} | |
/* follow me template */ | |
.made-with-love { | |
margin-top: 40px; | |
padding: 10px; | |
clear: left; | |
text-align: center; | |
font-size: 10px; | |
font-family: arial; | |
color: #fff; | |
} | |
.made-with-love i { | |
font-style: normal; | |
color: #F50057; | |
font-size: 14px; | |
position: relative; | |
top: 2px; | |
} | |
.made-with-love a { | |
color: #fff; | |
text-decoration: none; | |
} | |
.made-with-love a:hover { | |
text-decoration: underline; | |
} | |
/* for custom scrollbar for webkit browser*/ | |
::-webkit-scrollbar { | |
width: 6px; | |
} | |
::-webkit-scrollbar-track { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
::-webkit-scrollbar-thumb { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
</style> | |
</head> | |
<body> | |
<section> | |
<h1>올파일포유 다운로드 리스트</h1> | |
<h2>[예약하신 파일은 서버 혼잡 상태에 따라 잠시 뒤 DOWNLINK에서 바로보기 혹은 다운로드가 가능합니다.]</h2> | |
<h3>파일 다운로드가 완료되면 텔레그램 메세지로 알려드립니다.</h3> | |
<div class="tbl-header"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<thead> | |
<tr> | |
<th width="20%">파일아이디</th> | |
<th width="30%">파일명</th> | |
<th>공유링크</th> | |
</tr> | |
</thead> | |
</table> | |
</div> | |
<div class="tbl-content"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<tbody> | |
""" | |
for file_info in retval[1]: | |
retmsg += u""" | |
<tr> | |
<td width="20%">{}</td> | |
<td width="30%">{}</td> | |
<td><a href="{}">바로보기</a> <a href="{}" download>다운로드</a></td> | |
</tr> | |
""".format(file_info[2], | |
file_info[3], | |
u"http://helloong.ipdisk.co.kr:5002/comp/" + str(chat_id) + u"/" + urllib.parse.quote(file_info[3]), | |
u"http://helloong.ipdisk.co.kr:5002/comp/" + str(chat_id) + u"/" + urllib.parse.quote(file_info[3])) | |
retmsg += u""" | |
</tbody> | |
</table> | |
</div> | |
</section> | |
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> | |
<script> | |
// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width . | |
$(window).on("load resize ", function() { | |
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width(); | |
$('.tbl-header').css({'padding-right':scrollWidth}); | |
}).resize(); | |
</script> | |
</body> | |
</html> | |
""" | |
else: | |
retmsg = u""" | |
<!DOCTYPE html> | |
<html lang="ko" > | |
<head> | |
<meta charset="UTF-8"> | |
<title>All Files For You</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> | |
<style> | |
h1{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: center; | |
margin-bottom: 15px; | |
} | |
h2{ | |
font-size: 15px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: 300; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
h3{ | |
font-size: 30px; | |
color: #fff; | |
text-transform: uppercase; | |
font-weight: bold; | |
text-align: left; | |
margin-bottom: 15px; | |
} | |
table{ | |
width:100%; | |
table-layout: fixed; | |
} | |
.tbl-header{ | |
background-color: rgba(255,255,255,0.3); | |
} | |
.tbl-content{ | |
height:300px; | |
overflow-x:auto; | |
margin-top: 0px; | |
border: 1px solid rgba(255,255,255,0.3); | |
} | |
th{ | |
padding: 20px 15px; | |
text-align: left; | |
font-weight: 500; | |
font-size: 12px; | |
color: #fff; | |
text-transform: uppercase; | |
} | |
td{ | |
padding: 15px; | |
text-align: left; | |
vertical-align:middle; | |
font-weight: 300; | |
font-size: 12px; | |
color: #fff; | |
border-bottom: solid 1px rgba(255,255,255,0.1); | |
} | |
/* demo styles */ | |
@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700); | |
body{ | |
background: -webkit-linear-gradient(left, #25c481, #25b7c4); | |
background: linear-gradient(to right, #25c481, #25b7c4); | |
font-family: 'Roboto', sans-serif; | |
} | |
section{ | |
margin: 50px; | |
} | |
/* follow me template */ | |
.made-with-love { | |
margin-top: 40px; | |
padding: 10px; | |
clear: left; | |
text-align: center; | |
font-size: 10px; | |
font-family: arial; | |
color: #fff; | |
} | |
.made-with-love i { | |
font-style: normal; | |
color: #F50057; | |
font-size: 14px; | |
position: relative; | |
top: 2px; | |
} | |
.made-with-love a { | |
color: #fff; | |
text-decoration: none; | |
} | |
.made-with-love a:hover { | |
text-decoration: underline; | |
} | |
/* for custom scrollbar for webkit browser*/ | |
::-webkit-scrollbar { | |
width: 6px; | |
} | |
::-webkit-scrollbar-track { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
::-webkit-scrollbar-thumb { | |
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); | |
} | |
</style> | |
</head> | |
<body> | |
<section> | |
<h1>올파일포유 다운로드 리스트</h1> | |
<h3>파일 다운로드 예약에 실패하였습니다.</h2> | |
<h3>잠시 후 다시 시도 하여주세요</h3> | |
<div class="tbl-header"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<thead> | |
<tr> | |
<th width="20%">파일아이디</th> | |
<th width="30%">파일명</th> | |
<th>공유링크</th> | |
</tr> | |
</thead> | |
</table> | |
</div> | |
<div class="tbl-content"> | |
<table cellpadding="0" cellspacing="0" border="0"> | |
<tbody> | |
<tr> | |
<td width="20%"></td> | |
<td width="30%"></td> | |
<td><a href="http://www.google.com">바로보기</a> <a href="http://www.google.com" download>다운로드</a></td> | |
</tr> | |
</tbody> | |
</table> | |
</div> | |
</section> | |
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> | |
<script> | |
// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width . | |
$(window).on("load resize ", function() { | |
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width(); | |
$('.tbl-header').css({'padding-right':scrollWidth}); | |
}).resize(); | |
</script> | |
</body> | |
</html> | |
""" | |
return retmsg | |
def try_sign_in(): | |
logger.debug(get_trace_this_point(9)) | |
global SESSION | |
global USER_ID | |
global USER_PW | |
# FileIs Login | |
if not fileis.login_to_fileis(SESSION, USER_ID, USER_PW): | |
logger.debug(u"Fileis site sign in failed!") | |
return 1 | |
return 0 | |
if __name__ == u"__main__": | |
logger = fileis_logger.get_logger("fileis_flask") | |
logger.debug(get_trace_this_point(9)) | |
load_all_data() | |
if try_sign_in(): | |
sys.exit(0) | |
app.run(host='0.0.0.0', port=5003, debug=False, threaded=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
************************************************************************* | |
1. Title : | |
2. Writer : hElLoOnG | |
3. Date : | |
4. ETC : | |
5. History | |
- 20XX.XX.XX, helloong, First Created | |
************************************************************************* | |
""" | |
# 도움말에 보여줄 명령어 리스트 | |
import collections | |
main_cmd_list = collections.OrderedDict() | |
# 사용자 도움말 | |
main_cmd_list[u"줄바꿈00"] = u"#" | |
main_cmd_list[u"시작"] = u"사용자 인증 및 서비스 시작" | |
main_cmd_list[u"도움말"] = u"기능 도움말 출력" | |
main_cmd_list[u"검색 [키워드]"] = (u"원하는 파일을 키워드 검색 후 다운로드 예약\n" | |
u"마지막에 성인제외 입력시 성인컨텐츠 검색제외") | |
main_cmd_list[u"파일정보 [파일ID]"] = u"파일 상세정보 조회" | |
main_cmd_list[u"다운예약 [파일ID]"] = u"파일ID 직접 입력하여 다운로드 예약" | |
main_cmd_list[u"다시받기"] = u"이전 내 다운로드 파일중 다시받기 가능 파일 조회" | |
main_cmd_list[u"브라우저"] = u"서비스전용 브라우저 다운로드" | |
main_cmd_list[u"내아이디"] = u"전용브라우저 로그인 고유ID 조회" | |
main_cmd_list[u"서버상태"] = u"서버 다운로드 상태정보 출력" | |
main_cmd_list[u"로그아웃"] = u"로그아웃" | |
main_cmd_list[u"줄바꿈01"] = u"#" | |
# 관리자 도움말 | |
admin_cmd_list = collections.OrderedDict() | |
admin_cmd_list[u"줄바꿈00"] = u"#" | |
admin_cmd_list[u"누구"] = u"현재 참여중인 사용자를 조회합니다." | |
admin_cmd_list[u"관리자등록"] = u"사용자를 관리자로 등록합니다." | |
admin_cmd_list[u"관리자삭제"] = u"사용자의 관리자 권한을 제거합니다." | |
admin_cmd_list[u"인증취소"] = u"사용자의 로그인 인증을 취소합니다." | |
admin_cmd_list[u"줄바꿈01"] = u"#" | |
admin_cmd_list[u"셧다운"] = u"서비스를 중지합니다.[운영자전용]" | |
# admin_cmd_list[u"다운로더실행"] = u"사용자의 관리자 권한을 제거합니다.[운영자전용]" | |
# admin_cmd_list[u"다운로더중지"] = u"사용자의 관리자 권한을 제거합니다.[운영자전용]" | |
admin_cmd_list[u"줄바꿈02"] = u"#" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
************************************************************************* | |
1. Title : Logger of helloong | |
2. Writer : hElLoOnG | |
3. Date : | |
4. ETC : | |
5. History | |
- 20XX.XX.XX, helloong, First Created | |
************************************************************************* | |
""" | |
import logging.handlers | |
MAX_FILE_SIZE = 10 * 1024 * 1024 | |
def get_logger(logger_name): | |
logger = logging.getLogger(logger_name) | |
logger.setLevel(logging.DEBUG) | |
stream_formatter = logging.Formatter('[%(levelname)s] %(asctime)s > %(message)s') | |
file_formatter = logging.Formatter('[%(levelname)-08s|%(processName)-20s|%(funcName)-25s|%(lineno)05s] %(asctime)s ' | |
'> %(message)s') | |
file_handler = logging.handlers.RotatingFileHandler(filename=logger_name + ".log", maxBytes=MAX_FILE_SIZE, | |
backupCount=100, encoding="utf-8") | |
stream_handler = logging.StreamHandler() | |
file_handler.setFormatter(file_formatter) | |
stream_handler.setFormatter(stream_formatter) | |
logger.addHandler(file_handler) | |
logger.addHandler(stream_handler) | |
return logger |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************************************************************** | |
* Title: AllFilesForYou Browser v0.9 | |
* Date: 2018.05.05 | |
* Auther: hElLoOnG | |
* History | |
* Add, 2018.04.23, hElLoOng, First Created | |
* Add, 2018.04.26, hElLoOng, Change version of webborwser control.[IE8 ==> IE11 Not edge mode] | |
* Add, 2018.05.05, hElLoOng, Notify to the telegram using by user's telegram chat id. | |
* Del, 2018.05.08, hElLoOnG, Remove the exection place check logic. All users should have signed in before use this. | |
********************************************************************************************** */ | |
using System; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Windows.Forms; | |
using System.Runtime.InteropServices; | |
using System.Text.RegularExpressions; | |
using Fiddler; | |
using System.Drawing; | |
using System.Diagnostics; | |
using Microsoft.Win32; | |
using System.IO; | |
using System.Text; | |
using System.Threading; | |
namespace WindowsFormsApp1 | |
{ | |
public partial class frm_main : Form | |
{ | |
string sBuildNum = "201805180001"; | |
bool bIsLocal = false; | |
string sChatId = ""; | |
string sUserName = ""; | |
string sMobilePhone = ""; | |
List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>(); | |
struct Struct_INTERNET_PROXY_INFO | |
{ | |
public int dwAccessType; | |
public IntPtr proxy; | |
public IntPtr proxyBypass; | |
}; | |
[DllImport("wininet.dll", SetLastError = true)] | |
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); | |
private void RefreshIESettings(string strProxy) | |
{ | |
const int INTERNET_OPTION_PROXY = 38; | |
const int INTERNET_OPEN_TYPE_PROXY = 3; | |
Struct_INTERNET_PROXY_INFO struct_IPI; | |
struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY; | |
struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy); | |
struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local"); | |
IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI)); | |
Marshal.StructureToPtr(struct_IPI, intptrStruct, true); | |
bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI)); | |
} | |
private Boolean Check_execute_place() | |
{ | |
bool bIsItOkToExecute = false; | |
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); | |
string ClientIP = string.Empty; | |
for (int i = 0; i < host.AddressList.Length; i++) | |
{ | |
if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork) | |
{ | |
ClientIP = host.AddressList[i].ToString(); | |
if (ClientIP.Substring(0, 9).Equals("10.101.10") || | |
ClientIP.Substring(0, 9).Equals("10.101.20") || | |
ClientIP.Substring(0, 11).Equals("129.100.170") || | |
ClientIP.Substring(0, 11).Equals("129.100.180") || | |
ClientIP.Substring(0, 11).Equals("192.168.0.8")) | |
{ | |
bIsItOkToExecute = true; | |
} | |
if (ClientIP.StartsWith("192.168.0.8") || ClientIP.StartsWith("192.168.0.3")) | |
{ | |
txt_Status.Text += "로컬 환경 실행중!!"; | |
bIsLocal = true; | |
} | |
} | |
} | |
if (bIsItOkToExecute) | |
{ | |
return true; | |
} | |
return false; | |
} | |
private delegate void NewWindowDelegate(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed); | |
private void OnNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed) | |
{ | |
Processed = true; | |
wb.Navigate(URL); | |
} | |
private void SetWebBorwserVersion(string appName) | |
{ | |
RegistryKey Regkey = null; | |
try | |
{ | |
if (Environment.Is64BitOperatingSystem) | |
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", true); | |
else | |
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true); | |
if (Regkey == null) | |
{ | |
txt_Status.Text += "\r\n" + "브라우저 에뮬레이션 세팅 실패 - 레지스트리 키를 찾지 못했습니다."; | |
return; | |
} | |
string FindAppkey = Convert.ToString(Regkey.GetValue(appName)); | |
if (FindAppkey == "11000") | |
{ | |
txt_Status.Text += "\r\n" + "브라우져 에뮬레이션 설정이 이미 되어 있습니다."; | |
Regkey.Close(); | |
return; | |
} | |
if (string.IsNullOrEmpty(FindAppkey)) | |
Regkey.SetValue(appName, unchecked((int)0x2AF8), RegistryValueKind.DWord); | |
FindAppkey = Convert.ToString(Regkey.GetValue(appName)); | |
if (FindAppkey == "11000") | |
txt_Status.Text += "\r\n" + "브라우져 에뮬레이션 설정에 성공하였습니다."; | |
else | |
txt_Status.Text += "\r\n" + "브라우저 에뮬레이션 설정에 실패하였습니다. 버전: " + FindAppkey; | |
} | |
catch (Exception ex) | |
{ | |
txt_Status.Text += "\r\n" + "브라우저 에뮬레이션 세팅 실패!!"; | |
txt_Status.Text += "\r\n" + ex.Message; | |
} | |
finally | |
{ | |
if (Regkey != null) | |
Regkey.Close(); | |
} | |
} | |
private void Fiddler_Run() | |
{ | |
#region AttachEventListeners | |
// | |
// It is important to understand that FiddlerCore calls event handlers on the | |
// session-handling thread. If you need to properly synchronize to the UI-thread | |
// (say, because you're adding the sessions to a list view) you must call .Invoke | |
// on a delegate on the window handle. | |
// | |
// If you are writing to a non-threadsafe data structure (e.g. List<t>) you must | |
// use a Monitor or other mechanism to ensure safety. | |
// | |
// Simply echo notifications to the console. Because Fiddler.CONFIG.QuietMode=true | |
// by default, we must handle notifying the user ourselves. | |
Fiddler.FiddlerApplication.OnNotification += delegate (object sender, NotificationEventArgs oNEA) | |
{ | |
//Console.WriteLine("** NotifyUser: " + oNEA.NotifyString); | |
}; | |
Fiddler.FiddlerApplication.Log.OnLogString += delegate (object sender, LogEventArgs oLEA) | |
{ | |
//Console.WriteLine("** LogString: " + oLEA.LogString); | |
}; | |
Fiddler.FiddlerApplication.BeforeRequest += delegate (Fiddler.Session oS) | |
{ | |
//Console.WriteLine("Before request for:\t" + oS.fullUrl); | |
// In order to enable response tampering, buffering mode must | |
// be enabled; this allows FiddlerCore to permit modification of | |
// the response in the BeforeResponse handler rather than streaming | |
// the response to the client as the response comes in. | |
oS.bBufferResponse = true; | |
try | |
{ | |
oAllSessions.Add(oS); | |
//txt_Status.Text += "\r\n[SYB]FULLURL: " + oS.fullUrl; | |
} | |
catch (System.Exception e) | |
{ | |
txt_Status.Text += string.Format("\r\n" + "oAllSessions.Add(oS): {0}", e.Message); | |
} | |
}; | |
Fiddler.FiddlerApplication.BeforeResponse += delegate (Fiddler.Session oS) | |
{ | |
// Console.WriteLine("{0}:HTTP {1} for {2}", oS.id, oS.responseCode, oS.fullUrl); | |
// Uncomment the following two statements to decompress/unchunk the | |
// HTTP response and subsequently modify any HTTP responses to replace | |
// instances of the word "Microsoft" with "Bayden" | |
oS.utilDecodeResponse(); | |
if (oS.HostnameIs("fileis.com")) | |
{ | |
string sPattern = @"^http://fileis\.com/js/lib/viewPopup\.js\?ver=\d+?.?"; | |
if (Regex.IsMatch(oS.fullUrl, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) | |
{ | |
string hook_str; | |
if (bIsLocal) | |
{ | |
hook_str = "if(flag_adult == '1'){location.href = \"http://192.168.0.8:5003/search_signedin/\" + idx + \"/" + sChatId + "/" + sMobilePhone + "/" + sUserName + "\";}"; | |
//txt_Status.Text += "\r\n" + hook_str; | |
} | |
else | |
{ | |
hook_str = "if(flag_adult == '1'){location.href = \"http://helloong.ipdisk.co.kr:5003/search_signedin/\" + idx + \"/" + sChatId + "/" + sMobilePhone + "/" + sUserName + "\";}"; | |
//txt_Status.Text += "\r\n" + hook_str; | |
} | |
if (oS.utilReplaceInResponse("// adt check page parameter Start", hook_str)) | |
{ | |
//txt_Status.Text += "\r\n" + "Modifing popup script for adult content!!"; | |
} | |
} | |
sPattern = @"^http://fileis\.com/js/old_function.js\?ver=\d+?.?"; | |
if (Regex.IsMatch(oS.fullUrl, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) | |
{ | |
string find_str = @"movePageLayers\(url, caller, location_\)\s+//.+?\s+?{"; | |
//txt_Status.Text += "\r\n" + find_str; | |
string replace_str; | |
if (bIsLocal) | |
{ | |
//string replace_str = @"movePageLayers(url, caller, location_){alert(url);alert('index of: ' + url.indexOf('/contents/index.htm?category1=ADT'));if(url.indexOf('/contents/index.htm?category1=ADT') == 0){self.location.href='http://helloong.ipdisk.co.kr:5003/serfe_url?url='+url;}"; | |
replace_str = @"movePageLayers(url, caller, location_){if(url.indexOf('/contents/index.htm?category1=ADT') == 0){self.location.href='http://192.168.0.8:5003/serfe_url?url='+url;}"; | |
} | |
else | |
{ | |
//string replace_str = @"movePageLayers(url, caller, location_){alert(url);alert('index of: ' + url.indexOf('/contents/index.htm?category1=ADT'));if(url.indexOf('/contents/index.htm?category1=ADT') == 0){self.location.href='http://helloong.ipdisk.co.kr:5003/serfe_url?url='+url;}"; | |
replace_str = @"movePageLayers(url, caller, location_){if(url.indexOf('/contents/index.htm?category1=ADT') == 0){self.location.href='http://helloong.ipdisk.co.kr:5003/serfe_url?url='+url;}"; | |
} | |
//txt_Status.Text += "\r\n" + replace_str; | |
if (oS.utilReplaceRegexInResponse(find_str, replace_str)) | |
{ | |
//txt_Status.Text += "\r\n" + "Modifing show login layer script for adult content!!"; | |
//txt_Status.Text += "\r\n" + "[SYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYB]"; | |
//txt_Status.Text += oS.GetResponseBodyAsString(); | |
//txt_Status.Text += "\r\n" + "[SYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYBSYB]"; | |
} | |
} | |
sPattern = @"^http://fileis\.com/contents/view\.htm\?idx=\d+?.?"; | |
if (Regex.IsMatch(oS.fullUrl, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) | |
{ | |
string file_id = ""; | |
Regex reg = new Regex(@"\?idx=(\d+?)&"); | |
MatchCollection resultMatches = reg.Matches(oS.fullUrl); | |
foreach (Match x in resultMatches) | |
{ | |
Group g = x.Groups[1]; | |
file_id = g.Value; | |
txt_Status.Text += "\r\n" + "파일아이디: " + file_id; | |
} | |
//txt_Status.Text += "\r\n" + "상세페이지로 이동합니다."; | |
string strDownLink = ""; | |
if (bIsLocal) | |
{ | |
if (btn_Login.Text == "로그아웃") | |
{ | |
// /web_login_down/<file_id>/<chat_id>/<mobile_phone> | |
// /web_login_down/<file_id>/<chat_id>/<mobile_phone>/<user_name> | |
strDownLink = "http://192.168.0.8:5003/web_login_down/" + file_id + "/" + sChatId + "/" + sMobilePhone + "/" + sUserName; | |
} | |
else | |
{ | |
strDownLink = "http://192.168.0.8:5003/web_down/" + file_id; | |
} | |
} | |
else | |
{ | |
if (btn_Login.Text == "로그아웃") | |
{ | |
strDownLink = "http://helloong.ipdisk.co.kr:5003/web_login_down/" + file_id + "/" + sChatId + "/" + sMobilePhone + "/" + sUserName; | |
} | |
else | |
{ | |
strDownLink = "http://helloong.ipdisk.co.kr:5003/web_down/" + file_id; | |
} | |
} | |
if (oS.utilReplaceInResponse("찜하기</a>", "찜하기</a><span id=\"topBtnFake2\" class=\"btn_dv_quickdown\" style=\"cursor:pointer;display:none;\"> 찜하기</span> <a href=\"" + strDownLink + "\" id=\"AllFilesForYou\" class=\"btn_dv_quickdown\">올파일포유다운</a>")) | |
{ | |
//txt_Status.Text += "\r\n" + "Modifing the login page of content!!"; | |
} | |
if (oS.utilReplaceInResponse("찜 해제</a>", "찜 해제</a><span id=\"topBtnFake2\" class=\"btn_dv_quickdown\" style=\"cursor:pointer;display:none;\"> 찜 해제</span> <a href=\"" + strDownLink + "\" id=\"AllFilesForYou\" class=\"btn_dv_quickdown\">올파일포유다운</a>")) | |
{ | |
//txt_Status.Text += "\r\n" + "Modifing the none login page of content!!"; | |
} | |
} | |
} | |
if (oS.fullUrl.ToString().StartsWith("http://helloong.ipdisk.co.kr:5003/contents/view.htm?idx=") || | |
oS.fullUrl.ToString().StartsWith("http://192.168.0.8:5003/contents/view.htm?idx=")) | |
{ | |
string file_id = ""; | |
Regex reg = new Regex(@"\?idx=(\d+?)&"); | |
MatchCollection resultMatches = reg.Matches(oS.fullUrl); | |
foreach (Match x in resultMatches) | |
{ | |
Group g = x.Groups[1]; | |
file_id = g.Value; | |
txt_Status.Text += "\r\n" + "파일아이디: " + file_id; | |
} | |
//txt_Status.Text += "\r\n" + "상세페이지로 이동합니다."; | |
string strDownLink = ""; | |
if (bIsLocal) | |
{ | |
if (btn_Login.Text == "로그아웃") | |
{ | |
// /web_login_down/<file_id>/<chat_id>/<mobile_phone> | |
// /web_login_down/<file_id>/<chat_id>/<mobile_phone>/<user_name> | |
strDownLink = "http://192.168.0.8:5003/web_login_down/" + file_id + "/" + sChatId + "/" + sMobilePhone + "/" + sUserName; | |
} | |
else | |
{ | |
strDownLink = "http://192.168.0.8:5003/web_down/" + file_id; | |
} | |
} | |
else | |
{ | |
if (btn_Login.Text == "로그아웃") | |
{ | |
strDownLink = "http://helloong.ipdisk.co.kr:5003/web_login_down/" + file_id + "/" + sChatId + "/" + sMobilePhone + "/" + sUserName; | |
} | |
else | |
{ | |
strDownLink = "http://helloong.ipdisk.co.kr:5003/web_down/" + file_id; | |
} | |
} | |
if (oS.utilReplaceInResponse("찜하기</a>", "찜하기</a><span id=\"topBtnFake2\" class=\"btn_dv_quickdown\" style=\"cursor:pointer;display:none;\"> 찜하기</span> <a href=\"" + strDownLink + "\" id=\"AllFilesForYou\" class=\"btn_dv_quickdown\">올파일포유다운</a>")) | |
{ | |
//txt_Status.Text += "\r\n" + "Modifing the login page of content!!"; | |
} | |
if (oS.utilReplaceInResponse("찜 해제</a>", "찜 해제</a><span id=\"topBtnFake2\" class=\"btn_dv_quickdown\" style=\"cursor:pointer;display:none;\"> 찜 해제</span> <a href=\"" + strDownLink + "\" id=\"AllFilesForYou\" class=\"btn_dv_quickdown\">올파일포유다운</a>")) | |
{ | |
//txt_Status.Text += "\r\n" + "Modifing the none login page of content!!"; | |
} | |
} | |
if (oS.fullUrl.ToString().StartsWith("http://192.168.0.8:5003/serfe_url?url=/contents/index.htm?category1=ADT&category2=ADT_OTH")) | |
{ | |
//txt_Status.Text += "\r\n" + "hoho=================================hoho"; | |
// http://192.168.0.8:5003/serfe_url?url=/contents/index.htm?category1=ADT&category2=ADT_OTH&s_word=&viewTab=new&viewList=&rows=25&page=3 | |
if (oS.utilReplaceInResponse(@"</a><a href=""#", @"</a><a href=""http://192.168.0.8:5003/serfe_url?url=/contents/index.htm?category1=ADT&category2=ADT_OTH&s_word=&viewTab=new&viewList=&rows=25&page=")) | |
{ | |
//txt_Status.Text += "\r\n" + "================================="; | |
} | |
} | |
}; | |
Fiddler.FiddlerApplication.AfterSessionComplete += delegate (Fiddler.Session oS) | |
{ | |
//Console.WriteLine("Finished session:\t" + oS.fullUrl); | |
// Fiddler.Utilities.WriteSessionArchive(@"C:\users\ericlaw\desktop\" + oS.id + ".saz", new Fiddler.Session[] { oS }, "secret", true); | |
}; | |
// Tell the system console to handle CTRL+C by calling our method that | |
// gracefully shuts down the FiddlerCore. | |
// | |
// Note, this doesn't handle the case where the user closes the window with the close button. | |
// See http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx for info on that... | |
// | |
#endregion AttachEventListeners | |
//Console.WriteLine(String.Format("Starting {0}...", Fiddler.FiddlerApplication.GetVersionString())); | |
// For the purposes of this demo, we'll forbid connections to HTTPS | |
// sites that use invalid certificates | |
Fiddler.CONFIG.IgnoreServerCertErrors = false; | |
// Because we've chosen to decrypt HTTPS traffic, makecert.exe must | |
// be present in the Application folder. | |
Fiddler.FiddlerApplication.Startup(12570, false, true); | |
//Console.WriteLine("Hit CTRL+C to end session."); | |
// Fiddler.FiddlerApplication.Shutdown(); | |
// Fiddler.FiddlerApplication.Startup(8877, true, true); | |
//*/ | |
} | |
private void btn_Back_Click(object sender, EventArgs e) | |
{ | |
wb.GoBack(); | |
} | |
private void btn_Next_Click(object sender, EventArgs e) | |
{ | |
wb.GoForward(); | |
} | |
private void btn_Home_Click(object sender, EventArgs e) | |
{ | |
wb.Navigate("http://fileis.com"); | |
} | |
private void btn_Exit_Click(object sender, EventArgs e) | |
{ | |
Quit_Proc(); | |
} | |
private void frm_main_FormClosing(object sender, FormClosingEventArgs e) | |
{ | |
} | |
private void frm_main_SizeChanged(object sender, EventArgs e) | |
{ | |
Control control = (Control)sender; | |
wb.Size = new Size(control.Size.Width, control.Size.Height - 85); | |
} | |
private void txt_TelegramID_KeyDown(object sender, KeyEventArgs e) | |
{ | |
Control control = (Control)sender; | |
if (e.KeyCode == Keys.Enter) | |
{ | |
DialogResult result = MessageBox.Show("입력하신 ID로 로그인 하시겠습니까?", "알림", MessageBoxButtons.YesNo); | |
if (result == DialogResult.Yes) | |
{ | |
btn_Login.PerformClick(); | |
} | |
else | |
{ | |
txt_TelegramID.SelectAll(); | |
txt_TelegramID.Focus(); | |
} | |
} | |
} | |
private string Get(string uri) | |
{ | |
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); | |
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; | |
try | |
{ | |
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) | |
using (Stream stream = response.GetResponseStream()) | |
using (StreamReader reader = new StreamReader(stream)) | |
{ | |
return reader.ReadToEnd(); | |
} | |
} | |
catch (Exception e) | |
{ | |
txt_Status.Text += "\r\n" + e.Message; | |
return ""; | |
} | |
} | |
private string[] Get_LoginInfo() | |
{ | |
string regSubkey = "Software\\AllFilesForYou"; | |
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(regSubkey, true); | |
if (regKey == null) | |
{ | |
regKey = Registry.LocalMachine.CreateSubKey(regSubkey); | |
} | |
try | |
{ | |
return regKey.GetValue("LoginID") as string[]; | |
} | |
catch (Exception e) | |
{ | |
txt_Status.Text += "\r\n" + e.Message; | |
string[] Login_Info = { "", "", "" }; | |
return Login_Info; | |
} | |
finally | |
{ | |
if (regKey != null) | |
regKey.Close(); | |
} | |
} | |
private int Set_LoginInfo(string[] login_info) | |
{ | |
string regSubkey = "Software\\AllFilesForYou"; | |
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(regSubkey, true); | |
if (regKey == null) | |
{ | |
regKey = Registry.LocalMachine.CreateSubKey(regSubkey); | |
} | |
try | |
{ | |
regKey.SetValue("LoginID", login_info); | |
return 0; | |
} | |
catch (Exception e) | |
{ | |
txt_Status.Text += "\r\n" + e.Message; | |
return -1; | |
} | |
finally | |
{ | |
if (regKey != null) | |
{ | |
regKey.Close(); | |
} | |
} | |
} | |
private int Del_LoginInfo() | |
{ | |
string regSubkey = "Software\\AllFilesForYou"; | |
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(regSubkey, true); | |
if (regKey == null) | |
{ | |
regKey = Registry.LocalMachine.CreateSubKey(regSubkey); | |
} | |
try | |
{ | |
regKey.DeleteValue("LoginID"); | |
return 0; | |
} | |
catch (Exception e) | |
{ | |
txt_Status.Text += "\r\n" + e.Message; | |
return -1; | |
} | |
finally | |
{ | |
if (regKey != null) | |
{ | |
regKey.Close(); | |
} | |
} | |
} | |
private void btn_Login_Click(object sender, EventArgs e) | |
{ | |
if (txt_TelegramID.Text.Trim().Length <= 4) | |
{ | |
MessageBox.Show("텔레그램 아이디를 입력하셔야 합니다.", "알림", MessageBoxButtons.OK); | |
txt_TelegramID.SelectAll(); | |
txt_TelegramID.Focus(); | |
return; | |
} | |
if (btn_Login.Text == "로그인") | |
{ | |
string sUrl; | |
//txt_Status.Text += "\r\n" + bIsLocal.ToString(); | |
if (bIsLocal) | |
{ | |
sUrl = "http://192.168.0.8:5003/login/" + txt_TelegramID.Text; | |
//txt_Status.Text += "\r\n" + sUrl.ToString(); | |
} | |
else | |
{ | |
sUrl = "http://helloong.ipdisk.co.kr:5003/login/" + txt_TelegramID.Text; | |
//txt_Status.Text += "\r\n" + sUrl.ToString(); | |
} | |
string sRetVal = Get(sUrl); | |
//txt_Status.Text += "\r\n" + sRetVal.ToString(); | |
if (sRetVal == "") | |
{ | |
MessageBox.Show("로그인에 실패하였습니다.", "알림", MessageBoxButtons.OK); | |
sChatId = ""; | |
sUserName = ""; | |
sMobilePhone = ""; | |
return; | |
} | |
//txt_Status.Text += "\r\n" + sRetVal; | |
Regex reg = new Regex(@"\[Y/(?<chat_id>\d+?)/(?<user_name>.+?)/(?<user_mobile>.+?)\]"); | |
MatchCollection retValues = reg.Matches(sRetVal); | |
//txt_Status.Text += "\r\nMatches Count: " + retValues.Count.ToString(); | |
if (retValues.Count < 1) | |
{ | |
MessageBox.Show("로그인에 실패하였습니다.", "알림", MessageBoxButtons.OK); | |
sChatId = ""; | |
sUserName = ""; | |
sMobilePhone = ""; | |
return; | |
} | |
foreach (Match retValue in retValues) | |
{ | |
//txt_Status.Text += "\r\n" + retValue.Groups["chat_id"].Value.ToString(); | |
//txt_Status.Text += "\r\n" + retValue.Groups["user_name"].Value.ToString(); | |
//txt_Status.Text += "\r\n" + retValue.Groups["user_mobile"].Value.ToString(); | |
sChatId = retValue.Groups["chat_id"].Value.ToString(); | |
sUserName = retValue.Groups["user_name"].Value.ToString(); | |
sMobilePhone = retValue.Groups["user_mobile"].Value.ToString(); | |
} | |
string[] lLoginInfo = { sChatId, sUserName, sMobilePhone }; | |
Set_LoginInfo(lLoginInfo); | |
Login_Status(); | |
} | |
else | |
{ | |
Logout_Status(); | |
Del_LoginInfo(); | |
Quit_Proc(); | |
} | |
} | |
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) | |
{ | |
if (btn_Login.Text == "로그인") | |
{ | |
if (e.Url.ToString().StartsWith("http://fileis") || e.Url.ToString().StartsWith("http://www.fileis")) | |
{ | |
if (bIsLocal) | |
{ | |
wb.Navigate("http://192.168.0.8:5003/waiting"); | |
} | |
else | |
{ | |
wb.Navigate("http://helloong.ipdisk.co.kr:5003/waiting"); | |
} | |
} | |
} | |
} | |
private Boolean Server_Ping() | |
{ | |
string sUrl = ""; | |
if (bIsLocal) | |
{ | |
sUrl = "http://192.168.0.8:5003/ping"; | |
} | |
else | |
{ | |
sUrl = "http://helloong.ipdisk.co.kr:5003/ping"; | |
} | |
try | |
{ | |
string sRetVal = Get(sUrl); | |
if (sRetVal == "Y") | |
return true; | |
else | |
{ | |
txt_Status.Text += "\r\n" + "서비스가 실행중이지 않습니다."; | |
return false; | |
} | |
} | |
catch (Exception ex) | |
{ | |
txt_Status.Text += "\r\n" + ex.Message; | |
txt_Status.Text += "\r\n" + "서비스 상태확인에 실패하였습니다."; | |
return false; | |
} | |
} | |
private Boolean Get_BuildNum() | |
{ | |
string sUrl = ""; | |
if (bIsLocal) | |
{ | |
sUrl = "http://192.168.0.8:5003/buildnum"; | |
} | |
else | |
{ | |
sUrl = "http://helloong.ipdisk.co.kr:5003/buildnum"; | |
} | |
try | |
{ | |
string sRetVal = Get(sUrl); | |
if (sRetVal == sBuildNum) | |
return true; | |
else | |
{ | |
txt_Status.Text += "\r\n" + "브라우저 버전 불일치!!"; | |
return false; | |
} | |
} | |
catch (Exception ex) | |
{ | |
txt_Status.Text += "\r\n" + ex.Message; | |
txt_Status.Text += "\r\n" + "브라우저 버전 확인에 실패하였습니다."; | |
return false; | |
} | |
} | |
private void Logout_Status() | |
{ | |
sChatId = ""; | |
sUserName = ""; | |
sMobilePhone = ""; | |
btn_Login.Text = "로그인"; | |
txt_TelegramID.Text = ""; | |
txt_TelegramID.Enabled = true; | |
txt_UserName.Text = ""; | |
txt_UserName.Enabled = true; | |
btn_Back.Enabled = false; | |
btn_Next.Enabled = false; | |
btn_Home.Enabled = false; | |
if (bIsLocal) | |
{ | |
this.wb.Navigate("http://192.168.0.8:5003/waiting"); | |
} | |
else | |
{ | |
this.wb.Navigate("http://helloong.ipdisk.co.kr:5003/waiting"); | |
} | |
} | |
private void Login_Status() | |
{ | |
btn_Login.Text = "로그아웃"; | |
txt_TelegramID.Enabled = false; | |
txt_UserName.Text = sUserName; | |
txt_UserName.Enabled = false; | |
btn_Back.Enabled = true; | |
btn_Next.Enabled = true; | |
btn_Home.Enabled = true; | |
this.wb.Navigate("http://fileis.com"); | |
} | |
private void Quit_Proc() | |
{ | |
// MessageBox.Show("올파일포유 브라우저를 종료합니다.", "알림", MessageBoxButtons.OK); | |
try | |
{ | |
Fiddler.FiddlerApplication.oProxy.Detach(); | |
Fiddler.FiddlerApplication.Shutdown(); | |
} | |
finally | |
{ | |
Application.Exit(); | |
} | |
} | |
public frm_main() | |
{ | |
InitializeComponent(); | |
// Del, 2018.05.08, hElLoOnG, 무조건 텔레그램 로그인 방식으로 변경으로 인한 삭제 | |
// 실행가능장소 체크 | |
if (!Check_execute_place()) | |
{ | |
/* | |
DialogResult result = MessageBox.Show("실행 불가능한 장소입니다.\r\n임시 실행 하시겠습니까?", "알림", MessageBoxButtons.YesNo); | |
if(result == DialogResult.Yes) | |
{ | |
string sTempKey = Microsoft.VisualBasic.Interaction.InputBox("알림", "임시 실행 키:", "여기에 키 입력!!", 0, 0); | |
if (sTempKey == "여기에 키 입력!") | |
{ | |
MessageBox.Show("임시 장소에서 실행합니다.", "알림", MessageBoxButtons.OK); | |
} | |
else | |
{ | |
Quit_Proc(); | |
} | |
} | |
else | |
{ | |
Quit_Proc(); | |
} | |
*/ | |
} | |
if (!Server_Ping()) | |
{ | |
MessageBox.Show("서비스 상태확인에 실패하였습니다.\r\n잠시후 다시 시도하여주세요.", "알림", MessageBoxButtons.OK); | |
Quit_Proc(); | |
} | |
if (!Get_BuildNum()) | |
{ | |
MessageBox.Show("전용브라우저가 업데이트 되었습니다.\r\n텔레그램에서 /브라우저 명령을 실행하여 최신버전 브라우저 다운로드 후 재시도 하여주세요!!", "알림", MessageBoxButtons.OK); | |
Quit_Proc(); | |
} | |
string[] lLogin_info = Get_LoginInfo(); | |
if (lLogin_info == null || String.IsNullOrEmpty(lLogin_info[0])) | |
{ | |
Logout_Status(); | |
} | |
else | |
{ | |
sChatId = lLogin_info[0]; | |
sUserName = lLogin_info[1]; | |
sMobilePhone = lLogin_info[2]; | |
txt_TelegramID.Text = sChatId; | |
Login_Status(); | |
} | |
var appName = Process.GetCurrentProcess().ProcessName + ".exe"; | |
SetWebBorwserVersion(appName); | |
Fiddler_Run(); | |
RefreshIESettings("127.0.0.1:12570"); | |
dynamic ax = this.wb.ActiveXInstance; | |
ax.NewWindow += new NewWindowDelegate(this.OnNewWindow); | |
txt_TelegramID.Focus(); | |
} | |
private void btn_ClearLog_Click(object sender, EventArgs e) | |
{ | |
txt_Status.Text = ""; | |
oAllSessions.Clear(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment