def get(self, domain_identifier, task_identifier): task = api.get_task(domain_identifier, task_identifier) if not task: self.error(404) return session = Session(writer='cookie', wsgiref_headers=self.response.headers) user = api.get_user() domain = api.get_domain(domain_identifier) subtasks = api.get_all_subtasks(domain_identifier, task) parent_task = task.parent_task parent_identifier = parent_task.identifier() if parent_task else "" parent_title = parent_task.title() if parent_task else "" template_values = { 'domain_name': domain.name, 'domain_identifier': domain_identifier, 'user_name': user.name, 'user_identifier': user.identifier(), 'messages': get_and_delete_messages(session), 'task_title' : task.title(), 'task_description': task.description_body(), 'task_assignee': assignee_description(task), 'task_identifier': task.identifier(), 'task_can_assign_to_self': api.can_assign_to_self(task, user), 'subtasks': _task_template_values(subtasks, user), 'parent_identifier': parent_identifier, 'parent_title': parent_title, } path = os.path.join(os.path.dirname(__file__), 'templates/taskdetail.html') self.response.out.write(template.render(path, template_values))
def login_user(): user_to_login = json.loads(request.data) email = user_to_login.get("email") password = user_to_login.get("password") user_id = api.get_user(email, password) session['user'] = user_id return "Success"
def txn(): task = api.get_task(domain_identifier, task_identifier) if not task: logging.error("Task '%s/%s' does not exist", domain_identifier, task_identifier) return index = TaskIndex.get_by_key_name(task_identifier, parent=task) if not index: index = TaskIndex(parent=task, key_name=task_identifier) # Get all subtasks. The ancestor queries are strongly # consistent, so when propagating upwards through the # hierarchy the changes are reflected. subtasks = list(Task.all().ancestor(domain_key).filter("parent_task =", task.key())) if not subtasks: # atomic task task.derived_completed = task.completed task.derived_size = 1 task.derived_atomic_task_count = 1 task.derived_has_open_tasks = task.open() assignee_identifier = task.assignee_identifier() if assignee_identifier: index.assignees = [assignee_identifier] if not DEV_SERVER: # Uses a multi entity group transaction to get the name # of the assignee. This is cached in the record for # quick descriptions. assignee = api.get_user(assignee_identifier) name = assignee.name if assignee else "<Missing>" else: name = "temp" task.derived_assignees[task.assignee_identifier()] = { "id": task.assignee_identifier(), "name": name, "completed": int(task.is_completed()), "all": 1, } else: # composite task task.derived_completed = all(t.is_completed() for t in subtasks) task.derived_size = 1 + sum(t.derived_size for t in subtasks) task.derived_atomic_task_count = sum(t.atomic_task_count() for t in subtasks) task.derived_has_open_tasks = any(t.has_open_tasks() for t in subtasks) # Compute derived assignees, and sum the total of all # their assigned and completed subtasks. assignees = {} for subtask in subtasks: subtask_assignees = subtask.derived_assignees for id, record in subtask_assignees.iteritems(): if not id in assignees: assignees[id] = {"id": id, "name": record["name"], "completed": 0, "all": 0} assignees[id]["completed"] += record["completed"] assignees[id]["all"] += record["all"] task.derived_assignees = assignees index.assignees = list(assignees.iterkeys()) task.put() index.completed = task.is_completed() index.has_open_tasks = task.has_open_tasks() index.atomic = task.atomic() index.put() # Propagate further upwards if task.parent_task_identifier(): UpdateTaskCompletion.enqueue(domain_identifier, task.parent_task_identifier(), transactional=True)
def login_user(): user_to_login = json.loads(request.data) logging.info(" called api/in with user") email = user_to_login.get("email") password = user_to_login.get("password") user_id = api.get_user(email, password) session["user"] = user_id login = True print login return "Success"
def post(self): try: domain_id = self.request.get('domain') title = self.request.get('title') except (TypeError, ValueError): self.error(403) return user = api.get_user() domain = api.create_domain(domain_id, title, user) if not domain: self.response.out.write("Could not create domain") return self.response.out.write("Created domain '%s'" % domain.key().name())
def get(self): user = api.get_user() domains = api.get_all_domains_for_user(user) session = Session(writer='cookie', wsgiref_headers=self.response.headers) template_values = { 'username' : user.name, 'domains' : [{ 'identifier': domain.identifier(), 'name': domain.name } for domain in domains], 'messages': get_and_delete_messages(session), } path = os.path.join(os.path.dirname(__file__), 'templates/landing.html') self.response.out.write(template.render(path, template_values))
def post(self): try: domain_id = self.request.get('domain') title = self.request.get('title') except (TypeError, ValueError): self.error(403) return user = api.get_user() domain = api.create_domain(domain_id, title, user) if not domain: self.response.out.write("Could not create domain") return session = Session(writer='cookie', wsgiref_headers=self.response.headers) add_message(session, "Created domain '%s'" % domain.key().name()) self.redirect('/d/%s/' % domain.key().name())
def mail_responder(event, _): """ Main entry point to handle the feedback form :param event: information about the email :return: True when successful, False otherwise """ logger.info('%s: Request received:%s', __name__, str(event['Records'][0]['eventSource'])) try: (source_email, recipient) = parse_ses_notification(event['Records'][0]['ses']) except Exception: logger.error('Error parsing received Email') return False LANG = CONFIG['LANG'] logger.debug('Source Email {} recipient {}'.format(source_email, recipient)) if recipient == CONFIG['TEST_EMAIL']: feedback.send_email(CONFIG['REPLY_EMAIL'], source_email, TEMPLATES['EMAIL_SUBJECT'], 'a', 'a', '', None, CONFIG['FEEDBACK_EMAIL']) return True elif recipient == CONFIG['TEST_EMAIL_NEW']: email_key(source_email, 'https://example.com') return True elif recipient == CONFIG['REPLY_EMAIL']: logger.info('Response to no-reply ignored') return True elif recipient == CONFIG['DELETE_USER_EMAIL']: try: deleted = api.delete_user(user_id=source_email) except Exception: email(source_email, 'try_again.j2') return False if deleted: email(source_email, 'unsubscribed.j2') return False elif recipient == CONFIG['GET_EMAIL']: try: user_exist = api.get_user(source_email) except Exception: logger.error('API error when checking {}'.format(source_email)) email(source_email, 'try_again.j2') return False if not user_exist: try: api.create_user(source_email, 'EM') except Exception: logger.error('API error when Creating {}'.format(source_email)) email(source_email, 'try_again.j2') return False try: new_key = api.get_new_key(user_id=source_email) except Exception: logger.error( 'API error when getting key fo {}'.format(source_email)) email(source_email, 'try_again.j2') return False if not new_key: email(source_email, 'no_key.j2') return False awsurl = ((CONFIG['OUTLINE_AWS_URL']).format( urllib.parse.quote(new_key))) email_key(source_email, awsurl) return True
def account(user_id): user = get_user(user_id) orders = get_user_orders(user_id) return render_template('account.html', user=user, orders=orders)
def bot_handler(event, _): """ Main entry point to handle the bot param event: information about the chat :param _: information about the telegram message (unused) """ logger.info("%s:%s Request received:%s", __name__, str(time.time()), str(event)) try: default_language = event["lang"] logger.info("Language is %s", event["lang"]) except KeyError: default_language = "fa" logger.info("Language is not defined!") try: token = event['token'] except KeyError: logger.error("Token is not defined!") return None try: tmsg = TelegramMessage(event, default_language) logger.info("TMSG object: {}".format(tmsg)) except Exception as exc: logger.error('Error in Telegram Message parsing {} {}'.format( event, str(exc))) return None preferred_lang = dynamodb.get_user_lang(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id) if (preferred_lang is None or preferred_lang not in CONFIG['SUPPORTED_LANGUAGES']): preferred_lang = default_language current_language = CONFIG['SUPPORTED_LANGUAGES'].index(preferred_lang) logger.info('User language is {}'.format(preferred_lang)) change_lang(preferred_lang) tmsg.lang = preferred_lang if tmsg.body == globalvars.lang.text('MENU_BACK_HOME'): telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) return if tmsg.command == CONFIG['TELEGRAM_START_COMMAND'] and len( tmsg.command_arg) > 0: tmsg.command = "" tmsg.body = base64.urlsafe_b64decode(tmsg.command_arg) # Check for commands (starts with /) if tmsg.command == CONFIG["TELEGRAM_START_COMMAND"]: dynamodb.create_chat_status(CONFIG['DYNAMO_TABLE'], tmsg.chat_id, STATUSES['START']) telegram.send_message( token, tmsg.chat_id, globalvars.lang.text("MSG_INITIAL_SCREEN").format( CONFIG['VERSION'])) keyboard = make_language_keyboard() telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_SELECT_LANGUAGE'), keyboard) save_chat_status(tmsg.chat_id, STATUSES['SET_LANGUAGE']) return None elif tmsg.command == CONFIG['TELEGRAM_ADMIN_COMMAND']: chat_status = int( dynamodb.get_chat_status(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id)) if not admin_menu(token, tmsg, chat_status): telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME'), globalvars.HOME_KEYBOARD) return None # non-command texts elif tmsg.command == '': # This is a message not started with / chat_status = int( dynamodb.get_chat_status(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id)) if chat_status >= STATUSES['ADMIN_SECTION_HOME']: if not admin_menu(token, tmsg, chat_status): telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME'), globalvars.HOME_KEYBOARD) return None elif chat_status == STATUSES['SET_LANGUAGE']: if (tmsg.body is None or tmsg.body not in globalvars.lang.text('SUPPORTED_LANGUAGES')): message = globalvars.lang.text('MSG_LANGUAGE_CHANGE_ERROR') else: new_lang = CONFIG['SUPPORTED_LANGUAGES'][globalvars.lang.text( 'SUPPORTED_LANGUAGES').index(tmsg.body)] dynamodb.save_user_lang(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id, language=new_lang) change_lang(new_lang) message = globalvars.lang.text('MSG_LANGUAGE_CHANGED').format( tmsg.body) telegram.send_message(token, tmsg.chat_id, message) try: user_exist = api.get_user(tmsg.user_uid) except Exception: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None if not user_exist: choices, a, b = get_choice(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id) if choices: keyboard = telegram.make_keyboard(choices, 2, '') telegram.send_keyboard( token, tmsg.chat_id, "{}\n{} + {}:".format( globalvars.lang.text("MSG_ASK_CAPTCHA"), a, b), keyboard) save_chat_status(tmsg.chat_id, STATUSES['FIRST_CAPTCHA']) else: telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) return None elif chat_status == STATUSES['FIRST_CAPTCHA']: check = check_captcha(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id, sum=int(tmsg.body)) if check: tos = get_tos_link() pp = get_pp_link() if tos is not None: telegram.send_message(token, tmsg.chat_id, tos) if pp is not None: telegram.send_message(token, tmsg.chat_id, pp) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text("MSG_OPT_IN"), globalvars.OPT_IN_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['OPT_IN']) else: telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_WRONG_CAPTCHA')) choices, a, b = get_choice(table=CONFIG["DYNAMO_TABLE"], chat_id=tmsg.chat_id) if choices: keyboard = telegram.make_keyboard(choices, 2, '') telegram.send_keyboard( token, tmsg.chat_id, "{}\n{} + {}:".format( globalvars.lang.text("MSG_ASK_CAPTCHA"), a, b), keyboard) save_chat_status(tmsg.chat_id, STATUSES['FIRST_CAPTCHA']) return None elif chat_status == STATUSES['OPT_IN']: if tmsg.body == globalvars.lang.text( 'MENU_PRIVACY_POLICY_CONFIRM'): try: api.create_user(user_id=tmsg.user_uid) except Exception: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) else: telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text('MSG_PRIVACY_POLICY_DECLINE'), globalvars.OPT_IN_DECLINED_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['OPT_IN_DECLINED']) return None elif chat_status == STATUSES['OPT_IN_DECLINED']: if tmsg.body == globalvars.lang.text('MENU_BACK_PRIVACY_POLICY'): telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text("MSG_OPT_IN"), globalvars.OPT_IN_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['OPT_IN']) elif tmsg.body == globalvars.lang.text( 'MENU_HOME_CHANGE_LANGUAGE'): keyboard = make_language_keyboard() telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text('MSG_SELECT_LANGUAGE'), keyboard) save_chat_status(tmsg.chat_id, STATUSES['SET_LANGUAGE']) return None elif chat_status == STATUSES['HOME']: if tmsg.body == globalvars.lang.text('MENU_HOME_EXISTING_KEY'): try: user_exist = api.get_user(tmsg.user_uid) except Exception: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None if not user_exist: telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_NO_ACCOUNT'), parse='MARKDOWN') telegram.send_message(token, tmsg.chat_id, '/start') return None elif not user_exist['outline_key']: telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_NO_EXISTING_KEY')) else: awsurl = (CONFIG['OUTLINE_AWS_URL'].format( urllib.parse.quote(user_exist['outline_key']))) telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_EXISTING_KEY_A').format( awsurl), parse='MARKDOWN') telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_EXISTING_KEY_B'), parse='MARKDOWN') telegram.send_message(token, tmsg.chat_id, user_exist['outline_key']) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) return None elif tmsg.body == globalvars.lang.text('MENU_CHECK_STATUS'): blocked = False banned = False try: user_info = api.get_outline_user(tmsg.user_uid) vpnuser = api.get_user(tmsg.user_uid) except Exception: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None banned = vpnuser['banned'] telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_ACCOUNT_INFO_BANNED') \ if banned else globalvars.lang.text('MSG_ACCOUNT_INFO_OK') ) if not banned: if user_info is not None: try: serverinfo = api.get_outline_server_info( user_info['server']) except Exception: telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None if serverinfo is not None: blocked = serverinfo['is_blocked'] telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_SERVER_INFO_BLOCKED') \ if blocked else globalvars.lang.text('MSG_SERVER_INFO_OK') ) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) return None elif tmsg.body == globalvars.lang.text('MENU_HOME_NEW_KEY'): try: user_exist = api.get_user(tmsg.user_uid) except Exception: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None if not user_exist: logger.info("New user: {}".format(tmsg.user_uid)) telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_NO_ACCOUNT'), parse='MARKDOWN') telegram.send_message(token, tmsg.chat_id, '/start') return None elif not user_exist['outline_key']: create_new_key(tmsg, token) telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) return None issues_dict = api.get_issues(tmsg.lang) issues = list(issues_dict.values()) keyboard = telegram.make_keyboard(issues, 2, '') telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text("MSG_ASK_ISSUE"), keyboard) save_chat_status(tmsg.chat_id, STATUSES['ASK_ISSUE']) return None elif tmsg.body == globalvars.lang.text('MENU_HOME_FAQ'): telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_FAQ_URL')) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) return None elif tmsg.body == globalvars.lang.text('MENU_HOME_INSTRUCTION'): photo_name = "" with open(photo_name, 'rb') as photofile: telegram.send_photo(token, tmsg.chat_id, photofile.read(), "instructions") telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) return None elif tmsg.body == globalvars.lang.text( 'MENU_HOME_CHANGE_LANGUAGE'): keyboard = make_language_keyboard() telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text('MSG_SELECT_LANGUAGE'), keyboard) save_chat_status(tmsg.chat_id, STATUSES['SET_LANGUAGE']) return None elif tmsg.body == globalvars.lang.text('MENU_HOME_PRIVACY_POLICY'): telegram.send_message(token, tmsg.chat_id, get_pp_link()) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) return None elif tmsg.body == globalvars.lang.text('MENU_HOME_SUPPORT'): telegram.send_message(token, tmsg.chat_id, globalvars.lang.text("MSG_SUPPORT_BOT")) telegram.send_message(token, tmsg.chat_id, CONFIG["SUPPORT_BOT"]) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) return None elif tmsg.body == globalvars.lang.text('MENU_HOME_DELETE_ACCOUNT'): keyboard = telegram.make_keyboard( globalvars.lang.text('MENU_DELETE_REASONS'), 2, globalvars.lang.text('MENU_BACK_HOME')) telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text("MSG_ASK_DELETE_REASONS"), keyboard) save_chat_status(tmsg.chat_id, STATUSES['DELETE_ACCOUNT_REASON']) return None elif chat_status == STATUSES['ASK_ISSUE']: issues_dict = api.get_issues(tmsg.lang) issue_ids = [ key for (key, value) in issues_dict.items() if value == tmsg.body ] if not issue_ids: telegram.send_message( token, tmsg.chat_id, globalvars.lang.text("MSG_UNSUPPORTED_COMMAND")) else: create_new_key(tmsg, token, issue_ids[0]) telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) return None elif chat_status == STATUSES['DELETE_ACCOUNT_REASON']: if tmsg.body in globalvars.lang.text('MENU_DELETE_REASONS'): reason_id = globalvars.lang.text('MENU_DELETE_REASONS').index( tmsg.body) logger.debug( 'user {} wants to delete her account because {}'.format( tmsg.user_uid, tmsg.body)) try: deleted = api.delete_user(user_id=tmsg.user_uid) except Exception: telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR'), globalvars.HOME_KEYBOARD) return None if deleted: telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text("MSG_DELETED_ACCOUNT"), globalvars.BACK_TO_HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['DELETE_ACCOUNT_CONFIRM']) return None else: # unsupported message from user telegram.send_message( token, tmsg.chat_id, globalvars.lang.text("MSG_UNSUPPORTED_COMMAND")) try: user_exist = api.get_user(tmsg.user_uid) except Exception: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None if not user_exist: # start from First step keyboard = make_language_keyboard() telegram.send_keyboard( token, tmsg.chat_id, globalvars.lang.text('MSG_SELECT_LANGUAGE'), keyboard) save_chat_status(tmsg.chat_id, STATUSES['SET_LANGUAGE']) return None else: telegram.send_keyboard(token, tmsg.chat_id, globalvars.lang.text('MSG_HOME_ELSE'), globalvars.HOME_KEYBOARD) save_chat_status(tmsg.chat_id, STATUSES['HOME']) return None
def get_user(username): # For testing return jsonify(api.get_user(username)._user_data)
def test_get_bio(self): user = api.get_user('jawkneelin') self.assertIsNotNone(user.get_bio())
def user(username): return api.get_user(username)
def openprofile(self): profileroot = Toplevel() rantapp = profileview.profileview(profileroot,api.get_user(self.rant["rant"]["user_id"])) profileview.mainloop()
def txn(): task = api.get_task(domain_identifier, task_identifier) if not task: logging.error("Task '%s/%s' does not exist", domain_identifier, task_identifier) return index = TaskIndex.get_by_key_name(task_identifier, parent=task) if not index: index = TaskIndex(parent=task, key_name=task_identifier) # Get all subtasks. The ancestor queries are strongly # consistent, so when propagating upwards through the # hierarchy the changes are reflected. subtasks = list(Task.all().ancestor(domain_key).filter( 'parent_task =', task.key())) if not subtasks: # atomic task task.derived_completed = task.completed task.derived_size = 1 task.derived_atomic_task_count = 1 task.derived_has_open_tasks = task.open() assignee_identifier = task.assignee_identifier() if assignee_identifier: index.assignees = [assignee_identifier] if not DEV_SERVER: # Uses a multi entity group transaction to get the name # of the assignee. This is cached in the record for # quick descriptions. assignee = api.get_user(assignee_identifier) name = assignee.name if assignee else '<Missing>' else: name = 'temp' task.derived_assignees[task.assignee_identifier()] = { 'id': task.assignee_identifier(), 'name': name, 'completed': int(task.is_completed()), 'all': 1 } else: # composite task task.derived_completed = all(t.is_completed() for t in subtasks) task.derived_size = 1 + sum(t.derived_size for t in subtasks) task.derived_atomic_task_count = sum(t.atomic_task_count() for t in subtasks) task.derived_has_open_tasks = any(t.has_open_tasks() for t in subtasks) # Compute derived assignees, and sum the total of all # their assigned and completed subtasks. assignees = {} for subtask in subtasks: subtask_assignees = subtask.derived_assignees for id, record in subtask_assignees.iteritems(): if not id in assignees: assignees[id] = { 'id': id, 'name': record['name'], 'completed': 0, 'all': 0 } assignees[id]['completed'] += record['completed'] assignees[id]['all'] += record['all'] task.derived_assignees = assignees index.assignees = list(assignees.iterkeys()) task.put() index.completed = task.is_completed() index.has_open_tasks = task.has_open_tasks() index.atomic = task.atomic() index.put() # Propagate further upwards if task.parent_task_identifier(): UpdateTaskCompletion.enqueue(domain_identifier, task.parent_task_identifier(), transactional=True)
def test_get_num_followers(self): user = api.get_user('jawkneelin') self.assertIsNotNone(user.get_num_followers())
def testGetUser(self): email = "*****@*****.**" password = "******" self.assertEqual(api.get_user(email, password), 84)
def testGetUserFail(self): email = "*****@*****.**" password = "******" self.assertEqual(api.get_user(email, password), "User does not exist.")
import api import json import sys import scrapers.shared as shared test_userdata_file = 'test-userdata.json' test_projectdata_file = 'test-projectdata.json' userdata = api.get_user('vala') projectdata = api.get_project('cat-house') def compare_data(filename, data): with open(filename) as file: testdata = json.load(file) a, b = json.dumps(testdata, sort_keys=True), json.dumps(data, sort_keys=True) if a != b: print(a) print(b) return False return True def dump_data(): test_userdata = json.dumps(userdata, indent=4, sort_keys=True) test_projectdata = json.dumps(projectdata, indent=4, sort_keys=True) with open(test_userdata_file, 'w') as file: file.write(test_userdata) with open(test_projectdata_file, 'w') as file: file.write(test_projectdata) sys.exit(0) # dump_data()
async def recommend_map(ch, username): if '(' in username: username = username[:username.index('(')].strip() api.refresh_token() counter = 0 user = None while counter < 3: try: user = api.get_user(username) break except: counter += 1 if not user: await send_error_message(ch, f'User **{username}** not found.') return scores = None while counter < 3: try: scores = api.get_scores(user['id'], limit=50) break except: counter += 1 if not scores: await send_error_message( ch, f'Error fetching scores for user **{username}**. Please try again later.' ) return counter = 0 score_index = 0 sim = None while counter < 5: score_index = random.randrange(min(25, len(scores))) sim = similarity_srs.get_similar(scores[score_index]['beatmap']['id'], 100, scores[score_index]['mods']) if sim: break counter += 1 if not sim: await send_error_message( ch, f'Error finding map recommendations for user **{username}**. Please try again later.' ) return score_ids = set(score['beatmap']['id'] for score in scores) farm_maps = [] for i in range(len(sim)): map_id = file_to_id(sim[i][0]) if not map_id or int(map_id) in score_ids: continue if map_freq.get(map_id, 0) >= 150: # frequency threshold farm_maps.append(i) if not farm_maps: index = 0 else: index = farm_maps[random.randrange(0, min(len(farm_maps), 50))] color = discord.Color.from_rgb(100, 255, 100) modstr = ' +' + ''.join( scores[score_index]['mods']) if scores[score_index]['mods'] else '' description = f'**{sim[index][0]}**{modstr}\n{file_to_link(sim[index][0])}' embed = discord.Embed(description=description, color=color) embed.set_footer(text=f'Recommended map for {user["username"]}') await ch.send(embed=embed)
def refresh_data(self): self.data = get_user() self.total_pages = len(self.data) / Table.rows_per_page self.page = 0
async def start_quiz(ch, au, params): if ch.id in active_quizzes: return active_quizzes[ch.id] = {} q = active_quizzes[ch.id] q['first'] = 'first' in params q['diff'] = 'diff' in params pool = [] difficulties = [] if q['diff']: easy, medium, hard, impossible, iceberg = easy_diffs, medium_diffs, hard_diffs, impossible_diffs, iceberg_diffs else: easy, medium, hard, impossible, iceberg = easy_sets, medium_sets, hard_sets, impossible_sets, iceberg_sets if 'topplays' in params and not q['diff']: usernames = None i = params.index('topplays') if i + 8 < len(params): bracket = params[i + 8] brackets = {'(': ')', '[': ']', '{': '}'} if bracket in brackets: usernames = params[i + 9:] if brackets[bracket] not in usernames: active_quizzes.pop(ch.id) return usernames = usernames[:usernames.index(brackets[bracket] )].split(',') for i in range(len(usernames)): usernames[i] = usernames[i].strip() api.refresh_token() if not usernames: username = au.display_name if '(' in username: username = username[:username.index('(')].strip() usernames = [username] users = [] for username in usernames: try: user = api.get_user(username) users.append(user) except: await send_error_message(ch, f'User **{username}** not found.') active_quizzes.pop(ch.id) return for i in range(len(users)): user = users[i] try: scores = api.get_scores(user['id'], limit=50, offset=0) + api.get_scores( user['id'], limit=50, offset=50) except: await send_error_message( ch, f'Error fetching scores for user **{usernames[i]}**. Please try again later.' ) active_quizzes.pop(ch.id) return score_ids = list( set(score['beatmap']['beatmapset_id'] for score in scores)) pool.extend(score_ids) difficulties.append('Top plays') else: if 'easy' in params: pool.extend(easy) difficulties.append('Easy') if 'medium' in params: pool.extend(medium) difficulties.append('Medium') if 'hard' in params: pool.extend(hard) difficulties.append('Hard') if 'impossible' in params: pool.extend(impossible) difficulties.append('Impossible') if 'iceberg' in params: pool.extend(iceberg) difficulties.append('Iceberg') if not pool: pool = easy difficulties = ['Easy'] mapset_ids = [] while len(mapset_ids) < 10: selected = pool[random.randrange(len(pool))] if selected not in mapset_ids: mapset_ids.append(selected) api.refresh_token() mapset_infos = [] i = 0 while i < len(mapset_ids): try: if q['diff']: mapset_infos.append(api.get_beatmap(mapset_ids[i])) else: mapset_infos.append(api.get_beatmapset(mapset_ids[i])) i += 1 except: continue answers = [] images = [] for mi in mapset_infos: name = mi['beatmapset']['title'] if q['diff'] else mi['title'] namesplit = name.split(' ') for i in range(1, len(namesplit)): if any(namesplit[i].startswith(c) for c in '~([-<') \ or any(alphanumeric(namesplit[i].lower()) == s for s in ['ft', 'feat', 'featuring']) \ or any(namesplit[i].lower().startswith(s) for s in ['ft.', 'feat.', 'featuring.']) \ or 'tv' in namesplit[i].lower(): name = ''.join(namesplit[:i]) break if any(c in namesplit[i] for c in '~([<'): for c in '~([<': if c in namesplit[i]: namesplit[i] = namesplit[i][:namesplit[i].index(c)] name = ''.join(namesplit[:i + 1]) break answers.append(alphanumeric(name.lower())) images.append( f'**[{mi["version"]}]**' if q['diff'] else mi['covers']['cover']) q['answers'] = answers q['scores'] = {} guess_time = 10 if q['diff']: await ch.send( 'Welcome to the osu! beatmap quiz! You will be given a series of difficulty names; try to type ' 'the title of the beatmap as quickly as possible.\n\n' f"Current settings: {'+'.join(difficulties)}, 10 songs, {guess_time}s guess time, {'first-guess' if q['first'] else 'time-based'} scoring\n\n" 'First difficulty name will appear in 5 seconds!') else: await ch.send( 'Welcome to the osu! beatmap quiz! You will be given a series of beatmap backgrounds; try to type ' 'the title of the beatmap as quickly as possible.\n\n' f"Current settings: {'+'.join(difficulties)}, 10 songs, {guess_time}s guess time, {'first-guess' if q['first'] else 'time-based'} scoring\n\n" 'First background will appear in 5 seconds!') await asyncio.sleep(5) if ch.id not in active_quizzes: return for i in range(len(answers)): q['index'] = i q['window'] = (time.time(), time.time() + guess_time) q['curr_scores'] = {} await ch.send(images[i]) if q['first']: for _ in range(guess_time): if q['curr_scores']: break await asyncio.sleep(1) else: await asyncio.sleep(guess_time) if ch.id not in active_quizzes: return output = f"The answer was: {mapset_infos[i]['beatmapset']['title'] if q['diff'] else mapset_infos[i]['title']}\n" if q['curr_scores']: output += '\n' + '\n'.join( f"{au.display_name}: {q['curr_scores'][au]}" for au in q['curr_scores']) + '\n' if i < len(answers) - 1: output += '\nNext question in 5 seconds.\n' output += '-' * 20 await ch.send(output) for au in q['curr_scores']: if au not in q['scores']: q['scores'][au] = 0 q['scores'][au] += q['curr_scores'][au] if i < len(answers) - 1: await asyncio.sleep(5) if ch.id not in active_quizzes: return scores = list(q['scores'].items()) scores.sort(key=lambda s: -s[1]) output = 'Final standings:\n' icons = {0: ':first_place:', 1: ':second_place:', 2: ':third_place:'} output += '\n'.join( f"{icons.get(i, '')}{scores[i][0].display_name}: {scores[i][1]}" for i in range(len(scores))) await ch.send(output) active_quizzes.pop(ch.id)
def get_current_user(): user_email = request.args['user_email'] access_token = session['google_token'] jwt_token = get_token(access_token) user = get_user(user_email, jwt_token) return json_response({'value': user})
def put(self): uuid = self.request.get('group_uuid') name = self.request.get('name') admin_ids = self.request.get_all('admin_uuid') member_ids = self.request.get_all('member_uuid') public = self.request.get('public') if not uuid: api.write_error(self.response, 400, 'Missing required parameter, group_uuid') return user = api.get_user(self.request) if not user: api.write_error(self.response, 403, 'Unknown or missing user') return group = Group.query(Group.uuid == uuid).get() if not group: api.write_error(self.response, 404, 'Unknown or missing group') return if not user.key in group.admins: api.write_error(self.response, 403, 'User not allowed to update group') return if name: group.name = name if 'public' in self.request.params and not public == '': group.public = public.lower() in ("yes", "true", "t", "1", "on") for admin_id in admin_ids: remove_user = False if admin_id and admin_id[0] == '-': remove_user = True admin_id = admin_id[1:] admin = User.query(User.uuid == admin_id).get() if admin: if remove_user and admin.key in group.admins: if len(group.admins) > 1: group.admins.remove(admin.key) else: api.write_error(self.response, 403, 'Cannot remove last admin') return elif not admin.key in group.admins: group.admins.append(admin.key) else: logging.warn('Unknown user %s' % (admin_id)) for member_id in member_ids: remove_user = False if member_id and member_id[0] == '-': remove_user = True member_id = member_id[1:] member = User.query(User.uuid == member_id).get() if member: if remove_user and member.key in group.members: group.members.remove(member.key) elif not member.key in group.members: group.members.append(member.key) else: logging.warn('Unknown user %s' % (member_id)) group.put() if group.public: api.search.update_public_index(group) else: api.search.update_private_index(group, user.uuid) api.write_message(self.response, 'Updated group', extra={'groups' : [ get_group_json(group) ]})