def manage_room(id): room = current_user.rooms.filter_by(id=id).first() if room is None: flash('您无此群聊') next = request.referrer if next is None or not next.startswith('/'): next = url_for('main.index') return redirect(next) form = ManageRoomForm() form.friends.choices = [(friend.id, friend.nickname) for friend in current_user.get_friends() if friend not in room.users.all()] if form.validate_on_submit(): room.name = form.name.data, room.description = form.description.data, db.session.add(room) db.session.commit() current_user.rooms.append(room) db.session.add(current_user) for sub in form.friends: friend = User.query.filter_by(id=sub.data).first() if friend is not None: friend.rooms.append(room) db.session.add(friend) db.session.commit() return redirect(url_for('main.roomchat', id=room.id)) form.name.data = room.name form.description.data = room.description return render_template('manage_room.html', form=form)
def createInvoice(embedded): print("invoice") form = CreateInvoice() #form.receiver.choices = [(g.frienduserid, User.query.filter_by(userid=g.frienduserid).first().username) for g in Relationship.query.filter_by(userid=current_user.userid, statusid=3).all()] #form.receiver.choices = [(g.frienduserid, g.rel_receiver.username) for g in current_user.get_friends()] choices = [(-1, 'Select receiver')] print(choices) for i in current_user.get_friends(): choices.append((i.frienduserid, i.rel_receiver.username)) #choices.append((g.frienduserid, g.rel_receiver.username) for g in current_user.get_friends()) print(choices) form.receiver.choices = choices #form.receiver.choices = ([(g.frienduserid, g.rel_receiver.username) for g in current_user.get_friends()]) if embedded=="false": emb=False else: emb=True #print("username: "******"Invoice sent"}) return {'message' : "Invoice sent"} return render_template('invoice.html', form=form, embedded=emb)
def connect(): if current_user.is_authenticated: current_user.state = True current_user.session_id = request.sid db.session.add(current_user) db.session.commit() for friend in current_user.get_friends(): if friend.state: emit('message', {'online': current_user.nickname}, room=friend.session_id) for room in current_user.rooms: join_room(room.id)
def disconnect(): if current_user.is_authenticated: current_user.state = False current_user.session_id = None current_user.last_seen = datetime.utcnow() + timedelta(hours=8) db.session.add(current_user) db.session.commit() for friend in current_user.get_friends(): if friend.state: emit('message', {'offline': current_user.nickname}, room=friend.session_id) for room in current_user.rooms: leave_room(room.id)
def get_friend_tasklist(): if request.form is None or 'friend_username' not in request.form: ret = [] for friend in current_user.get_friends(): ret.extend([task for task in friend.get_public_tasks()]) ret = sorted(ret, key=lambda v: v.finish_time) ret = [task.get_info_map() for task in ret] return Validity(True, {'friend task list': ret}).get_resp() else: form = {k: request.form[k].strip() for k in request.form} if utils.validate_username(form['friend_username']): return Validity( False, 'User ' + form['friend_username'] + ' does not exist.').get_resp() friend = User.query.filter_by(username=form['friend_username']).first() ret = sorted([task for task in friend.get_public_tasks()], key=lambda v: v.finish_time) ret = [task.get_info_map() for task in ret] return Validity(True, {'friend task list': ret}).get_resp()
def create_room(): form = RoomForm() form.friends.choices = [(friend.id, friend.nickname) for friend in current_user.get_friends()] if form.validate_on_submit(): room = Room(name=form.name.data, description=form.description.data, creater_id=current_user.id) db.session.add(room) db.session.commit() current_user.rooms.append(room) db.session.add(current_user) for sub in form.friends: friend = User.query.filter_by(id=sub.data).first() if friend is not None: friend.rooms.append(room) db.session.add(friend) db.session.commit() return redirect(url_for('main.roomchat', id=room.id)) return render_template('create_room.html', form=form)
def get_friendlist(): ret = sorted([friend for friend in current_user.get_friends()], key=lambda v: v.name) ret = [friend.get_info_map() for friend in ret] return Validity(True, {'friend list': ret}).get_resp()
def createInvoice(embedded): form = CreateInvoice() choices = [(-1, 'Välj mottagare')] for i in current_user.get_friends(): choices.append((i.frienduserid, i.rel_receiver.username)) form.receiver.choices = choices #print(choices) if embedded == "False": emb = False else: emb = True #print("username: "******"Du har blivit fakkad :)", sender=('fakk.', '*****@*****.**'), recipients=[form.email.data]) msg.body = "Du har blivit fakkad, se bifogat " + confirm_url msg.html = html #msg.attach('invoice.pdf', 'application/pdf', data=pdf.read()) mail.send(msg) #flash('Faktura skickad till '+ form.email.data, category='success') elif form.inv_type.data == 3: is_user_with_phone = User.query.filter_by( phone=form.phone.data, confirmed_phone=True).first() #print(is_user_with_phone) if (is_user_with_phone): invoice = Invoice(amount=form.amount.data, description=form.description.data, userid=current_user.userid, frienduserid=is_user_with_phone.userid) #print(invoice) db.session.add(invoice) db.session.commit() #print(invoice.invoiceid) #Skicka SMS package_locked = generate_invoice_token( form.receiver.data, invoice.invoiceid) elif User.query.filter_by(usertype=1, phone=form.phone.data).first(): dummyuser = User.query.filter_by( usertype=1, phone=form.phone.data).first() invoice = Invoice(amount=form.amount.data, description=form.description.data, userid=current_user.userid, frienduserid=dummyuser.userid) #print(invoice) db.session.add(invoice) db.session.commit() #print(invoice.invoiceid) package_locked = generate_invoice_token( invoice.invoiceid, dummyuser.userid) else: newdummyuser = User( username=None, #email=form.email.data, password='******', usertype=1, credits=None) db.session.add(newdummyuser) db.session.commit() newdummyuser.phone = form.phone.data db.session.commit() invoice = Invoice(amount=form.amount.data, description=form.description.data, userid=current_user.userid, frienduserid=newdummyuser.userid) #print(invoice) db.session.add(invoice) db.session.commit() #print(invoice.invoiceid) package_locked = generate_invoice_token( invoice.invoiceid, newdummyuser.userid) confirm_url = url_for('main.invoice_site', invoice_token=package_locked, _external=True) message = 'Du har fått en faktura av ' + current_user.phone + ' ' + confirm_url sms_status = sendSMS(form.phone.data, message) #print('sms_status', sms_status) current_user.credits -= 5 db.session.commit() flash('Faktura skickad till ' + str(form.phone.data), category='success') #flash('Faktura skickad till '+ form.phone.data, category='success') if emb: return {'message': "Invoice sent"} else: return redirect(url_for('invoices.getAll')) #print(emb) return render_template('invoice.html', form=form, embedded=emb)
def new_note(): form = CreateNoteForm() if form.validate_on_submit(): local_note = Note( content=form.content.data, created_by=current_user.id, is_public=not form.is_private.data, is_recurring=form.is_recurring.data, is_shared_with_friends=form.is_shared_with_friends.data, is_commentable=form.is_commentable.data) db.session.add(local_note) # Create tags----------------------- raw_tags = form.tags.data.split('$') clean_tags = [ tag.lower() for tag in [tag.strip() for tag in raw_tags] if ' ' not in tag and tag ] tags = [] for each_clean_tag in clean_tags: temp_tag = Tag.query.filter_by(name=each_clean_tag).first() if not temp_tag: temp_tag = Tag(name=each_clean_tag) db.session.add(temp_tag) tags.append(temp_tag) # Create region------------------------- if form.region_name.data: local_region = Region.query.filter_by( name=form.region_name.data).first() else: local_region = Region(latitude=form.latitude.data, longitude=form.longitude.data, radius=form.radius.data) db.session.add(local_region) # Create Recurrence Pattern---------------- recurrence = RecurrencePattern( recurrence_type=form.recurrence_type.data if form.recurrence_type.data else None, start_time=form.start_time.data, end_time=form.end_time.data, start_date=form.start_date.data, end_date=form.end_date.data, separation_count=form.separation_count.data if form.separation_count.data > 0 else None, day_of_week=form.day_of_week.data if form.day_of_week.data else None, week_of_month=form.week_of_month.data if form.week_of_month.data else None, day_of_month=form.day_of_month.data if form.day_of_month.data else None, month_of_year=form.month_of_year.data if form.month_of_year.data else None) db.session.add(recurrence) db.session.flush() # Adjust note visibility local_note.region_id = local_region.id if not local_note.is_public: local_note.visibility.append(current_user) if local_note.is_shared_with_friends: local_note.visibility.extend(current_user.get_friends()) local_note.tags.extend(tags) local_note.pattern.append(recurrence) db.session.commit() flash('success$Note has been created !') return redirect(url_for('note', note_id=local_note.id)) return render_template('new_note.html', form=form)
def test_message(message): if 'type' in message and message['type'] == 'attention': if message['content'] in ('post', 'imagepost'): for friend in current_user.get_friends(): if friend.state: emit('message', {'type': 'attention'}, room=friend.session_id) elif message['content'] in ('comment', 'reply'): receiver = User.query.filter_by( id=int(message['receiver_id'])).first() if receiver is not None and receiver.state: emit('message', {'type': 'attention'}, room=receiver.session_id) elif message['content'] == 'view': imagepost = ImagePost.query.filter_by( id=int(message['imagepost_id'])).first() if imagepost is not None: reply_to = ([imagepost.author] if current_user != imagepost.author else []) for view in imagepost.views.all(): if view.author not in reply_to and view.author != current_user and view.author.state: reply_to.append(view.author) for user in reply_to: emit('message', {'type': 'attention'}, room=user.session_id) elif message['content'] in ('friend_request', 'friend_confirm'): receiver = User.query.filter_by( id=int(message['receiver_id'])).first() if receiver is not None and receiver.state: emit('message', {'type': 'attention'}, room=receiver.session_id) elif 'state' in message and message['state'] == 'sending': if 'receiver' in message and 'room' not in message: user = User.query.filter_by(nickname=message['receiver']).first() if user.state: emit('message', { 'data': message['data'], 'sender': current_user.nickname, 'receiver_id': user.id, 'time': (datetime.utcnow() + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S'), 'state': 'sent' }, room=user.session_id) else: message = Message(sender_id=current_user.id, receiver_id=user.id, data=message['data'], time_stamp=(datetime.utcnow() + timedelta(hours=8)), state='unshow') db.session.add(message) db.session.commit() elif 'room' in message: room = Room.query.filter_by(id=int(message['room'])).first() emit('message', { 'data': message['data'], 'sender': current_user.nickname, 'room_id': room.id, 'time': (datetime.utcnow() + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S'), 'state': 'sent' }, room=room.id) message = Message(sender_id=current_user.id, receiver_id=None, room_id=room.id, data=message['data'], time_stamp=(datetime.utcnow() + timedelta(hours=8)), state='sent') db.session.add(message) db.session.commit() offline_store_room_message(room, message) elif 'state' in message and message['state'] in ('unshow', 'received'): sender = User.query.filter_by(nickname=message['sender']).first() message = Message( sender_id=sender.id, receiver_id=current_user.id, data=message['data'], room_id=(message['room_id'] if 'room_id' in message else None), time_stamp=(datetime.utcnow() + timedelta(hours=8)), state=message['state']) db.session.add(message) db.session.commit()
def home(): # home if auth if current_user.is_authenticated(): # projects projects_where_is_owner = [] for project in current_user.projects: projects_where_is_owner.append({ "id": project.id, "ownerName": project.owner_name, "name": project.name, "goToUrl": f"/{project.owner_name}/{project.name}" }) projects_where_is_collab = current_user.get_projects_where_is_collaborator( ) for i, project in enumerate(projects_where_is_collab): projects_where_is_collab[i] = { "id": project.id, "ownerName": project.owner_name, "name": project.name, "goToUrl": f"/{project.owner_name}/{project.name}" } # notifications notifications = current_user.get_notifications() for i, notification in enumerate(notifications): from_user = User.get_by_id(notification.from_id) if isinstance(notification, Msg): notifications[i] = { "id": notification.id, "type": "msg", "chatType": "userToUser", "picUrl": from_user.small_avatar_url, "goToUrl": f"/{from_user.name}", "goToChatUrl": f"/chat?with={from_user.name}", "datetime": f"{notification.datetime}+00:00", "content": notification.content } elif isinstance(notification, ChatGroupMsg): notifications[i] = { "id": notification.id, "type": "msg", "chatType": "chatGroup", "picUrl": from_user.small_avatar_url, "goToUrl": f"/{from_user.name}", "goToChatUrl": "/chat", "datetime": f"{notification.datetime}+00:00", "content": notification.content } elif isinstance(notification, ProjectChatGroupMsg): notifications[i] = { "id": notification.id, "type": "msg", "chatType": "projectChatGroup", "picUrl": from_user.small_avatar_url, "goToUrl": f"/{from_user.name}", "goToChatUrl": "/chat", "datetime": f"{notification.datetime}+00:00", "content": notification.content } elif isinstance(notification, FriendshipRequest): notifications[i] = { "id": notification.id, "type": "friendshipRequest", "picUrl": from_user.small_avatar_url, "goToUrl": f"/{from_user.name}", "datetime": f"{notification.datetime}+00:00" } # friends friends = current_user.get_friends() for i, friend in enumerate(friends): friends[i] = { "id": friend.id, "name": friend.name, "picUrl": friend.small_avatar_url, "goToUrl": f"/{friend.name}" } return render_template("home.auth.html.j2", projects={ "whereOwner": projects_where_is_owner, "whereCollab": projects_where_is_collab }, notifications=notifications, friends=friends) # home if not auth return render_template("home.unauth.html.j2")
def chat(): if not current_user.is_authenticated(): abort(404) chats = {"userToUser": {}, "chatGroup": {}, "projectChatGroup": {}} for friend in current_user.get_friends(): last_msg = current_user.get_last_msg(friend.id, "userToUser") last_msg = { "content": last_msg.content, "datetime": f"{last_msg.datetime}+00:00" } if last_msg else "None" chats["userToUser"][friend.id] = { "id": friend.id, "type": "userToUser", "name": friend.name, "unreadCount": current_user.get_unread_count_in_chat(friend.id, "userToUser"), "lastMsg": last_msg, "picUrl": friend.small_avatar_url, "goToUrl": f"/{friend.name}" } for chat_group in current_user.get_chat_groups_where_member(): last_msg = current_user.get_last_msg(chat_group.id, "chatGroup") last_msg = { "content": last_msg.content, "datetime": f"{last_msg.datetime}+00:00" } if last_msg else "None" members = {} for member_user in db.session.query(ChatGroupMemberLink) \ .filter_by(chat_group_id=chat_group.id) \ .join(User, User.id == ChatGroupMemberLink.user_id) \ .with_entities(User.id, User.name, User.small_avatar_url, ChatGroupMemberLink.user_role): members[member_user.id] = { "id": member_user.id, "name": member_user.name, "picUrl": member_user.small_avatar_url, "goToUrl": f"/{member_user.name}", "role": member_user.user_role } chats["chatGroup"][chat_group.id] = { "id": chat_group.id, "type": "chatGroup", "name": chat_group.name, "unreadCount": current_user.get_unread_count_in_chat(chat_group.id, "chatGroup"), "lastMsg": last_msg, "picUrl": "/static/img/group.png", "roleOfCurrentUser": chat_group.user_role, "members": members } for project_chat_group in current_user.get_project_chat_groups_where_member( ): last_msg = current_user.get_last_msg(project_chat_group.id, "projectChatGroup") last_msg = { "content": last_msg.content, "datetime": f"{last_msg.datetime}+00:00" } if last_msg else "None" members = {} for member_user in db.session.query(ProjectChatGroupMemberLink) \ .filter_by(project_chat_group_id=project_chat_group.id) \ .join(User, User.id == ProjectChatGroupMemberLink.user_id) \ .with_entities(User.id, User.name, User.small_avatar_url): members[member_user.id] = { "id": member_user.id, "name": member_user.name, "picUrl": member_user.small_avatar_url, "goToUrl": f"/{member_user.name}", "role": "default" } chats["projectChatGroup"][project_chat_group.id] = { "id": project_chat_group.id, "type": "projectChatGroup", "name": project_chat_group.name, "unreadCount": current_user.get_unread_count_in_chat(project_chat_group.id, "projectChatGroup"), "lastMsg": last_msg, "picUrl": "/static/img/group.png", "roleOfCurrentUser": project_chat_group.user_role, "members": members } user_to_chat_with_name = request.args.get("with") if user_to_chat_with_name: member_user = User.get_by_name(user_to_chat_with_name) if member_user: if current_user.is_friend_with(member_user.id): return render_template( "chat.html.j2", chats=chats, chat_to_open={ "id": User.get_by_name(user_to_chat_with_name).id, "type": "userToUser" }) return render_template("chat.html.j2", chats=chats)
def get_friends(): return current_user.get_friends()