You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

358 lines
13 KiB

# coding=utf-8
import base64
import json
import re
import urllib
import hashlib
import os
import random
import string
import sys
import time
from PIL import Image, ImageDraw, ImageFont
from lms.html2bbcode import HTML2BBCode
from lms.settings import BASE_DIR, BILL_RESULT_KEY, BILL_KEY, COMMENT_SECRET
BBParser = HTML2BBCode()
def out_uri(url, data):
params = urllib.parse.urlencode(data)
# Отправка красивой uri строки
return "%s?%s" % (url, params)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def gen_pay_sig(keys, method='', result=True):
# Формирование
sig = '%s;' % method
for key, value in sorted(keys.items()):
if value and key != 'sp_sig' and key[:3] == 'sp_':
sig += '{0};'.format(value)
sig += BILL_RESULT_KEY if result else BILL_KEY
return hashlib.md5(sig.encode('utf-8')).hexdigest()
def comment_auth_data(user):
_time = str(int(time.time()))
USER_INFO = str('{"nick": "')+str(user.get_name())+str('", "avatar": "')+str(user.get_image_url())+('", "id": "')+str(user.id)+str('", "email": "')+str(user.email)+str('", "profile_url": "')+str(user.get_profile())+('"}')
user_base64 = base64.b64encode(USER_INFO.encode('utf-8')).decode('utf-8')
before_sign = ('{0}{1}{2}'.format(COMMENT_SECRET, user_base64, _time)).encode('utf-8')
sign = hashlib.md5(before_sign).hexdigest()
return "{0}_{1}_{2}".format(user_base64, _time, sign)
def random_string(length=10, postfix='', prefix=''):
# Генерация случайной строки
string_in = \
''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(length))
return prefix + string_in + postfix
def random_int(length=1, postfix='', prefix=''):
result = ''.join(random.choice(string.digits) for x in range(length))
return prefix + str(result) + postfix
def md5_for_file(f):
# Вичисление ХЕШ суммы файла
return hashlib.md5(open(f).read()).hexdigest()
def condition_factory(list_in):
# Фабрика проверки условий
# i['condition'] - Условие
# i['error'] - Ошибка выполнения запроса
# result['code'] = 0 - условие не выполнилось
# result['response'] - Текст ошибки не выполненного условия
result = {
'code': '1',
'response': ''
}
for i in list_in:
if not i['condition']:
result['code'] = '0'
result['response'] = i['error']
return result
return result
def chap_shielding(chap, shielding):
result = ''
if chap in shielding:
result += '\\' + chap
else:
result += chap
return result
def word_shielding(word, shielding):
result = ''
for ch in word:
result += chap_shielding(ch, shielding)
return result
def str_shielding(str, exclude):
# Экранирование строки
# exclude - строка элементов, которые не нужно экранировать
result = ''
shielding_chp = ["'", '{', '}']
n = 0
exlude_flag = list([len(i) for i in exclude])
max_n = max(exlude_flag)
_tmp = ''
_shi_tmp = ''
for chap in str:
_tmp += chap
if chap in shielding_chp:
_shi_tmp += '\\' + chap
else:
_shi_tmp += chap
n += 1
if n in exlude_flag:
if _tmp in exclude:
result += _tmp
n = 0
_tmp = ''
_shi_tmp = ''
if n == max_n:
result += _shi_tmp
n = 0
_tmp = ''
_shi_tmp = ''
if _shi_tmp:
result += _shi_tmp
return result
def translit(locallangstring, only_letter=False):
conversion = {
u'\u0410': 'a', u'\u0430': 'a',
u'\u0411': 'b', u'\u0431': 'b',
u'\u0412': 'v', u'\u0432': 'v',
u'\u0413': 'g', u'\u0433': 'g',
u'\u0414': 'd', u'\u0434': 'd',
u'\u0415': 'e', u'\u0435': 'e',
u'\u0401': 'yo', u'\u0451': 'yo',
u'\u0416': 'zh', u'\u0436': 'zh',
u'\u0417': 'z', u'\u0437': 'z',
u'\u0418': 'i', u'\u0438': 'i',
u'\u0419': 'y', u'\u0439': 'y',
u'\u041a': 'k', u'\u043a': 'k',
u'\u041b': 'l', u'\u043b': 'l',
u'\u041c': 'm', u'\u043c': 'm',
u'\u041d': 'n', u'\u043d': 'n',
u'\u041e': 'o', u'\u043e': 'o',
u'\u041f': 'p', u'\u043f': 'p',
u'\u0420': 'r', u'\u0440': 'r',
u'\u0421': 's', u'\u0441': 's',
u'\u0422': 't', u'\u0442': 't',
u'\u0423': 'u', u'\u0443': 'u',
u'\u0424': 'f', u'\u0444': 'f',
u'\u0425': 'h', u'\u0445': 'h',
u'\u0426': 'ts', u'\u0446': 'ts',
u'\u0427': 'ch', u'\u0447': 'ch',
u'\u0428': 'sh', u'\u0448': 'sh',
u'\u0429': 'sch', u'\u0449': 'sch',
u'\u042a': '"', u'\u044a': '"',
u'\u042b': 'y', u'\u044b': 'y',
u'\u042c': '\'', u'\u044c': '\'',
u'\u042d': 'e', u'\u044d': 'e',
u'\u042e': 'yu', u'\u044e': 'yu',
u'\u042f': 'ya', u'\u044f': 'ya',
u' ': '-',
u',': '',
u'': '-',
u'#': 'sharp'
}
conversion_letter = {
u'\u0410': 'a', u'\u0430': 'a',
u'\u0411': 'b', u'\u0431': 'b',
u'\u0412': 'v', u'\u0432': 'v',
u'\u0413': 'g', u'\u0433': 'g',
u'\u0414': 'd', u'\u0434': 'd',
u'\u0415': 'e', u'\u0435': 'e',
u'\u0401': 'yo', u'\u0451': 'yo',
u'\u0416': 'zh', u'\u0436': 'zh',
u'\u0417': 'z', u'\u0437': 'z',
u'\u0418': 'i', u'\u0438': 'i',
u'\u0419': 'y', u'\u0439': 'y',
u'\u041a': 'k', u'\u043a': 'k',
u'\u041b': 'l', u'\u043b': 'l',
u'\u041c': 'm', u'\u043c': 'm',
u'\u041d': 'n', u'\u043d': 'n',
u'\u041e': 'o', u'\u043e': 'o',
u'\u041f': 'p', u'\u043f': 'p',
u'\u0420': 'r', u'\u0440': 'r',
u'\u0421': 's', u'\u0441': 's',
u'\u0422': 't', u'\u0442': 't',
u'\u0423': 'u', u'\u0443': 'u',
u'\u0424': 'f', u'\u0444': 'f',
u'\u0425': 'h', u'\u0445': 'h',
u'\u0426': 'ts', u'\u0446': 'ts',
u'\u0427': 'ch', u'\u0447': 'ch',
u'\u0428': 'sh', u'\u0448': 'sh',
u'\u0429': 'sch', u'\u0449': 'sch',
u'\u042a': '', u'\u044a': '',
u'\u042b': 'y', u'\u044b': 'y',
u'\u042c': '', u'\u044c': '',
u'\u042d': 'e', u'\u044d': 'e',
u'\u042e': 'yu', u'\u044e': 'yu',
u'\u042f': 'ya', u'\u044f': 'ya',
u' ': '-'
}
translitstring = []
p = re.compile(r'\?')
for c in locallangstring:
translitstring.append(conversion.setdefault(c, c) if not only_letter else conversion_letter.setdefault(c, c))
return p.sub('', ''.join(translitstring))
def weekdays(date, short=False):
if short:
days = {0: u"ПН", 1: u"ВТ", 2: u"СР", 3: u"ЧТ", 4: u"ПТ", 5: u"СБ", 6: u"ВС"}
else:
days = {0: u"Понедельник", 1: u"Вторник", 2: u"Среда", 3: u"Четверг", 4: u"Пятница", 5: u"Суббота",
6: u"Воскресенье"}
return days[date.weekday()]
def transit_month(month):
monthes = {1: u'Января', 2: u'Февраля', 3: u'Марта', 4: u'Апреля', 5: u'Мая', 6: u'Июня', 7: u'Июля', 8: u'Августа',
9: u'Сентября', 10: u'Октября', 11: u'Ноября', 12: u'Декабря'}
return monthes[month]
def out_date_format(date, no_time=False):
# Формат выводимой даты
if date:
if no_time:
return u'{0} {1} {2} {3}'.format(weekdays(date, short=True), date.day, transit_month(date.month), date.year)
else:
return u'{0} {1} {2} {3}'.format(date.day, transit_month(date.month), date.year, date.strftime("%H:%M"))
return ''
def check_role(user, role):
result = {'result': False}
if user.in_role == role:
result['result'] = True
else:
if user.in_role == 'U':
result['redirect'] = '/access/profile'
elif user.in_role == 'T':
result['redirect'] = '/teacher/profile'
elif user.in_role == 'M':
result['redirect'] = '/management/profile/'
elif user.in_role == 'S':
result['redirect'] = '/management/super_profile/'
elif user.in_role == 'A':
result['redirect'] = '/admin'
return result
def phone_format(phone, type_in='long'):
if phone:
if type_in == 'short':
return u'({0}{1}{2}) {3}{4}{5}-{6}{7}-{8}{9}'.format(phone[0], phone[1], phone[2], phone[3], phone[4],
phone[5],
phone[6], phone[7], phone[8], phone[9])
elif type_in == 'long':
return u'+7 ({0}{1}{2}) {3}{4}{5}-{6}{7}-{8}{9}'.format(phone[0], phone[1], phone[2], phone[3], phone[4],
phone[5], phone[6], phone[7], phone[8], phone[9])
return ''
def check_set_password(password):
not_list = ['thomas', '121212', 'zxcvbnm', 'admin123', 'nikita', 'sergey', 'asdfghjkl', 'stalker', 'saravn',
'789456', 'password1234', 'aaaaaa', 'e10adc3949ba59abbe56e057f20f883e', 'fuckyou', '1q2w3e4r',
'football1', 'cjkysirj', 'gewinner', '123456789', '123123123', 'soccer', '123abc', '123321', 'gfhjkm',
'password1234567', '12344321', 'qwe123', 'hallo123', '\xd0\xbb\xd1\x8e\xd0\xb1\xd0\xbe\xd0\xb2\xd1\x8c',
'password123456789', 'shadow', 'password', 'qq18ww899', '123123', 'q1q1q1', 'michael', 'hejsan',
'111222', 'martin', '147258369', 'zzzzzz', '123qwe', '11111111', '159951', '7654321', '142536',
'mirage', '\xd0\xb9\xd1\x86\xd1\x83\xd0\xba\xd0\xb5\xd0\xbd', 'qwertyuiop[]', 'qwertyuiop', 'computer',
'1q2w3e', 'k.,jdm', '123456', 'knopka', 'lol123', 'password12', 'lovers', 'matrix', '555555',
'qazwsxedc', '1234554321', 'genius', 'daniel', 'internet', 'princess', 'nastya', 'fylhtq',
'password12345', '147258', '9379992', '12341234', 'maximius', 'spartak', '159753', 'fyfcnfcbz',
'qwertyu', 'marina', '666666', 'eminem', 'sophie', '1q2w3e4r5t', '258456', 'tecktonik', '1234567890',
'222222', '999999', 'iloveyou', 'abc123', 'qweqwe', '1111111111', '654321', '134679', 'q1w2e3',
'121314', 'letmein', '333333', 'vfhbyf', 'pokemon', 'george', 'tundra_cool2', 'monkey', '131313',
'1234567', 'password12345678', 'doudou', 'lollipop', 'holysh!t', 'secret', 'master', 'TempPassWord',
'naruto', 'andrey', '123654', '88888888', 'sunshine', 'andrew', '12345678', '987654', '1111111',
'asdfgh', 'cjmasterinf', 'password123456', 'easytocrack1', 'qwaszx', 'Test123', 'ghbdtn', 'azerty',
'212121', '777777', 'qweasd', 'yfnfif', '666999', '1111114', 'natasha', 'password1', 'changeme',
'kikugalanetroot', 'vkontakte', 'abcd1234', 'vfrcbv', 'loulou', 'qwerty', 'liverpool', 'ngockhoa',
'147852', '753951', 'qweasdzxc', 'dragon', 'superman', 'slipknot', '100827092', 'password123',
'baseball1', '232323', '19921992', '124578', '19951995', '888888', '1qaz2wsx', '159357', '112233',
'zxcvbn', 'qazwsx', 'asdasd', 'administrator', 'killer', '987654321',
'\xd0\xbf\xd0\xb0\xd1\x80\xd0\xbe\xd0\xbb\xd1\x8c', 'fktrcfylh', '7777777',
'135790', 'sandra', '1234321', '4815162342', '000000', 'samsung', 'charlie',
'zaqwsx', 'q1w2e3r4', '111111', 'jessica', '123789', 'parola']
result = True
message = ''
if len(password) < 6:
result = False
message = u'Пароль не должен быть меньше 6 символов'
if password in not_list:
result = False
message = u'Ваш пароль входит в список <br>"50 самых распространныеных паролей"<br> это не безопасно'
return result, message
def user_fabric(user=None):
if user and user.is_authenticated():
return user
else:
return None
def gen_write(SOURCE, FONT, FONT_SIZE, TEXT, HEIGHT, LEFT, COLOR):
PATH = os.path.join(BASE_DIR, 'media/img_creator/')
logo = Image.open(SOURCE).convert('RGBA')
img = Image.new('RGBA', logo.size, (0, 0, 0, 1))
fnt = ImageFont.truetype(FONT, int(FONT_SIZE))
d = ImageDraw.Draw(img)
d.text((int(HEIGHT), int(LEFT)), TEXT, font=fnt, fill=COLOR)
out = Image.alpha_composite(logo, img)
out.show()
path = os.path.join(PATH, '{0}-{1}.png'.format(translit(TEXT), random_int(length=10)))
out.save(path)
return path
def show_progress(full, now, post=''):
# + Процесс отображения процентов выполнения
# Отображение процента выполнения
if full != 0:
progress = float(now / (full * 0.01))
else:
progress = '100'
sys.stdout.write(u'\rВыполнено: {0:6.4}% {1}'.format(progress, post))
sys.stdout.flush()
def convert_html_to_bb(text):
return str(BBParser.feed(text.strip()))