def get_self(): """ Endpoint to get the current user information """ user_id = get_jwt_identity() response = get_user({"guid": user_id}) return jsonify(response['payload']), response['status_code']
def push_message(appid, appname, receiver, content, extra, collapse_id=None): u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return push_message_u(appid, appname, u, content, extra, collapse_id=collapse_id)
def handle_voip_message(msg): obj = json.loads(msg) appid = obj["appid"] sender = obj["sender"] receiver = obj["receiver"] appname = get_title(appid) sender_name = user.get_user_name(rds, appid, sender) u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return #找出最近绑定的token ts = max(u.apns_timestamp, u.xg_timestamp, u.ng_timestamp, u.mi_timestamp, u.hw_timestamp, u.gcm_timestamp, u.ali_timestamp) if sender_name: sender_name = sender_name.decode("utf8") content = "%s:%s"%(sender_name, u"请求与你通话") else: content = u"你的朋友请求与你通话" if u.apns_device_token and u.apns_timestamp == ts: sound = "apns.caf" badge = 0 ios_push(appid, u.apns_device_token, content, badge, sound, {}) elif u.mi_device_token and u.mi_timestamp == ts: MiPush.push_message(appid, u.mi_device_token, content) elif u.hw_device_token and u.hw_timestamp == ts: HuaWeiPush.push_message(appid, u.hw_device_token, content) elif u.ali_device_token and u.ali_timestamp == ts: AliPush.push_message(appid, appname, u.hw_device_token, content) else: logging.info("uid:%d has't device token", receiver)
def get(self): user = m_user.get_user(self.db, EMAIL) if user is None: user = { "name": "", "en_name": "", "email": "", "descript": "", "wechat": "", "github": "", "address": "", } else: contact = user["contact"] user = { "name": user["name"], "en_name": user["en_name"], "descript": user["descript"], "email": contact.get("email", ""), "wechat": contact.get("wechat", ""), "github": contact.get("github", ""), "address": contact.get("address", ""), } visitor_num = self.get_visitor_num() self.render("frontend/about.html", user=user, visitor_num=visitor_num, title=ABOUT_TITLE )
async def show_sticker(self, ctx): with session_scope() as session: user = get_user(session, ctx.author.id) if user is None: await ctx.send("아직 스티커를 받지 않았습니다.") return await ctx.send(f"스티커를 `{user.sticker}`장 갖고 있습니다.")
def api_user_authenticate(self): name = self.request.json_body.get('name', '') animal = self.request.json_body.get('spirit_animal', '') user = get_user(self.request, name, animal) if user: return self.ok({'user':self.format_user(user)}) else: return self.error("Username or animal were not correct")
def show_user(username): """Show User Show all ideas that a user as created or posted to; if the user is logged in, then show the stubs they have pinned""" user = get_user(username) if not user.loaded: abort(404) return render_template('user_management/show_user.html', user=user)
def post(self): args=parser.parse_args() try: # user=get_user(user_id=args['user_id']) user=get_user(**args) session['user']=user['id'] return user except: return None
def before_request(): g.db = connect_db() if 'username' in session: from models.user import get_user g.current_user = get_user(session['username']) if not app.config['TESTING'] and request.method == "POST": token = session.pop('_csrf_token', None) if not token or token != request.form.get('_csrf_token'): abort(403)
def userinfo(): form = UserInfoForm() user = get_user(1) if form.validate_on_submit() and user: # 有问题 set_userinfo(user, form.userinfo.data) return redirect(url_for('admin.userinfo')) else: form.userinfo.data = user.raw_markdown return render_template('admin/userinfo.html', form=form, user=user)
def get_current_user(self): sid = self.get_secure_cookie("sid") if not sid: return None # return session.query_sid(self.db, sid) session_doc = session.query_sid(self.db, sid) if not isinstance(session_doc, dict): # Not found user by the sid. return None email = session_doc.get("email", None) if email is None: return None return user.get_user(self.db, email)
async def search_reward(self, ctx, discord_user: discord.User): with session_scope() as session: user = get_user(session, discord_user.id) if user is None or user.formlink is None: await ctx.send( f"{ctx.author.mention}, 해당 사용자는 현물 교환 신청을 안 했습니다.") return url = os.getenv("STICKER_FORM_URL").format( parse.quote(user.get_info())) await ctx.send( f"{ctx.author.mention}, {discord_user.mention}: {url}")
async def reset_sticker(self, ctx, member: discord.Member): with session_scope() as session: user = get_user(session, member.id) if user is None: await ctx.send("가입하지 않은 사용자입니다.") return session.delete(user) self.bot.logger.info("user delete: " + repr(user)) await ctx.send( member.mention + "님의 정보를 삭제했습니다.", allowed_mentions=discord.AllowedMentions.none(), )
def format_spell(self, spell): user = self.format_user(get_user(self.request, spell[0])) setup = json.loads(spell[4]) if spell[4] else None loop = json.loads(spell[5]) if spell[5] else None return { 'user_name': spell[0], 'name': spell[1], 'priority': spell[2], 'cast_time': spell[3], 'setup': setup, 'loop': loop, 'complete': spell[6], 'spell_duration': user['spell_duration'] }
def handle_customer_message(msg): obj = json.loads(msg) if not obj.has_key("appid") or not obj.has_key("command") or \ not obj.has_key("customer_appid") or not obj.has_key("customer") or \ not obj.has_key("seller") or not obj.has_key("content") or \ not obj.has_key("store") or not obj.has_key("receiver"): logging.warning("invalid customer push msg:%s", msg) return logging.debug("customer push msg:%s", msg) appid = obj["appid"] receiver = obj["receiver"] command = obj["command"] customer_appid = obj["customer_appid"] customer = obj["customer"] store = obj["store"] seller = obj["seller"] raw_content = obj["content"] appname = get_title(appid) extra = {} if command == MSG_CUSTOMER: sender_name = user.get_user_name(rds, customer_appid, customer) content = push_content(sender_name, raw_content) push_message(appid, appname, receiver, content, extra) elif command == MSG_CUSTOMER_SUPPORT: if appid == customer_appid and receiver == customer: #客服发给顾客 u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return if u.wx_openid: WXPush.push(appid, appname, u.wx_openid, raw_content) else: extra['store_id'] = store extra['xiaowei'] = {"new":1} store = Store.get_store(rds, store) sender_name = store.name content = push_content(sender_name, raw_content) push_customer_support_message(appid, appname, u, content, extra) else: #群发到其它客服人员 sender_name = user.get_user_name(rds, appid, seller) content = push_content(sender_name, raw_content) push_message(appid, appname, receiver, content, extra)
def register_exts(app: Flask): # flask-sqlalchemy db.init_app(app) # flask-login login = LoginManager(app) login.login_message = None login.login_view = 'admin.login' login.user_loader(lambda user_id: get_user(user_id)) # exts.library from . import library LibraryManager(app, library) # exts.message Message(app)
def handle_system_message(msg): obj = json.loads(msg) appid = obj["appid"] receiver = obj["receiver"] appname = get_title(appid) try: content_obj = json.loads(obj.get('content')) voip_content = content_obj.get('voip_push') content = content_obj.get('push') if not voip_content and not content: return sound = content_obj.get('sound', 'default') except Exception as e: logging.info("exception:%s", e) return u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return #找出最近绑定的token ts = max(u.apns_timestamp, u.xg_timestamp, u.ng_timestamp, u.mi_timestamp, u.hw_timestamp, u.gcm_timestamp, u.ali_timestamp) if u.apns_device_token and u.apns_timestamp == ts: if voip_content and u.pushkit_device_token: IOSPush.voip_push(appid, u.pushkit_device_token, voip_content) elif content: IOSPush.push(appid, u.apns_device_token, content, sound=sound, badge=u.unread + 1) user.set_user_unread(rds, appid, receiver, u.unread + 1) return if not content: return if u.mi_device_token and u.mi_timestamp == ts: MiPush.push_message(appid, u.mi_device_token, content) elif u.hw_device_token and u.hw_timestamp == ts: HuaWeiPush.push_message(appid, u.hw_device_token, content) else: logging.info("uid:%d has't device token", receiver)
def handle_customer_message_v2(msg): obj = json.loads(msg) if "appid" not in obj or "content" not in obj or \ "sender_appid" not in obj or "sender" not in obj or \ "receiver_appid" not in obj or "receiver" not in obj: logging.warning("invalid customer push msg:%s", msg) return logging.debug("customer push msg:%s", msg) appid = obj["appid"] sender_appid = obj["sender_appid"] sender = obj["sender"] receiver_appid = obj["receiver_appid"] receiver = obj["receiver"] raw_content = obj["content"] assert (appid == receiver_appid) extra = {} appname = get_title(appid) u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return if u.wx_openid: result = WXPush.push(appid, appname, u.wx_openid, raw_content) # errcode=45015, # errmsg=response out of time limit or subscription is canceled if result and result.get('errcode') == 45015: now = int(time.time()) content_obj = { "wechat": { "customer_appid": receiver_appid, "customer_id": receiver, "timestamp": now, "notification": "微信会话超时" } } post_system_message(sender_appid, sender, json.dumps(content_obj)) else: extra['xiaowei'] = {"new": 1} sender_name = user.get_user_name(rds, sender_appid, sender) content = push_content(sender_name, raw_content) push_customer_support_message(appid, appname, u, content, extra)
def todo(username): # get user identiy from jwt TODO usr = get_user('admin') if not usr: return jsonify(error=f'Error: did not found user: {username}' ), HTTPStatus.BAD_REQUEST if request.method == 'GET': return show_user_todo_list(usr.id) # POST data = request.get_json() if not data or 'task' not in data: return jsonify( error='expected format {task: value}'), HTTPStatus.BAD_REQUEST task = create_task_by_user_id(data['task'], usr.id) return jsonify(task=f'created new task {task} for user {username}' ), HTTPStatus.CREATED
def sign_up(): """ Sing up new User """ data = request.get_json() if 'username' in data and 'password' in data and 'email' in data: username = data['username'] password = data['password'] email = data['email'] if get_user(username): app.logger.info(f'try to create user that already exist {username} {email}') return jsonify(error='User aleady exist'), HTTPStatus.BAD_REQUEST try: usr = User(username, password, email) db.session.add(usr) db.session.commit() app.logger.info(f'created new user {username} {email}') return jsonify(msg=f'new user has been created {username}'), HTTPStatus.CREATED except SQLAlchemyError as e: app.logger.error(e) return jsonify(error=f'DB error could not create '), HTTPStatus.INTERNAL_SERVER_ERROR else: abort(HTTPStatus.BAD_REQUEST)
appid = obj["appid"] receiver = obj["receiver"] appname = get_title(appid) try: content_obj = json.loads(obj.get('content')) voip_content = content_obj.get('voip_push') content = content_obj.get('push') if not voip_content and not content: return sound = content_obj.get('sound', 'default') except Exception, e: logging.info("exception:%s", e) return u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return #找出最近绑定的token ts = max(u.apns_timestamp, u.xg_timestamp, u.ng_timestamp, u.mi_timestamp, u.hw_timestamp, u.gcm_timestamp, u.ali_timestamp) if u.apns_device_token and u.apns_timestamp == ts: if voip_content and u.pushkit_device_token: IOSPush.voip_push(appid, u.pushkit_device_token, voip_content) elif content: IOSPush.push(appid, u.apns_device_token, content,
def edit_user(username): """Edit User Edit a user profile""" # Must be logged in. if not session.get('logged_in', False): abort(403) # Permission denied unless the user's editing themselves, or it's an admin. if not g.current_user.is_admin() and session['username'] != username: abort(403) user = get_user(username) if not user.loaded: abort(404) if request.method == 'POST': # Update the user with new fields so that form repopulates changed # data. user.display_name = request.form['display_name'] user.blurb = request.form['blurb'] user.artist_type = request.form['artist_type'] if 'user_type' in request.form: user.user_type = int(request.form['user_type']) # Allow password/email editing if it's the current user. if g.current_user.username == user.username: # Check old password. if (not request.form['password'] or not check_password(user.username, request.form['password'])): abort(403) user.email = request.form['email'] new_password = request.form['new_password'] # Set new password if it was provided and matches confirmation; # otherwise, just set the email. if new_password: if new_password != request.form['new_password2']: flash('New password and confirmation mismatch.') return render_template('user_management/edit_user.html', user=user) # TODO validate/confirm email - #29 - Makyo hashword, salt = generate_hashword(new_password) g.db.execute('update auth_users set salt = ?, hashword = ?, ' 'email = ? where username = ?', [base64.b64encode(salt), base64.b64encode(hashword), user.email, username]) else: g.db.execute('update auth_users set email = ? where ' 'username = ?', [user.email, username]) # Set the remainder of the fields and commit. g.db.execute('update auth_users set display_name = ?, blurb = ?, ' 'user_type = ?, artist_type = ? where username = ?', [user.display_name, user.blurb, user.user_type, user.artist_type, user.username]) g.db.commit() flash('Profile updated!') return redirect(url_for('.show_user', username=username)) return render_template('user_management/edit_user.html', user=user)
def POST(self): """ Log in to the web application and register the session :return: The login page showing other users if logged in """ session = web.ctx.session nav = get_nav_bar(session) data = web.input(username="", password="", remember=False) inp = web.input() if not ('csrf_token' in inp and inp.csrf_token == session.pop('csrf_token', None)): raise web.badrequest() # Validate login credential with database query user_exists = models.user.check_user_exists(data.username) print("USEREXIST: {}".format(user_exists)) if not user_exists: # Lockout if too many failed attempts if not (write_to_logins(str(web.ctx['ip']))): return render.login( nav, login_form, "- Too many login attempts in short amount of time") log("LOGIN", web.ctx['ip'], [('Username', data.username), ("Response: ", "Login failed, user does not exist")]) session.csrf_token = uuid4().hex return render.login(nav, login_form, "- User authentication failed", session.csrf_token) user = None stored_password = models.user.get_password_by_user_name(data.username) if (verify_password(stored_password, data.password)): user = models.user.match_user(data.username, stored_password) userid = get_user_id_by_name(data.username) session.unauth_username = data.username session.unauth_userid = userid session.unauth_remember = 1 if data.remember else 0 user = get_user(session.unauth_userid) email = user[0][5] qr_verification_key = get_key(session.unauth_username) if qr_verification_key != None: url = generate_url("beelance", email, qr_verification_key) session.auth_url = url user_is_verified = models.user.check_if_user_is_verified_by_username( data.username) # If there is a matching user/password in the database the user is logged in if user: if not user_is_verified: session.csrf_token = uuid4().hex # Lockout if failed attempts if not (write_to_logins(str(web.ctx['ip']))): return render.login( nav, login_form, "- Too many login attempts in short amount of time", session.csrf_token) log("LOGIN", web.ctx['ip'], [('Username', data.username), ("Password", stored_password), ("Response: ", "Login failed, User not verified")]) return render.login(nav, login_form, "- User not verified", session.csrf_token) if qr_verification_key == None: # Lockout if failed attempts session.csrf_token = uuid4().hex if not (write_to_logins(str(web.ctx['ip']))): return render.login( nav, login_form, "- Too many login attempts in short amount of time", session.csrf_token) log("LOGIN", web.ctx['ip'], [ ('Username', data.username), ("Password", stored_password), ("Response: ", "Login failed, docker might have restarted") ]) return render.login( nav, login_form, "- User authentication failed. This might be because docker demon has restarted", session.csrf_token) else: log("LOGIN", web.ctx['ip'], [('Username', data.username), ("Password", stored_password), ("Response: ", "Login accepted, forwarded to two factor auth")]) raise web.seeother("/qr_verify") else: log("LOGIN", web.ctx['ip'], [('Username', data.username), ("Password", stored_password), ("Response: ", "Login failed, username/password mismatch")]) session.csrf_token = uuid4().hex # Lockout if failed attempts if not (write_to_logins(str(web.ctx['ip']))): return render.login( nav, login_form, "- Too many login attempts in short amount of time", session.csrf_token) return render.login(nav, login_form, "- User authentication failed", session.csrf_token)
def edit_user(username): """Edit User Edit a user profile""" # Must be logged in. if not session.get('logged_in', False): abort(403) # Permission denied unless the user's editing themselves, or it's an admin. if not g.current_user.is_admin() and session['username'] != username: abort(403) user = get_user(username) if not user.loaded: abort(404) if request.method == 'POST': # Update the user with new fields so that form repopulates changed # data. user.display_name = request.form['display_name'] user.blurb = request.form['blurb'] user.artist_type = request.form['artist_type'] if 'user_type' in request.form: user.user_type = int(request.form['user_type']) # Allow password/email editing if it's the current user. if g.current_user.username == user.username: # Check old password. if (not request.form['password'] or not check_password(user.username, request.form['password'])): abort(403) user.email = request.form['email'] new_password = request.form['new_password'] # Set new password if it was provided and matches confirmation; # otherwise, just set the email. if new_password: if new_password != request.form['new_password2']: flash('New password and confirmation mismatch.') return render_template('user_management/edit_user.html', user=user) # TODO validate/confirm email - #29 - Makyo hashword, salt = generate_hashword(new_password) g.db.execute('update auth_users set salt = ?, hashword = ?, ' 'email = ? where username = ?', [salt, hashword, user.email, username]) else: g.db.execute('update auth_users set email = ? where ' 'username = ?', [user.email, username]) # Set the remainder of the fields and commit. g.db.execute('update auth_users set display_name = ?, blurb = ?, ' 'user_type = ?, artist_type = ? where username = ?', [user.display_name, user.blurb, user.user_type, user.artist_type, user.username]) g.db.commit() flash('Profile updated!') return redirect(url_for('.show_user', username=username)) return render_template('user_management/edit_user.html', user=user)
def send_group_message(obj): appid = obj["appid"] sender = obj["sender"] receivers = obj["receivers"] group_id = obj["group_id"] appname = get_title(appid) sender_name = user.get_user_name(rds, appid, sender) content = push_content(sender_name, obj["content"]) try: c = json.loads(obj["content"]) collapse_id = c.get('uuid') if c.has_key('revoke'): collapse_id = c['revoke']['msgid'] sender_name = sender_name if sender_name else '' content = "%s撤回了一条消息" % sender_name at = c.get('at', []) at_all = c.get('at_all', False) except ValueError: at = [] at_all = False collapse_id = None extra = {} extra["sender"] = sender extra["group_id"] = group_id apns_users = [] jp_users = [] xg_users = [] hw_users = [] gcm_users = [] mi_users = [] ali_users = [] # 群聊中被at的用户 at_users = [] for receiver in receivers: quiet = user.get_user_notification_setting(rds, appid, receiver, group_id) if quiet: logging.info("uid:%d group id:%d do not disturb", receiver, group_id) if quiet and receiver not in at: continue u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) continue if (at_all or receiver in at) and sender_name: at_users.append(u) continue # 找出最近绑定的token ts = max(u.apns_timestamp, u.xg_timestamp, u.mi_timestamp, u.hw_timestamp, u.gcm_timestamp, u.ali_timestamp, u.jp_timestamp) if u.apns_device_token and u.apns_timestamp == ts: apns_users.append(u) elif u.xg_device_token and u.xg_timestamp == ts: xg_users.append(u) elif u.mi_device_token and u.mi_timestamp == ts: mi_users.append(u) elif u.hw_device_token and u.hw_timestamp == ts: hw_users.append(u) elif u.gcm_device_token and u.gcm_timestamp == ts: gcm_users.append(u) elif u.ali_device_token and u.ali_timestamp == ts: ali_users.append(u) elif u.jp_device_token and u.jp_timestamp == ts: jp_users.append(u) else: logging.info("uid:%d has't device token", receiver) for u in at_users: content = "%s在群聊中@了你" % sender_name push_message_u(appid, appname, u, content, extra) for u in xg_users: xg_push(appid, appname, u.xg_device_token, content, extra) for u in hw_users: HuaWeiPush.push(appid, appname, u.hw_device_token, content) for u in gcm_users: GCMPush.push(appid, appname, u.gcm_device_token, content) for u in ali_users: AliPush.push(appid, appname, u.ali_device_token, content) # ios apns notifications = [] for u in apns_users: sound = 'default' payload = Payload(alert=content, sound=sound, badge=u.unread + 1, custom=extra) token = u.apns_device_token n = Notification(token, payload, None) notifications.append(n) if notifications: IOSPush.push_group_batch(appid, notifications, collapse_id) for u in apns_users: user.set_user_unread(rds, appid, receiver, u.unread + 1) # 极光推送 tokens = [] for u in jp_users: tokens.append(u.jp_device_token) if tokens: JGPush.push(appid, appname, tokens, content) tokens = [] for u in mi_users: tokens.append(u.mi_device_token) MiPush.push_batch(appid, appname, tokens, content)
async def get_reward(self, ctx): xsi_prompt = self._check_and_give_xsi_reward(ctx) if xsi_prompt is not None: await wait_for_reaction(ctx, await xsi_prompt, EMOJI_OK) with session_scope() as session: user = get_user(session, ctx.author.id) if user is None: await ctx.send(f"{ctx.author.mention}, 이벤트에 참여한 기록이 없습니다.") return if user.formlink is not None: await self.send_formlink(ctx, user.get_info()) return if user.get_reward: await ctx.send(f"{ctx.author.mention}, 이미 보상을 선택했습니다.") return sticker = user.sticker if sticker < 5: await ctx.send( f"{ctx.author.mention}, 아쉽지만 보상은 스티커 5장 이상부터 받을 수 있습니다. (현재 `{sticker}장` 보유)" ) return emojis = [EMOJI_KEYCAP_1] description = f"{EMOJI_KEYCAP_1} 포르테 포인트로 교환 (스티커 보유 개수 ✕ 5P)\n" if sticker >= 10: remaining_time = (datetime.fromisoformat("2021-01-20T21:00:00") - datetime.now()) if remaining_time > timedelta(0): description += ( "🔒 **현물 스티커로 교환** (국내 한정 우편 발송)" f" : `{timedelta_to_string(remaining_time)}` 남음") else: description += f"{EMOJI_KEYCAP_2} **현물 스티커로 교환** (국내 한정 우편 발송)" emojis.append(EMOJI_KEYCAP_2) assert sticker <= 20 prompt = await ctx.send( f"{ctx.author.mention}, 보상을 교환할 방법을 선택해주세요.\n" "⚠️ **__`한 번 선택하면 다시 바꿀 수 없습니다!!`__**", embed=discord.Embed(title=f"보유한 스티커: {sticker}장", description=description.strip()), ) selection = await wait_for_multiple_reactions(ctx, prompt, emojis) with session_scope() as session: user = get_user(session, ctx.author.id) if user.formlink is not None: await self.send_formlink(ctx, user.get_info()) return if user.get_reward: await ctx.send(f"{ctx.author.mention}, 이미 보상을 선택했습니다.") return if selection == EMOJI_KEYCAP_1: user.get_reward = True session.commit() try: receipt_id = await give_forte_point( ctx.author.id, 5 * sticker) self.bot.logger.info( f"reward {ctx.author.id} - point {5 * sticker}, receipt_id {receipt_id}" ) except ForteError as e: user.get_reward = False self.bot.logger.warning( f"reward {ctx.author.id} - forte_fail {e}") if e.status == 404: await ctx.send( f"{ctx.author.mention}, 포르테 상점에서 디스코드로 로그인 한 뒤 다시 시도하세요.", embed=forte_embed, ) return await ctx.send( f"{ctx.author.mention}, 알 수 없는 에러로 포르테 포인트 지급에 실패했습니다. 나중에 다시 시도해주세요." ) return await ctx.send( f"{ctx.author.mention}, {5 * sticker}<:fortepoint:737564157473194014>를 드렸습니다!", embed=forte_embed, ) elif selection == EMOJI_KEYCAP_2: if count_formlinks(session) >= FORMLINK_MAX: await ctx.send( f"{ctx.author.mention}, 선착순 {FORMLINK_MAX}명이 다 차서 현물 스티커 신청은 마감되었습니다. 불편을 드려 죄송합니다." ) return user.get_reward = True user.formlink = make_random_string() + str(user.id)[-4:] self.bot.logger.info( f"reward {ctx.author.id} - make_link {user.formlink}") session.commit() await self.send_formlink(ctx, user.get_info())
def handle_im_messages(msgs): msg_objs = [] for msg in msgs: obj = json.loads(msg) if not obj.has_key("appid") or \ not obj.has_key("sender") or \ not obj.has_key("receiver"): logging.warning("invalid push msg:%s", msg) continue msg_objs.append(obj) logging.debug("push msg:%s", msg) apns_users = [] jp_users = [] xg_users = [] hw_users = [] gcm_users = [] mi_users = [] ali_users = [] for obj in msg_objs: appid = obj["appid"] sender = obj["sender"] receiver = obj["receiver"] appname = get_title(appid) sender_name = user.get_user_name(rds, appid, sender) do_not_disturb = user.get_user_do_not_disturb(rds, appid, receiver, sender) if do_not_disturb: logging.debug("uid:%s set do not disturb :%s", receiver, sender) continue u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) continue content_obj = json.loads(obj['content']) if content_obj.get('revoke'): collapse_id = content_obj.get('revoke').get('msgid') sender_name = sender_name if sender_name else '' content = "%s撤回了一条消息" % sender_name else: collapse_id = content_obj.get('uuid') content = push_content(sender_name, obj["content"]) # 找出最近绑定的token ts = max(u.apns_timestamp, u.xg_timestamp, u.mi_timestamp, u.hw_timestamp, u.gcm_timestamp, u.ali_timestamp, u.jp_timestamp) if u.apns_device_token and u.apns_timestamp == ts: apns_users.append((u, appname, content, collapse_id)) elif u.xg_device_token and u.xg_timestamp == ts: xg_users.append((u, appname, content, collapse_id)) elif u.mi_device_token and u.mi_timestamp == ts: mi_users.append((u, appname, content, collapse_id)) elif u.hw_device_token and u.hw_timestamp == ts: hw_users.append((u, appname, content, collapse_id)) elif u.gcm_device_token and u.gcm_timestamp == ts: gcm_users.append((u, appname, content, collapse_id)) elif u.ali_device_token and u.ali_timestamp == ts: ali_users.append((u, appname, content, collapse_id)) elif u.jp_device_token and u.jp_timestamp == ts: jp_users.append((u, appname, content, collapse_id)) else: logging.info("uid:%d has't device token", receiver) for u, appname, content, _ in xg_users: xg_push(u.appid, appname, u.xg_device_token, content, {}) for u, appname, content, _ in hw_users: HuaWeiPush.push(u.appid, appname, u.hw_device_token, content) for u, appname, content, _ in gcm_users: GCMPush.push(u.appid, appname, u.gcm_device_token, content) for u, appname, content, _ in ali_users: AliPush.push(u.appid, appname, u.ali_device_token, content) for u, appname, content, _ in jp_users: JGPush.push(u.appid, appname, u.jp_device_token, content) for u, appname, content, _ in mi_users: MiPush.push(u.appid, appname, u.mi_device_token, content) # ios apns notifications = [] for u, appname, content, collapse_id in apns_users: sound = 'default' payload = Payload(alert=content, sound=sound, badge=u.unread + 1) token = u.apns_device_token n = Notification(token, payload, collapse_id) notifications.append(n) if notifications: IOSPush.push_peer_batch(u.appid, notifications) for u, appname, content, collapse_id in apns_users: user.set_user_unread(rds, u.appid, u.uid, u.unread + 1)
def api_user_show(self): user = get_user(self.request, self.request.matchdict['name']) if user: return self.ok({'user': self.format_user(user)}) else: return self.error("No such user")
def handle_customer_message(msg): obj = json.loads(msg) if not obj.has_key("appid") or not obj.has_key("command") or \ not obj.has_key("customer_appid") or not obj.has_key("customer") or \ not obj.has_key("seller") or not obj.has_key("content") or \ not obj.has_key("store") or not obj.has_key("receiver"): logging.warning("invalid customer push msg:%s", msg) return logging.debug("customer push msg:%s", msg) appid = obj["appid"] receiver = obj["receiver"] command = obj["command"] customer_appid = obj["customer_appid"] customer = obj["customer"] store = obj["store"] seller = obj["seller"] raw_content = obj["content"] appname = get_title(appid) extra = {} if command == MSG_CUSTOMER: sender_name = user.get_user_name(rds, customer_appid, customer) content = push_content(sender_name, raw_content) push_message(appid, appname, receiver, content, extra) elif command == MSG_CUSTOMER_SUPPORT: if appid == customer_appid and receiver == customer: #客服发给顾客 u = user.get_user(rds, appid, receiver) if u is None: logging.info("uid:%d nonexist", receiver) return if u.wx_openid: result = WXPush.push(appid, appname, u.wx_openid, raw_content) #errcode=45015, #errmsg=response out of time limit or subscription is canceled if result and result.get('errcode') == 45015: now = int(time.time()) content_obj = { "wechat": { "customer_appid": customer_appid, "customer_id": customer, "timestamp": now, "notification": "微信会话超时" } } post_system_message(config.KEFU_APPID, seller, json.dumps(content_obj)) else: extra['store_id'] = store extra['xiaowei'] = {"new": 1} store = Store.get_store(rds, store) sender_name = store.name content = push_content(sender_name, raw_content) push_customer_support_message(appid, appname, u, content, extra) else: #群发到其它客服人员 sender_name = user.get_user_name(rds, appid, seller) content = push_content(sender_name, raw_content) push_message(appid, appname, receiver, content, extra)
def check_auth(username: str, password: str) -> bool: """This function is called to check if a username / password combination is valid. """ user = get_user(username) return str(username) == user.username and str(password) == user.password