Exemple #1
0
async def edit_comm_post(request):
    if not user_has_permission(request, 'des:obj', 'add_com'):
        return {"result": "fail", "error": "no comment"}
    if not user_is_logged_in(request):
        return response_json(request, {
            "result": "fail",
            "error": "no comment"
        })
    data = await request.post()
    comm_id = data.get('comm_id')
    body = data.get('body')
    user = data.get('user')

    if user == get_current_user(request) or is_admin(request):
        if 'child' in get_doc(request, comm_id) and not is_admin(request):
            return response_json(request, {
                "result": "fail",
                "error": "comment already answered"
            })
        doc = request.db.doc.update(
            {'_id': comm_id},
            {"$set": {
                "doc.body." + cur_lang(request): body
            }})
        from core.union import invalidate_cache
        invalidate_cache('single_page')
        return response_json(request, {"result": "ok", "id": comm_id})
    else:
        return response_json(request, {
            "result": "fail",
            "error": "access denied"
        })
Exemple #2
0
def add_vote_comm_post(request):
	"""Вычисляем данные в посте сколько проголосовало и тд."""
	data = request.post()
	vote    = data.get('vote')
	comm_id = data.get('comm_id')
	comm = get_doc(comm_id)

	# doc =  db.tree.find_one({'owner':doc_id})
	user = get_current_user(True)
	from libs.sites.sites import check_time
	# comm = doc['tree'][comm_id]


	if check_time( comm['doc']['date'], 'days', int( get_const_value(request, 'vote_timeout') ) ):
		return response_json(request, {"result":"fail", "error":"Голосование уже закончилось"})
	if not 'vote' in comm : comm['vote'] = {"score":0,"votes_count":0, "votes_count_plus":0,"votes_count_minus":0, "voted":{}}
	if not user_has_permission(request, 'des:obj', 'vote_com'): return response_json(request, {"result":"fail","error":"Не имеете права голоса"})
	if not is_admin(request) and user in comm['vote']['voted'] : return response_json(request, {"result":"fail","error":"Повторное голосование запрещено"})
	if not is_admin(request) and user == 'user:'******'title']): return response_json(request, {"result":"fail","error":"Голосовать за себя запрещено"})

	dt = datetime.today().strftime('%Y-%m-%d')
	user_f = get_doc(request, user)
	if not 'vote' in user_f : user_f['vote'] = {}
	if not dt in user_f['vote'] : user_f['vote'][dt] = {'up': 0, 'down': 0}

	if not is_admin(request) and int(user_f['vote'][dt]['up']) + int(user_f['vote'][dt]['down']) >= int(float(user_f['doc']['rate'])+1.25):
		return response_json(request, {"result":"fail","error":"Лимит голосов за сегодня исчерпан"})

	user_f['vote'][dt][vote] += 1
	request.db.doc.save(user_f)

	comm['vote']['voted'][user] = vote
	if vote == 'up':
		comm['vote']['score'] += 1
		comm['vote']['votes_count_plus'] += 1
	else:
		comm['vote']['score'] -= 1
		comm['vote']['votes_count_minus'] += 1
	comm['vote']['votes_count'] += 1
	request.db.doc.save(comm)
	comm_vote = comm['vote']

	# начисление балов пользователю
	# u_id = 'user:'******'title'])
	u_id = ct(request, comm['doc']['user'] )
	u = get_doc(request, u_id)
	if u:
		if not 'rate' in u['doc']:
			u['doc']['rate'] = '0'
			request.db.doc.save(u)
		if float(u['doc']['rate']) >= 17:
			rate = float(u['doc']['rate']) + (0.02 if vote == 'up' else -0.1)
		else: rate = float(u['doc']['rate']) + (0.2 if vote == 'up' else -0.1)
		#	rate =+ 1 if vote == 'up' else -1
		update_cell(request, str(u_id), 'des:users', 'rate', str(rate) )

	return response_json(request, {"result":"ok", "score":comm_vote["score"],"votes_count":comm_vote["score"],"charge_string":"","sign":"positive",
	        "votes_count_plus":comm_vote["votes_count_plus"],"votes_count_minus":comm_vote["votes_count_minus"],"is_positive":True})
Exemple #3
0
def ban_comm_post(request):
    if not is_admin(request):
        return response_json(request, {"result": "fail", "error": "no ban"})
    if not user_is_logged_in(request):
        return response_json(request, {
            "result": "fail",
            "error": "no comment"
        })
    data = request.post()
    proc_id = data.get('proc_id')
    id_comm = data.get('branch_id')
    doc = request.db.doc.find_one({'_id': id_comm})

    doc = doc['doc']
    ip = doc['ip'] if 'ip' in doc else ''
    # try:
    lst = [
        x.strip() for x in get_const_value(request, 'ban_comm', '').split(',')
    ]
    # die([lst, ip, branch])
    if not ip in lst:
        lst.append(ip)
    set_const_value(request, 'ban_comm', ','.join(lst))

    user_name = ct(request, doc['user'])
    user = get_doc(request, 'user:'******'doc']['ban'] = 'true'
        request.db.doc.save(user)
    return response_json(request, {"result": "ok", "user": user_name})
Exemple #4
0
def save_tags(request, doc, tag_dict):
	"""
	разбиваем строчку тегов в масив и заносим в документ правильно разбитые теги
	call the function that fills in the tag cloud
	tag_dict - справочник из которого теги сохраняются   вроде как удалено из текста
	1) check that the document contains tags
	2) разбиваем строку тегов на слова через запятую и запихиваем в словарь tags = {'tag1':1,'tag2':1}
	"""
	# TODO если теги пустые то мы их не стираем
	lang = cur_lang(request)
	if 'doc' in doc and doc['doc'] and 'tags' in doc['doc'] and doc['doc']['tags']:
		if lang in doc['doc']['tags']:
			if not doc['doc']['tags'][lang]: doc['doc']['tags'][lang] = ''
			t_old = doc['tags'][lang] if 'tags' in doc and lang in doc['tags'] else []
			# разбиваем строку тегов на слова через и запихиваем в словарь tags = {'123':1, '456':1}
			tags = dict([(i.strip().lower(), 1) for i in doc['doc']['tags'][lang].split(',') if i.strip()])
			if not 'tags' in doc: doc['tags'] = {}
			if not is_admin(request) and not user_has_permission(request, doc['doc_type'], 'edit_tag'):
				# наполняем в ифе tags теми перемеными которые не содержат звездочки.
				tags2 = tags; tags = {}
				for res in tags2:
					if not '*' in res:
						tags[res] = tags2[res]
			doc['tags'][lang] = tags
			if doc['doc_type'] in ['des:news', 'des:obj', 'des:banners', 'des:wiki']:
				if 'pub' in doc['doc'] and doc['doc']['pub'] == 'true':
					if 'accept' in doc['doc'] and doc['doc']['accept'] == 'true' or doc['doc_type'] in ['des:banners', 'des:wiki', 'des:news']:
						count_tags(request, tags, t_old, doc['doc_type'])
			elif doc['doc_type'] in ['des:ware']:
				count_tags(request, tags, t_old, doc['doc_type'])
			doc['doc']['tags'][lang] = ', '.join(tags)
			request.db.doc.save(doc)
Exemple #5
0
async def del_comm_post(request):
    """ doc_id - id самого коментария """
    data = await request.post()
    print(data)
    comm_id = data.get('comm_id')
    doc = get_doc(request, comm_id)

    if is_admin(request) or user_has_permission(request, 'des:obj',
                                                'del_comm'):
        # добавление подсчета коментариев в отдельном документе
        request.db.doc.update({"_id": doc['doc']['owner']},
                              {"$inc": {
                                  "count_branch": -1
                              }})
        if 'child' in doc:
            if len(doc['child']):
                request.db.doc.update({"_id": comm_id},
                                      {"$set": {
                                          'doc.is_del': 'true'
                                      }})
                return response_json(request, {
                    "result": "ok",
                    "action": "del_dom",
                    "id": comm_id
                })
        else:
            del_row(request, 'des:comments', {comm_id: comm_id})
            return response_json(request, {"result": "ok", "id": comm_id})

    else:
        return response_json(request, {
            "result": "fail",
            "error": "error sequrity"
        })
Exemple #6
0
def table_data_(request, proc_id):
	if get_const_value( request, 'is_admin') == "false" and not is_admin(request): return redirect('/')
	data = get_post( request )
	select_id = data['select_id'] if 'select_id' in data else None

	url = ''
	meta_doc = get_mt(request, proc_id)

	meta_table = check_map_perm(request, proc_id, meta_doc['doc'])
	#это для интернационализации
	parts = []
	# строим иерархию по шапкам
	for res in request.db.map.find({"conf.owner": proc_id}):
		parts.append(res)
	_parts = ""
	for tbl in parts:
		if _parts: _parts+=", "
		tp = 'table'; conf = {}
		if 'com:' == tbl['_id'][0:4]: tp = 'comments'
		if tp == 'table':
			conf['columns'] = rec_data_t(request, tbl['doc'])
		conf_ = ""
		for k in conf:
			if conf_: conf_ += ", "
			conf_ +='"' + k + '": '+ conf[k]
		conf_ = "{"+conf_+"}"
		_parts += '{"id": "' + tbl['_id'] + '", "title": "' + \
		          ct(request, tbl['conf']['title']) + '", "conf": ' + conf_ + ', "type": "' + tp + '" }'
	_parts = "["+_parts+"]"
	map_ = rec_data_t(request, meta_table)
	return  {'parts':_parts, 'hdata':meta_doc, 'map_':map_, 'url':url, 'proc_id':proc_id, 'select_id':select_id}
Exemple #7
0
async def get_doc_post(request):
	if is_admin(request):
		data = get_post(request)
		doc_id = data['doc_id']
		doc = request.db.doc.find_one({"_id":doc_id})['doc']
		return response_json(request,  {"result":"ok", "id":doc_id, "doc":doc})
	return response_json(request,  {"result":"fail", "doc":'bolt'})
Exemple #8
0
async def edit_comm_post(request):
	if not user_has_permission(request, 'des:obj', 'add_com'): return {"result":"fail", "error":"no comment"}
	if not user_is_logged_in(request): return response_json(request, {"result":"fail", "error":"no comment"})
	data = await request.post()
	comm_id = data.get('comm_id')
	body =    data.get('body')
	user =    data.get('user')

	if user == get_current_user(request) or is_admin(request):
		if 'child' in get_doc(request, comm_id) and not is_admin(request):
			return response_json(request, {"result":"fail", "error":"comment already answered"})
		doc = request.db.doc.update({'_id': comm_id}, {"$set": {"doc.body." + cur_lang(request): body}})
		from core.union import invalidate_cache
		invalidate_cache('single_page')
		return response_json(request, {"result":"ok", "id":comm_id})
	else:
		return response_json(request, {"result":"fail", "error":"access denied"})
Exemple #9
0
def accept_comm_post(request):
	if not is_admin(request) and not user_has_permission(request, 'des:comments', 'edit'):
		return response_json(request, {"result":"fail", "error":"no has permission"})
	data = get_post(request)
	doc_id = data.get('doc_id')
	doc = request.db.doc.find_one({'_id':doc_id})
	doc['doc']['pre'] = 'false'
	request.db.doc.save(doc)
	owner = doc['doc']['doc_id']
	comm_id = str(doc['doc']['comm_id'])
	tree = request.db.tree.find_one({'_id': owner})
	# die(tree['tree'].keys())
	tree['tree'][comm_id]['pre'] = 'false'
	request.db.tree.save(tree)
	return response_json(request, {"result":"ok"})
Exemple #10
0
async def del_comm_post(request):
	""" doc_id - id самого коментария """
	data = await request.post()
	print(data)
	comm_id = data.get( 'comm_id')
	doc = get_doc(request, comm_id)

	if is_admin(request) or user_has_permission(request, 'des:obj', 'del_comm'):
		# добавление подсчета коментариев в отдельном документе
		request.db.doc.update({ "_id": doc['doc']['owner'] }, { "$inc": { "count_branch":-1 } } )
		if 'child' in doc:
			if len(doc['child']):
				request.db.doc.update({"_id":comm_id}, {"$set":{'doc.is_del':'true'}})
				return response_json(request, {"result":"ok", "action":"del_dom", "id":comm_id})
		else:
			del_row(request, 'des:comments', { comm_id:comm_id })
			return response_json(request, {"result":"ok", "id":comm_id})

	else: return response_json(request, {"result":"fail", "error":"error sequrity"})
Exemple #11
0
def accept_comm_post(request):
    if not is_admin(request) and not user_has_permission(
            request, 'des:comments', 'edit'):
        return response_json(request, {
            "result": "fail",
            "error": "no has permission"
        })
    data = get_post(request)
    doc_id = data.get('doc_id')
    doc = request.db.doc.find_one({'_id': doc_id})
    doc['doc']['pre'] = 'false'
    request.db.doc.save(doc)
    owner = doc['doc']['doc_id']
    comm_id = str(doc['doc']['comm_id'])
    tree = request.db.tree.find_one({'_id': owner})
    # die(tree['tree'].keys())
    tree['tree'][comm_id]['pre'] = 'false'
    request.db.tree.save(tree)
    return response_json(request, {"result": "ok"})
Exemple #12
0
def ban_comm_post(request):
	if not is_admin(request): return response_json(request, {"result":"fail", "error":"no ban"})
	if not user_is_logged_in(request): return response_json(request, {"result":"fail", "error":"no comment"})
	data = request.post()
	proc_id = data.get('proc_id')
	id_comm = data.get('branch_id')
	doc = request.db.doc.find_one({'_id':id_comm})

	doc = doc['doc']
	ip = doc['ip'] if 'ip' in doc else ''
	# try:
	lst = [x.strip() for x in get_const_value(request, 'ban_comm', '').split(',')]
	# die([lst, ip, branch])
	if not ip in lst:
		lst.append(ip)
	set_const_value(request, 'ban_comm', ','.join(lst))

	user_name = ct(request, doc['user'])
	user = get_doc(request, 'user:'******'doc']['ban'] = 'true'
		request.db.doc.save(user)
	return response_json(request, {"result":"ok", "user":user_name})
Exemple #13
0
def table_data_post_(request, proc_id, filter, doc_id, parent, no_limit=False):
	""" Получает id таблицы и значения для фильтрации Берет из базы данные 
	формирует из них json и возвращает в нужный шаблон"""
	t = time.time()
	user_name = get_current_user(request)
	meta_doc = request.db.map.find_one({'_id':proc_id})
	meta_table = check_map_perm(request, proc_id, meta_doc['doc'])
	start_date = ''; end_date = '9999999999999999999999999'
	if 'date' in filter: 
		if 'start' in filter['date']: start_date = filter['date']['start'] 
		if 'end' in filter['date']: end_date = filter['date']['end'] + ' 99999999'
	if 'branch_id' in filter: branch_id = filter['branch_id']
	else: branch_id = None
	if 'page' in filter: page = filter['page']
	else: page = {}
	if not 'current' in page:
		page['current'] = 1
	limit = int(get_const_value(request, 'doc_page_limit'))
	skip = (page['current']-1)*limit
	#получаем данные из фильтров и присваиваем их нужной переменой
	condition = {'$and': [{'doc_type':proc_id}]}
#	condition = {'doc_type':proc_id, 'parent':{'$or':(parent)}
	if parent == '_':
		condition['$and'].append({'$or': ({'parent': '_'}, {'parent': {'$exists': 0}} )})
	else:
		condition['$and'].append({'parent': parent })
		no_limit = True
	_meta_table = {}
	#это для получение полного метатейбла с полем user чтоб по нему фильтровать.
	for meta in meta_doc['doc']:
		_meta_table[meta['id']] = meta
	user_in_meta = 'user' in _meta_table
	# это получение уже обрезаного мета тейбла.
	_meta_table = {}
	for meta in meta_table:
		_meta_table[meta['id']] = meta
	
	if doc_id != '_':	
		condition['$and'].append({'owner': doc_id})
	if 'date' in meta_table:
		condition['$and'].append({'doc.date': {'$gte': start_date, '$lte': end_date}})
	if user_in_meta and not is_admin(request) and get_const_value(request, 'user_self') == 'yes' :
		condition['$and'].append({'doc.user': "******"+user_name})

	if not 'main' in filter or any(filter['main']) == False and any(filter['column'])==False and (branch_id is None):
		pass
	elif 'main' in filter and any(filter['main']):
		regex = re.compile(u'%s' % filter['main'], re.I | re.UNICODE )
		ors = []
		for field in _meta_table:
			suffix = ''
			if 'is_translate' in _meta_table[field] and _meta_table[field]['is_translate']:
				suffix = '.' + cur_lang(request)
			ors.append({'doc.' + field + suffix: regex})
		condition['$and'].append({'$or': ors})
	elif 'column' in filter and any(filter['column']): #фильтр по колонкам
		for field in filter['column']:
			f = filter['column'][field]
			if not 'val' in f and not 'range' in f: continue
			if _meta_table[field]['type'] == 'date':
				condition['$and'].append({'doc.' + field: {'$gte':f['range']['from'], '$lt':f['range']['to'] }})
				continue
			regex = re.compile(u'%s' % str(f['val']), re.I | re.UNICODE)
			suffix = ''
			if 'is_translate' in _meta_table[field] and (_meta_table[field]['is_translate'] == "true" or
					                                             _meta_table[field]['is_translate'] == True):
				suffix = '.' + cur_lang(request)
			if _meta_table[field]['type'] == 'select':
				suffix = '.' + cur_lang(request)
				ids= []
				rel = _meta_table[field]['relation']
				for res in request.db.doc.find({"doc_type":rel, 'doc.'+('name' if rel == 'des:users' else 'title') + suffix: regex }):
					ids.append(res['_id'])
				condition['$and'].append({'doc.' + field:  {'$in':ids}})
			else:
				if 'str_option' in f and f['str_option'] == 'eq':
					condition['$and'].append({'doc.' + field + suffix: f['val']})
				else:
					regex = re.compile('%s%s%s' % ( ('^' if 'str_option' in f and f['str_option'] == 'start' else ''), f['val'],
					                                (('$' if 'str_option' in f and  f['str_option'] == 'end'  else ''))), re.I | re.UNICODE)
					condition['$and'].append({'doc.' + field + suffix: regex})

	#is_ajax = request.header.get('X-Requested-With') == 'XMLHttpRequest'
	docs_table_count = request.db.doc.find(condition).count()
	docs_table = None
	if no_limit:
		docs_table = request.db.doc.find(condition).sort('doc.date', -1)
	else:
		docs_table = request.db.doc.find(condition).sort('doc.date', -1).skip(skip).limit(limit)
	return list( sort_body(request, proc_id, meta_table, docs_table) ),   docs_table_count
Exemple #14
0
def sandbox(request):
	if is_admin(request):
		return templ('libs.admin:sandbox', request, dict(proc_id='sandbox'))
Exemple #15
0
def test_test(request):
	if is_admin(request):
		return templ('libs.admin:test_test', request, dict(proc_id='test_test'))
Exemple #16
0
async def table_del_row_post(request):
	data = await request.post()
	# proc_id = data['proc_id'] if 'proc_id' in data else None
	proc_id = data.get('proc_id')
	force = data.get('force', False)
	ids =   data.get('ids')
	ids =   json.loads( ids )
	idsn =  data.get('idsn')
	idsn =  json.loads(idsn)

	print( "4444", data['idsn'])

	for doc in request.db.doc.find({'_id': {'$in': idsn}}):
		final = False
		if not 'final' in doc: final = True
		# запрещаем не админу удалять документы созданые админом
		if not force and final and not user_has_permission(request, proc_id, 'delete') or not is_admin(request):
			return {"result": "fail", "error": "You have no permission."}
	return del_row(request, proc_id, ids)
Exemple #17
0
def update_row_(request, proc_id, doc_id, data, parent, noscript=True, no_synh=False, accept_def=False, no_notify=False):
	"""
	:param nouscript:  удаляет теги и стили из текста вроде
	:param no_synh:    не синхронизирует с фейсбуком
	:param accept_def: не публикует документ автоматически, нужно для всяких парсеров
	:param no_notify:
	:return: json format doc[id] proc_id   doc_ = {'body':wiki(body), 'date':date, 'title':title }
	"""

	print('parent', parent)

	doc_meta = get_mt(request, proc_id)
	meta_table = doc_meta['doc']
	doc = get_doc(request, doc_id)
	doc_parent = get_doc(request, parent) if parent != '_' else None
	user = request.db.doc.find_one({'_id':doc['doc']['user']})
	old_row = dict(doc['doc']) # doc из документа который создан create_empty_row_
	#=============================================================================================================================
	for field in meta_table:  # инициализируем поля и устраняем всякие глюки если чегото нет
		if 'is_translate' in field and (field['is_translate'] == True or field['is_translate'] == "true"):
			if not field['id'] in doc["doc"] or type(doc['doc'][field['id']]) != dict: # если в старой записи нет поля или оно не словарь
				doc["doc"][field['id']] = {}
			if not field['id'] in data:  # этот иф можно закоментировать     проверить     если поля нет в новой записи
				data[field['id']] = old_row[field['id']][cur_lang(request)] if field['id'] in old_row and old_row[field['id']] and cur_lang(request) in old_row[field['id']] else ''
			doc["doc"][field['id']][cur_lang(request)] = data[field['id']]
		else:
			if field['oncreate'] == 'edit':
				if not field['id'] in data:
					data[field['id']] = ''
				else:
					doc["doc"][field['id']] = data[field['id']]

	#===================================================================================================================
	if 'body' in doc['doc']:    # очищаем  боди от всякой ерунды
		text = doc['doc']['body'][cur_lang(request)] if  type(doc['doc']['body']) == dict else doc['doc']['body']
		text = re.sub(r'<!--(.|\n)*?-->', '', text)
#		if noscript or True: #==========================================================================================
		if noscript and not is_admin(request):
			text = no_script(text, True)
		if type(doc['doc']['body'] ) == dict:
			doc['doc']['body'][cur_lang(request)] = text
		else: doc['doc']['body'] = text

	#===================================================================================================================
	# if res == 'ok':  # если поле
	doc['doc_type'] = proc_id
#		if not is_admin:


	#сохранение единственого материала для отображения единственого автора в колонке
	if 'last_art' in doc['doc'] and  doc['doc']['last_art'] == 'true':
		for res in request.db.doc.find({'doc_type':proc_id, 'doc.user':doc['doc']['user'], 'doc.last_art':'true'}):
#			for res in db.doc.find({'doc_type':{'$ne':':'}, 'doc.user':doc['doc']['user'], 'doc.last_art':'true'}):
			res['doc']['last_art'] = 'false'
			request.db.doc.save(res)
	#сохранение для разрешенного пользователя
	if is_admin(request) or accept_def or proc_id == 'des:obj' and 'accept' in user['doc'] and user['doc']['accept'] == 'true':
		doc['doc']['accept'] = 'true'
	else: doc['doc']['accept'] = 'false'

	save_auto_tags(request, doc,'tags_'+proc_id[4:]) # автоопределение тегов  получаем текст и сравниваем его с с теми тегами которые уже есть и вычленяем их из него
	save_tags(request, doc, 'tags_'+proc_id[4:])

	#сохранение для разрешенного пользователя
	if accept_def or proc_id == 'des:obj' and 'primary' in user['doc'] and user['doc']['primary'] == 'true':
		doc['doc']['primary'] = 'true'
	else: doc['doc']['primary'] = 'false'

	if 'parent_id' in data and data['parent_id']:
		parent_id = data['parent_id']
		# Удаляем из старого родителя
		request.db.doc.update({'child':{'$in':[doc_id]}}, {'$pull':{'child':doc_id}})
		# Добавляем в нового родителя
		# if parent_id !='_': db.doc.update({'_id':parent_id}, {'$push':{'child':doc_id}})
		request.db.doc.update({'_id':parent_id}, {'$push':{'child':doc_id}})
		# Добавляем себе нового родителя
		doc['parent'] = parent_id
	else:
		doc['parent'] = parent
		if doc_parent: # тут мы получили родительский документ и смотрим если в нем нет себя ребенка то мы себя заносим
			if not 'child' in doc_parent: doc_parent['child'] = []
			doc_parent['child'].append(doc_id)
			request.db.doc.save(doc_parent)

	request.db.doc.update({'_id':doc_id}, doc)

	# =======================================================================
	res, err = event('on_update_row', proc_id, doc_id)
	if res != 'ok': return {"result":"fail", "error":json.dumps(err)}
	# =======================================================================

	doc['final'] = 1

	from core.core import get_settings

	if get_settings('notify_user', False) and check_pub_doc(doc) and proc_id in ['des:obj', 'des:radio', 'des:comments']: subscribe(doc)
	if not no_notify and get_settings('notify_admin', False) and proc_id in ['des:obj', 'des:radio', 'des:comments']: notify_admin(doc)


	if res == 'ok' and 'owner' in doc and doc['owner'] != '_':
		on_update_subtable(request, doc)

	from core.union import clean_cache
	from libs.sites.sites import wiki
	clean_cache(doc)

	doc_ = {'body':wiki(request, ct(request, doc['doc']['body'])), 'date':doc['doc']['date'], 'title':ct(request, doc['doc']['title']) }
	return {"result":"ok", "doc_id":doc['_id'], "proc_id":proc_id, "updated":"", "doc":doc_}
Exemple #18
0
def add_vote_comm_post(request):
    """Вычисляем данные в посте сколько проголосовало и тд."""
    data = request.post()
    vote = data.get('vote')
    comm_id = data.get('comm_id')
    comm = get_doc(comm_id)

    # doc =  db.tree.find_one({'owner':doc_id})
    user = get_current_user(True)
    from libs.sites.sites import check_time
    # comm = doc['tree'][comm_id]

    if check_time(comm['doc']['date'], 'days',
                  int(get_const_value(request, 'vote_timeout'))):
        return response_json(request, {
            "result": "fail",
            "error": "Голосование уже закончилось"
        })
    if not 'vote' in comm:
        comm['vote'] = {
            "score": 0,
            "votes_count": 0,
            "votes_count_plus": 0,
            "votes_count_minus": 0,
            "voted": {}
        }
    if not user_has_permission(request, 'des:obj', 'vote_com'):
        return response_json(request, {
            "result": "fail",
            "error": "Не имеете права голоса"
        })
    if not is_admin(request) and user in comm['vote']['voted']:
        return response_json(request, {
            "result": "fail",
            "error": "Повторное голосование запрещено"
        })
    if not is_admin(request) and user == 'user:'******'title']):
        return response_json(request, {
            "result": "fail",
            "error": "Голосовать за себя запрещено"
        })

    dt = datetime.today().strftime('%Y-%m-%d')
    user_f = get_doc(request, user)
    if not 'vote' in user_f: user_f['vote'] = {}
    if not dt in user_f['vote']: user_f['vote'][dt] = {'up': 0, 'down': 0}

    if not is_admin(request) and int(user_f['vote'][dt]['up']) + int(
            user_f['vote'][dt]['down']) >= int(
                float(user_f['doc']['rate']) + 1.25):
        return response_json(request, {
            "result": "fail",
            "error": "Лимит голосов за сегодня исчерпан"
        })

    user_f['vote'][dt][vote] += 1
    request.db.doc.save(user_f)

    comm['vote']['voted'][user] = vote
    if vote == 'up':
        comm['vote']['score'] += 1
        comm['vote']['votes_count_plus'] += 1
    else:
        comm['vote']['score'] -= 1
        comm['vote']['votes_count_minus'] += 1
    comm['vote']['votes_count'] += 1
    request.db.doc.save(comm)
    comm_vote = comm['vote']

    # начисление балов пользователю
    # u_id = 'user:'******'title'])
    u_id = ct(request, comm['doc']['user'])
    u = get_doc(request, u_id)
    if u:
        if not 'rate' in u['doc']:
            u['doc']['rate'] = '0'
            request.db.doc.save(u)
        if float(u['doc']['rate']) >= 17:
            rate = float(u['doc']['rate']) + (0.02 if vote == 'up' else -0.1)
        else:
            rate = float(u['doc']['rate']) + (0.2 if vote == 'up' else -0.1)
        #	rate =+ 1 if vote == 'up' else -1
        update_cell(request, str(u_id), 'des:users', 'rate', str(rate))

    return response_json(
        request, {
            "result": "ok",
            "score": comm_vote["score"],
            "votes_count": comm_vote["score"],
            "charge_string": "",
            "sign": "positive",
            "votes_count_plus": comm_vote["votes_count_plus"],
            "votes_count_minus": comm_vote["votes_count_minus"],
            "is_positive": True
        })
Exemple #19
0
def add_func(request):
	if is_admin(request):
		return templ('libs.admin:add_func', request, dict(proc_id='add_func'))
Exemple #20
0
def add_func(request):
	if is_admin(request):
		return templ('libs.auth:conf_', request, {"proc_id":'add_func'})