def admin(): global LIBERADO, KEY msg = False link = False # valores dos usuários para depurar userValue = USERS.keys()[0] if DEBUG else '' passValue = USERS[userValue] if DEBUG else '' if request.method == 'POST': login = request.form['login'] password = request.form['password'] horas = request.form['horas'] KEY = request.form['key'] if canLogin(login, password): LIBERADO = datetime.now() + timedelta(hours=float(horas)) msg = 'Sucesso!' link = '/?key=' + KEY else: msg = 'Falha no login' return render_template('admin.html', liberado=LIBERADO.strftime("%Y-%m-%d %H:%M"), msg=msg, maxtimeopen=MAXTIMEOPEN, key=KEY, link=link, userValue=userValue, passValue=passValue)
def process_lab_remove_info(message): global Q, queue_name, bot, state_table username = message.from_user.username chat_id = message.chat.id is_admin = username in ADMIN_USER is_student = USERS.get(username) is not None lab = None try: lab = int(message.text.strip()) if lab <= 0: lab = None raise ValueError("Lab number must be greater than 0") except ValueError: bot.send_message(chat_id, "Неправильный формат ввода.") if lab is not None: query = Q.record_present(username, lab) if query is not None: Q.remove(username, lab) update_backup() bot.send_message( chat_id, "Ваша запись удалена. Теперь вы не сдаёте лабу номер " + str(lab)) else: bot.send_message(chat_id, "Ты эту лабу и так не сдаёшь!") state_table[username] = BotState.READING_COMMAND
def addUsers(self): self.loginAsPortalOwner() # Add all users self.membership = getToolByName(self.portal, 'portal_membership', None) for user_id in USERS.keys(): self.membership.addMember(user_id, USERS[user_id]['passw'] , USERS[user_id]['roles'], []) # Add users to Discussion Manager group portal_groups = getToolByName(self.portal, 'portal_groups') dm_group = portal_groups.getGroupById('DiscussionManager') dm_users = [dm_group.addMember(u) for u in DM_USERS_IDS]
def get_user_rating(username, lab): name = USERS.get(username) if name is None: raise ValueError("User @" + username + "is not registered") elif lab <= 0: raise ValueError("Lab id must be positive") elif lab > len(leaderboard): raise LeaderboardLabError(username, lab) elif name not in leaderboard[lab - 1]: raise LeaderboardUserError(username, lab) else: return leaderboard[lab - 1][name]
def print_tg_info(): my_ip = socket.gethostbyname(socket.gethostname()) octets = [int(o) for o in my_ip.split(".")] ip_is_local = (len(octets) == 4 and (octets[0] in [127, 10] or octets[0:2] == [192, 168] or (octets[0] == 172 and 16 <= octets[1] <= 31))) if ip_is_local: my_ip = "YOUR_IP" for user, secret in USERS.items(): params = {"server": my_ip, "port": PORT, "secret": secret} print("tg://proxy?" + urllib.parse.urlencode(params), flush=True)
def process_new_queue_name(message): global Q, queue_name, bot, state_table username = message.from_user.username chat_id = message.chat.id is_admin = username in ADMIN_USER is_student = USERS.get(username) is not None Q = Queue() update_backup() queue_name = message.text bot.send_message(chat_id, "Название очереди изменено на `" + queue_name + "`") state_table[username] = BotState.READING_COMMAND
def testViewRepliesPublishedAllUsers(self): # All users MUST VIEW PUBLISHED comments # Get any document and publish it's comment doc = getattr(self.portal, 'doc_%s' % 'dm_admin') self.login('dm_admin') di = self.discussion.getDiscussionFor(doc).getReplies()[0] di.discussion_publish_comment() all_users_id = USERS.keys() + ['anonym'] for u in all_users_id: self.logout() if not u=='anonym': self.login(u) replies = self.discussion.getDiscussionFor(doc).getReplies() self.failUnless(replies, "Viewing PUBLISHED discussion item forbiden for %s user" % u)
def process_command(message): global Q, queue_name, bot, state_table, handing_stats username = message.from_user.username chat_id = message.chat.id is_admin = username in ADMIN_USER is_student = USERS.get(username) is not None is_teacher = False if message.text == create_new_queue_cmd and is_admin: bot.send_message(chat_id, "Введите название очереди:") state_table[username] = BotState.READING_QUEUE_NAME elif message.text == show_current_queue_cmd and (is_admin or is_student): log_queue(chat_id) elif message.text == add_to_queue_cmd and is_student: bot.send_message(chat_id, "Введите номер лабы, на которую хотите записаться") state_table[username] = BotState.READING_LAB_APPEND_DATA elif message.text == leave_queue_cmd and is_student: bot.send_message(chat_id, "Введите номер лабы, запись которой надо убрать") state_table[username] = BotState.READING_LAB_REMOVE_DATA elif message.text == show_position and is_student: query = Q.record_present(username, None) if query is None: bot.send_message(chat_id, "Тебя нет в очереди") else: bot.send_message( chat_id, "Ваша позиция в очереди: " + str(query.index + 1) + "!\nЭто Ваша БЛИЖАЙШАЯ позиция в очереди") elif message.text == display_first_cmd and is_teacher: pass elif message.text == show_handing_stats: msg = "Таблица сдачи лаб\n" for (i, b) in enumerate(iter(handing_stats[username])): labN = i + 1 if b: st = "*сдана*" else: st = "*не сдана*" msg += ("Лаба №" + str(labN) + " " + st + "\n") bot.send_message(chat_id, msg, parse_mode="MarkdownV2") else: bot.send_message( chat_id, "Неопознанная команда или у Вас нет прав на такую команду")
def send_welcome(message): username = message.from_user.username chat_id = message.chat.id sti = open("graphics/sticker.webp", "rb") if username in ADMIN_USER: bot.send_message(chat_id, "Привет, admin!") bot.send_sticker(chat_id, sti) # keyboard markup = types.ReplyKeyboardMarkup(row_width=1) item1 = types.KeyboardButton(create_new_queue_cmd) item2 = types.KeyboardButton(show_current_queue_cmd) markup.add(item1, item2, item3, item4) bot.send_message(chat_id, "Выбeрите функцию:", reply_markup=markup) elif USERS.get(username) is not None: bot.send_message(chat_id, "Привет, " + USERS[username] + "!") bot.send_sticker(chat_id, sti) # keyboard markup = types.ReplyKeyboardMarkup(row_width=1) item1 = types.KeyboardButton(show_current_queue_cmd) item2 = types.KeyboardButton(add_to_queue_cmd) item3 = types.KeyboardButton(leave_queue_cmd) item4 = types.KeyboardButton(show_position) markup.add(item1, item2, item3, item4) bot.send_message(chat_id, "Выбeрите функцию:", reply_markup=markup) else: bot.send_message( chat_id, "Привет, я тебя не знаю!\nЯ не умею работать с пользователей, которых не знаю!\nНапиши Никите Пологову, возможно это какая-то ошибка" )
def process_lab_append_info(message): global Q, queue_name, bot, state_table username = message.from_user.username chat_id = message.chat.id is_admin = username in ADMIN_USER is_student = USERS.get(username) is not None lab, rating = None, None try: lab = int(message.text.strip()) if lab <= 0: lab = None raise ValueError("Lab number must be greater than 0") except ValueError: bot.send_message(chat_id, "Неправильный формат ввода.") if lab is not None: query = Q.record_present(username, lab) if query is not None: bot.send_message(chat_id, "Ты уже есть в очереди!") else: try: Q.push(QueueElement(username, lab)) update_backup() bot.send_message(chat_id, "Поздравляю. Ты записан в очередь.") except LeaderboardLabError as err: print("@" + username + "has caused the following error:\n" + str(err)) err_msg = "Приносим свои извинения, но у нас пока не загружена таблица лабы №" + str( lab) + ".\n" + err_msg_ps bot.send_message(chat_id, err_msg) except LeaderboardUserError as err: print("@" + username + "has caused the following error:\n" + str(err)) err_msg = "Приносим свои извинения, но мы не нашли Вас в таблице лабы №" + str( lab) + ".\nВозможно наши данные устарели.\n" + err_msg_ps bot.send_message(chat_id, err_msg) state_table[username] = BotState.READING_COMMAND
def afterSetUp(self): self.loginAsPortalOwner() self.request = self.app.REQUEST # VERY IMPORTANT to guarantee product skin's content visibility self._refreshSkinData() # Add all users self.membership = getToolByName(self.portal, 'portal_membership', None) for user_id in USERS.keys(): self.membership.addMember(user_id, USERS[user_id]['passw'], USERS[user_id]['roles'], []) # Add users to Discussion Manager group portal_groups = getToolByName(self.portal, 'portal_groups') dm_group = portal_groups.getGroupById('DiscussionManager') dm_users = [dm_group.addMember(u) for u in DM_USERS_IDS] # Allow discussion for Document portal_types = getToolByName(self.portal, 'portal_types', None) doc_fti = portal_types.getTypeInfo('Document') doc_fti._updateProperty('allow_discussion', 1) # Make sure Documents are visible by default # XXX only do this for plone 3 self.portal.portal_workflow.setChainForPortalTypes(('Document',), 'plone_workflow') # Add testing documents to portal. Add one document for avery user. # For testing behaviors, where made some changes to document state it's more usefull. self.discussion = getToolByName(self.portal, 'portal_discussion', None) self.all_users_id = DM_USERS_IDS + COMMON_USERS_IDS for user_id in self.all_users_id: doc_id = 'doc_%s' % user_id self.portal.invokeFactory('Document', id=doc_id) doc_obj = getattr(self.portal, doc_id) doc_obj.edit(text_format='plain', text='hello world from %s' % doc_id) # Create talkback for document and Add comment to doc_obj self.discussion.getDiscussionFor(doc_obj) doc_obj.discussion_reply('A Reply for %s' % doc_id,'text of reply for %s' % doc_id)
def testDeleting(self): # Manager with DiscussionManager role CAN delete ANY REPLY. # Manager without DiscussionManager role [common manager] CAN delete ONLY PUBLISHED REPLY. # Get Managers managers = [u for u in USERS.keys() if 'Manager' in USERS[u]['roles']] dm_man = [u for u in managers if u.startswith('dm_')][0] common_man = [u for u in managers if not u.startswith('dm_')][0] # Publish document for common manager self.login(dm_man) doc_obj = getattr(self.portal, "doc_%s" % common_man) reply = self.discussion.getDiscussionFor(doc_obj).getReplies()[0] reply.discussion_publish_comment() # Check for really deleting for u in managers: self.login(u) auth = '%s:%s' % (u,USERS[u]['passw']) doc_id = "doc_%s" % u doc_obj = getattr(self.portal, doc_id) getReplies = self.discussion.getDiscussionFor(doc_obj).getReplies self.failUnless(getReplies(), "%s - user with Manager role not view discussion reply" % u) getReplies()[0].deleteDiscussion() self.failIf(getReplies(), "%s - user with Manager role not really delete discussion" % u)
def get_pw(username): if username in USERS: return USERS.get(username) return None
def __init__(self,user_name,roles:List[Role]=[]): self.user_name=user_name self.roles=roles USERS.append(self)
def load_user(id): return USERS.get(int(id))