def createDirectMessagingRoom(json): project_id = json['project_id'] user = User.query.filter_by(username=json['username']).first_or_404() other_user = User.query.filter_by(id=json['otheruser_id']).first_or_404() if (user.id < other_user.id): room_title = str(user.id) + ":" + user.username + ":" + str( other_user.id) + ":" + other_user.username users = str(user.id) + ":" + str(other_user.id) username_list = user.username + ":" + other_user.username new_room = Channel(project_id=project_id, room=room_title, users=users) duplicate = db.session.query(Channel).filter_by(room=room_title, users=users).first() if duplicate == None: db.session.add(new_room) db.session.commit() else: room_title = str( other_user.id) + ":" + other_user.username + ":" + str( user.id) + ":" + user.username users = str(other_user.id) + ":" + str(user.id) username_list = user.username + ":" + other_user.username new_room = Channel(project_id=project_id, room=room_title, users=users) duplicate = db.session.query(Channel).filter_by(room=room_title, users=users).first() if duplicate == None: db.session.add(new_room) db.session.commit() emit('displayNewDMRoom', { 'project_id': project_id, 'username_list': username_list, 'room_id': room_title }, broadcast=True)
def post(self, request, server_id, id): new_channel = request.POST.get("name") server = Server.objects.get(id=server_id) task = Task.objects.get(id=id) if new_channel is not None and 0 < len(new_channel) <= 20 and Channel.objects.filter( name=new_channel, server=server).first() is None: if server is not None: channel = Channel(name=new_channel, server=server) channel.save() return redirect("room", pk=server_id, room_name=new_channel) elif request.POST.get("delete_task"): if request.user == task.author: task.delete() return redirect("server_tasks", server_id) elif request.POST.get("comment_task"): form = TaskCommentForm(request.POST) form.instance.task_type = "comment" form.instance.author = request.user form.instance.task = task if form.is_valid(): content = form.cleaned_data.get('content') if len(content.replace(" ", "").replace(" ", "").replace("<p>", "").replace("</p>", "")) == 0: return HttpResponseRedirect(self.request.path_info) form.save() elif request.POST.get("delete_message"): comment_id = request.POST.get("comment_id") comment = TaskComment.objects.get(id=comment_id) if comment.author == request.user: comment.delete() return HttpResponseRedirect(self.request.path_info)
def post(self, request, server_id, id): new_channel = request.POST.get("name") server = Server.objects.get(id=server_id) if new_channel is not None and 0 < len(new_channel) <= 20 and Channel.objects.filter( name=new_channel, server=server).first() is None: if server is not None: channel = Channel(name=new_channel, server=server) channel.save() return redirect("room", pk=server_id, room_name=new_channel) title = request.POST.get("title") description = request.POST.get("description") task = Task.objects.get(id=id) task.assigned_for.clear() assigned_list = request.POST.get("assigned_users_list") for user in json.loads(assigned_list): if User.objects.filter(username=user).first() in server.users.all(): task.assigned_for.add(User.objects.get(username=user)) if task.assigned_for.count() == 0: task.assigned_for.add(task.author) if len(title) <= 20: task.title = title if len(description) <= 4000: task.description = description task.save() return redirect("task_detail", server_id, id)
def post(self, request, server_id): title = request.POST.get('title') new_channel = request.POST.get("name") server = Server.objects.get(id=server_id) if title is not None and len(title) <= 20: description = request.POST.get('description') assignments = request.POST.getlist('assignments') deadline = request.POST.get('deadline') server = Server.objects.get(id=server_id) server_task_id = Task.objects.filter(server=server).count() + 1 task = Task.objects.create(task_id=server_task_id, title=title, description=description, author=request.user, server=server) if deadline != "": task.deadline = deadline if len(assignments) == 0: task.assigned_for.add(request.user) else: for username in assignments: task.assigned_for.add(server.users.get(username=username)) task.save() response = redirect("server_tasks", server_id) response['Location'] += '?order=-deadline' return response elif (new_channel is not None and 0 < len(new_channel) <= 20 and Channel.objects.filter(name=new_channel, server=server).first() is None): if server is not None: channel = Channel(name=new_channel, server=server) channel.save() return redirect("room", pk=server_id, room_name=new_channel) else: return HttpResponseRedirect(self.request.path_info)
def post_dms(): """ Creates Direct messages """ user_ids = request.get_json()['user_ids'] user_ids.append(current_user.id) users = [User.query.get(id) for id in user_ids] user_ids = [str(id) for id in user_ids] # create the channel first dm = Channel( name = "-".join(user_ids), # name = 1-2-3-4 channel_type = "dm" ) db.session.add(dm) db.session.commit() # query for the channel dm = Channel.query.filter(Channel.name == "-".join(user_ids)).first() for user in users: user.channels.append(dm) db.session.commit() return dm.to_dict()
def test_repr() -> None: channel = Channel(name='channelName', password='******') assert channel.__repr__() == "Channel(name='channelName')" user = User(username='******', password='******', email='*****@*****.**') assert user.__repr__() == "User(name='userName')" with app.app_context(): db.drop_all() db.create_all() db.session.add(user) db.session.add(channel) channel_id = Channel.query.first().id user_id = User.query.first().id channel_allow_list = ChannelAllowList(user_id=user_id, channel_id=channel_id, user_role=UserRole.ADMIN.value) assert channel_allow_list.__repr__() == \ f'ChannelAllowList(channel_id=1, user_id=1, user_role={UserRole.ADMIN.value})' time = datetime.utcnow() message = Message(content='content', author_id=user_id, target_channel=channel_id, time=time) assert message.__repr__( ) == f"Message(author_id=1, target_channel=1, time={time})"
def deploy(): """Run deployment tasks.""" # migrate database to latest revision upgrade() # create or update user roles Role.deploy_roles() Channel.deploy_channels() User.deploy_users()
def addChannel(server_id, channel_name): name = channel_name created_at = datetime.now() new_channel = Channel(name=name, server_id=server_id, created_at=created_at) db.session.add(new_channel) db.session.commit() return new_channel.to_dict()
def add_channel(): channel = request.json new_channel = Channel(name=channel['name'], server_id=channel['serverId'], created_at=datetime.utcnow()) db.session.add(new_channel) db.session.commit() return new_channel.to_dict()
def post(self): args = channel_parser.parse_args() channel = Channel() channel.name = args['name'] channel.sort = args['sort'] db.session.add(channel) db.session.commit() return channel, 201
def create_channel(): request_data = request.form channel_name = str(request_data['name']).strip() channel = Channel(channel_name) success = channel.create() if success: result = channel_schema.dump(channel) return jsonify(result.data), 201 else: return Response(status=500)
def create_channel(): data = request.get_json() or {} if 'device_id' not in data or 'name' not in data or 'channel_num' not in data: return bad_post("Missing required fields.") channel = Channel() channel.from_dict(data) db.session.add(channel) db.session.commit() response = jsonify(channel.to_dict()) response.status_code = 200 return response
def vote_store_channel(sid): store = Store.read(sid) if store: request_data = request.form cid = request_data.get('cid', None) if not cid: return Response(status=400) else: cid = int(cid) idx = -1 for i, vote in enumerate(store.votes): if vote.cid == cid: idx = i break if idx >= 0: store.votes[idx].vote_count += 1 else: channel = Channel.read(cid) vote = Vote(sid=sid, cid=cid, vote_count=1) if channel: store.votes.append(vote) success = store.update() if success: result = store_schema.dump(store) return jsonify(result.data), 200 else: return Response(status=500) return Response(status=404)
def test_is_admin_ajax(self) -> None: db.session.add( User(username='******', password=hash_password('testPassword'), email='*****@*****.**')) db.session.add(Channel(name='channel', password='******')) db.session.add(ChannelAllowList(channel_id=1, user_id=1)) with app.test_client() as c: rv = c.post('/is-admin', data={'channelName': 'channel'}, follow_redirects=True) assert 'response' not in str(rv.data) rv = login(c, '*****@*****.**', 'testPassword') assert 'Log out' in str(rv.data) # User is not admin of the channel. rv = c.post('/is-admin', data={'channelName': 'channel'}, follow_redirects=True) assert 'response' in str(rv.data) json = eval( rv.data.decode('utf8').replace('false', 'False').replace( 'true', 'True')) assert not json['response'] ChannelAllowList.query.first().user_role = UserRole.ADMIN.value # User is admin of the channel rv = c.post('/is-admin', data={'channelName': 'channel'}, follow_redirects=True) assert 'response' in str(rv.data) json = eval( rv.data.decode('utf8').replace('false', 'False').replace( 'true', 'True')) assert json['response'] # No channel given in the form rv = c.post('/is-admin', follow_redirects=True) assert 'response' in str(rv.data) json = eval( rv.data.decode('utf8').replace('false', 'False').replace( 'true', 'True')) assert not json['response'] # Channel given in the form doesn't exist rv = c.post('/is-admin', data={'channelName': 'channel_second'}, follow_redirects=True) assert 'response' in str(rv.data) json = eval( rv.data.decode('utf8').replace('false', 'False').replace( 'true', 'True')) assert not json['response']
def process_add_channel_form(form: AddChannelForm) -> Response: """Get the validated form to add a channel. Hash the given password of the channel. Set the current user admin role on this channel. Save all of that in the database. Args: form: The filled form to add a channel. """ hashed_password = hash_password(form.password.data) db.session.add(Channel( name=form.name.data, password=hashed_password )) channel_id = Channel.query.filter_by(password=hashed_password).first().id db.session.add(ChannelAllowList( channel_id=channel_id, user_id=current_user.id, user_role=UserRole.ADMIN.value )) db.session.commit() flash(f'You have successfully added the channel "{form.name.data}"!', 'success') return redirect(url_for('main.setup_app'))
def create_channel(self, id: str, chat_id: str, last_video_id: str): channel = Channel(channel_id=id, chat_id=chat_id, last_video_id=last_video_id) self.session.add(channel) self.session.commit() return channel
def test_channel_settings(self) -> None: db.session.add( User(username='******', password=hash_password('testPassword'), email='*****@*****.**')) db.session.add(Channel(name='channel', password='******')) db.session.add(ChannelAllowList(channel_id=1, user_id=1)) with app.test_client() as c: rv = c.get('/channel/channel', follow_redirects=True) assert 'Please log in to access this page' in str(rv.data) rv = login(c, '*****@*****.**', 'testPassword') assert 'Log out' in str(rv.data) rv = c.get('/channel/channel', follow_redirects=True) assert 'Number of users:' not in str(rv.data) assert "you don't have necessary permission" in decode_bytecode_single_quote( rv.data) ChannelAllowList.query.first().user_role = UserRole.ADMIN.value rv = c.get('/channel/channel', follow_redirects=True) assert 'Number of users:' in str(rv.data) rv = c.get('/channel/channel_second', follow_redirects=True) assert 'Number of users:' not in str(rv.data) assert "channel doesn't exist" in decode_bytecode_single_quote( rv.data)
def auto_seed(count, server_count): for i in range(count): name = fake.domain_word() server = random.randint(1, server_count) created_at = datetime.now() seed_channel = Channel(name=name, server_id=server, created_at=created_at) db.session.add(seed_channel)
def test_get_initial_counter_ajax(self) -> None: db.session.add( User(username='******', password=hash_password('testPassword'), email='*****@*****.**')) db.session.add(Channel(name='channel', password='******')) with app.test_client() as c: rv = c.post('/get-messages', data={'channelName': 'channel'}, follow_redirects=True) assert 'counter' not in str(rv.data) rv = login(c, '*****@*****.**', 'testPassword') assert 'Log out' in str(rv.data) rv = c.post('/initial-counter', data={'channelName': 'channel'}, follow_redirects=True) assert 'counter' in str(rv.data) json = eval(rv.data.decode('utf8')) assert json['counter'] == 0 for _ in range(20): db.session.add( Message(content='&', target_channel=1, author_id=1, time=datetime.utcnow())) rv = c.post('/initial-counter', data={'channelName': 'channel'}, follow_redirects=True) json = eval(rv.data.decode('utf8')) assert json['counter'] == 20
def getvideos(channel_id): channel_info = get_channel_info(channel_id) channel = Channel(channelId=channel_id, **channel_info) videos = get_channel_videos(channel_id) db.session.add() return render_template('main/channel.html', ids=videos)
def private_messages_get(): channel_hash_id = request.args.get('channel_id') channel = Channel.get(channel_hash_id) l = [] for msg in channel.messages: if msg.sender_id == current_user.id: if msg.unread: status = 'sent' else: status = 'read' else: msg.unread = False db.session.commit() status = 'received' recipient = User.query.get(msg.recipient_id) sender = User.query.get(msg.sender_id) d = { 'position' : msg.sender_id == current_user.id and 'right' or 'left', 'date' : msg.timestamp.isoformat() + 'Z', 'status' : status, 'text' : msg.body, 'type' : 'text', 'id' : msg.hash_id, 'recipient_id': recipient.hash_id, 'sender_id' : sender.hash_id, 'channel_id' : msg.channel.hash_id } l.append(d) return jsonify(l)
def createGroupMessagingRoom(json): project_id = json['project_id'] room_title = json['roomName'] user = User.query.filter_by(username=json['username']).first_or_404() username_list = "" user_list = "" tosort = [user.id] for x in json['users']: tosort.append(int(x)) mylist = sorted(tosort) for user in mylist: user_list += ":" + str(user) user = User.query.filter_by(id=user).first_or_404() username_list += ":" + user.username duplicate = db.session.query(Channel).filter_by(room=room_title, users=user_list).first() if duplicate == None: new_room = Channel(project_id=project_id, room=room_title, users=user_list) db.session.add(new_room) db.session.commit() emit('displayNewGroupRoom', { 'project_id': project_id, 'room_title': room_title, 'username_list': username_list }, broadcast=True)
def issue(self, data): if not self.check_object_kind(data, 'issue'): # This should not happen return default_response() # Get the issue object issue = data.get('object_attributes') # Get the project data from the url, since there is no 'repository' provided project = parse_project_name_from_repo_url(issue.get('url'), resource='issues') # If the project has a namespace, check that the namespace exists in slack # Otherwise try to find the channel matching the project name # Finally check SLACK_DEVELOPERS_CHANNEL or #general names = [ i for i in [ project.get('namespace'), project.get('name'), app.config.get('SLACK_DEVELOPERS_CHANNEL'), '#general' ] if i is not None ] channel = None namespace_user = User.findBy( 'gitlab_name', project.get('namespace')) if project.get('namespace') else None if namespace_user: # If the namespace is a slack user, send data directly to the user channel channel = '@' + namespace_user.name for name in names: if channel: break channel = name if Channel.exists(name) else None # Get the user info gitlab_user = data.get('user') # Check if the username matches slack username user = {} user['full_name'] = gitlab_user.get('name') slack_user = User.findBy('gitlab_name', gitlab_user.get('username')) if slack_user: user = slack_user # Generate the response text message = render_template('issue.txt', user=user, project=project, issue=issue) if not app.config.get('TESTING', False): # Send message to slack slack.chat.post_message(channel, message) else: # Return message to check in testing return message return default_response()
def private_channel_get(): user_hash_id = request.args.get('user_id') other = User.get_or_404(user_hash_id) if current_user.id != other.id: channel = Channel.private_channel_get(current_user, other) return jsonify(channel) return jsonify({})
def addchannel(): # Check the request for json if request.get_json(): # If there is json in the request, assign it to the var content content = request.get_json() # Check for the existence of a user by the same name if Channel.query.filter_by(name=str(content['channelname'])).first(): # Return an error if that username already exists return jsonify({'error': 'Channel with that name already exists'}) # Should the name not already exist, create a user with that name chan = Channel(name=str(content['channelname'])) # Add the new user to the session db.session.add(chan) # Commit the session db.session.commit() msg = "Channel with name {} has been created".format(chan.name) # Return a resonse to the caller return jsonify({'status': msg}) else: # Should there have been no json in the request, tell the caller return jsonify({'error': 'There was no json found in body of request'})
def subscribe(): form = SubscribeForm() if form.validate_on_submit(): videos = get_channel_videos(form.channel.data) if not videos: raise DownloadError('Channel \'{}\' not found'.format( form.channel.data)) channel = Channel(name=videos[0]['uploader_id'], channel_id=videos[0]['channel_id']) db.session.add(channel) db.session.commit() for v in videos: if v and 'id' in v: video = Video(video_id=v['id'], title=v['title'], channel_id=channel.id, description=v['description'], thumbnail_url=v['thumbnail'], duration=v['duration'], upload_date=datetime.strptime( v['upload_date'], '%Y%m%d'), view_count=v['view_count']) db.session.add(video) db.session.commit() return redirect('/channels')
def get_channel(cid: int) -> Response: channel = Channel.read(cid) if channel: result = channel_schema.dump(channel) return jsonify(result.data), 200 else: return Response(status=404)
def apply(self, params, channel_id, sender_id): seconds = self._get_seconds(params) if seconds > self.MAX_SECONDS: return f'Soy un bot muy responsable. No puedo irme por más de {self.MAX_SECONDS} segundos' if seconds <= 0: return f'Soy un bot muy inteligente y se que los segundos deben ser positivos' channel = Channel.query.filter_by(id=channel_id).first() if channel is None: channel = Channel(id=channel_id) channel.enabled = datetime.now() + timedelta(seconds=seconds) db.session.add(channel) db.session.commit() return self._get_message(seconds)
def seed_channels(): for channel in channels: new_channel = Channel( name=channel['name'], channel_type=channel['channel_type'] ) db.session.add(new_channel) db.session.commit()
def create_fixtures(self): human = Human(user_id="1", user_name="joe") channel = Channel(chat_id="1", name="test", restrict=False) message = Message(user_id="1", chat_id="1", message_id="1") db.session.add(human) db.session.add(channel) db.session.add(message) db.session.commit()
def issue(self, data): if not self.check_object_kind(data, 'issue'): # This should not happen return default_response() # Get the issue object issue = data.get('object_attributes') # Get the project data from the url, since there is no 'repository' provided project = parse_project_name_from_repo_url(issue.get('url'), resource='issues') # If the project has a namespace, check that the namespace exists in slack # Otherwise try to find the channel matching the project name # Finally check SLACK_DEVELOPERS_CHANNEL or #general names = [i for i in [project.get('namespace'), project.get('name'), app.config.get('SLACK_DEVELOPERS_CHANNEL'), '#general'] if i is not None] channel = None namespace_user = User.findBy('gitlab_name', project.get('namespace')) if project.get('namespace') else None if namespace_user: # If the namespace is a slack user, send data directly to the user channel channel = '@' + namespace_user.name for name in names: if channel: break channel = name if Channel.exists(name) else None # Get the user info gitlab_user = data.get('user') # Check if the username matches slack username user = {} user['full_name'] = gitlab_user.get('name') slack_user = User.findBy('gitlab_name', gitlab_user.get('username')) if slack_user: user = slack_user # Generate the response text message = render_template('issue.txt', user=user, project=project, issue=issue) if not app.config.get('TESTING', False): # Send message to slack slack.chat.post_message(channel, message) else: # Return message to check in testing return message return default_response()
def create(request): c = Channel() newhash = base64.urlsafe_b64encode(hashlib.md5(str(time.time())).digest()) # Remove dashes and underscores to make this easier to type newhash = newhash.replace("-", "") newhash = newhash.replace("_", "") c.hash = newhash[0:6] c.name = "" c.pusher_key = "private-videochannel_" + c.hash c.save() return redirect("/channel/" + c.hash)