def post(self, message_id): try: message = Message.objects(id=message_id).get() message.was_seen = True message.save() data = json.loads(self.request.body) body = data['body'] response_message = Message( body=body, to_user=message.from_user, from_user=message.to_user, is_response=True, is_private=True, chat=message.chat, original_body=message.body ) response_message.save() self.set_status(201) self.write(response_message.to_representation()) except Message.DoesNotExist: self.clear() self.set_status(404) self.finish({'error': 'not found'})
def post(self): try: data = json.loads(self.request.body) body = data['body'] name = data['chat_id'] username = data['username'] chat = Chat.objects(slug_name=name).get() user = User.objects(username=username).get() self.set_status(201) message = Message( from_user=user, chat=chat, created_at=datetime.now(), body=body, is_private=self.is_private ) users = [user for user in chat.users] if len(users) > 1: to_user = users[random.randrange(0, len(users))] while to_user.id == user.id: to_user = users[random.randrange(0, len(users))] message.to_user = to_user message.save() self.write(message.to_representation()) except (Chat.DoesNotExist, User.DoesNotExist): self.clear() self.set_status(404) self.finish({'error': 'not found'})
def upload_backup_files(self, backup): """Update a Backup's attributes based on form contents. If successful, return True; otherwise, add errors to the form and return False. """ assignment = backup.assignment templates = assignment.files files = {} for upload in request.files.getlist(self.name): data = upload.read() if len(data) > 15 * 1024 * 1024: # file is too large (over 15 MB) self.errors.append('{} is larger than the maximum file size ' 'of 15MB'.format(upload.filename)) return False try: files[upload.filename] = str(data, 'utf-8') except UnicodeDecodeError: self.errors.append('{} is not a UTF-8 text file'.format( upload.filename)) return False template_files = assignment.files or [] missing = [ template for template in template_files if template not in files ] if missing: self.errors.append( 'Missing files: {}. The following files are required: {}'. format(', '.join(missing), ', '.join(templates))) return False message = Message(kind='file_contents', contents=files) backup.messages.append(message) return True
def setUp(self): super(TestGrading, self).setUp() self.setup_course() message_dict = {'file_contents': {'backup.py': '1'}, 'analytics': {}} self.active_user_ids = [self.user1.id, self.user2.id, self.user3.id] self.active_staff = [self.staff1, self.staff2] self.active_assignments = [self.assignment, self.assignment2] Group.invite(self.user1, self.user2, self.assignment) group = Group.lookup(self.user1, self.assignment) group.accept(self.user2) # Creates 5 submissions for each assignment per user, each spaced two minutes apart for assign in self.active_assignments: time = assign.due_date - datetime.timedelta(minutes=30) for num in range(5): for user_id in self.active_user_ids: num += 1 time += datetime.timedelta(minutes=2) backup = Backup(submitter_id=user_id, assignment=assign, submit=True) messages = [Message(kind=k, backup=backup, contents=m) for k, m in message_dict.items()] backup.created = time db.session.add_all(messages) db.session.add(backup) # Debugging print if tests fails # print("User {} | Assignment {} | Submission {} | Time {}".format( # user_id, assign.id, num, time)) db.session.commit()
def generate(self, sender): return Message( target=self.cleaned_data['target'], sender=sender, header=self.cleaned_data['header'], body=self.cleaned_data['body'], )
def get(self, name): try: chat = Chat.objects(slug_name=name).get() last_date = self.get_argument('last_date', None) if last_date: last_date = datetime.strptime(last_date, '%Y-%m-%dT%H:%M:%S.%f') messages = Message.objects(chat=chat, is_private=self.is_private, created_at__gt=last_date).order_by('created_at') else: messages = Message.objects(chat=chat, is_private=self.is_private).order_by('-created_at').limit(10) messages = [message for message in messages] messages.reverse() self.write({'results': [message.to_representation() for message in messages]}) except Chat.DoesNotExist: self.clear() self.set_status(404) self.finish({'error': 'not found'})
def clean(): for message in Message.objects(): message.delete() for user in User.objects(): user.delete() for chat in Chat.objects(): chat.delete()
def post(self, message_id): try: message = Message.objects(id=message_id).get() message.was_seen = True message.save() self.write(message.to_representation()) except Message.DoesNotExist: self.clear() self.set_status(404) self.finish({'error': 'not found'})
def do_reload(chats): clean() dummy_users_list = dummy_users() for chat in chats: messages = chat.pop('messages') ch = Chat(**chat) ch.save() ch.update(add_to_set__users=dummy_users_list) for i, message in enumerate(messages): m = Message( from_user=dummy_users_list[i % 2], chat=ch, created_at=datetime.now(), body=message, ) m.save()
def process_messages(management_source, management_data, machine, object_queue): for message_item in management_data.get('messages', []): object_queue['messages'].append( Message( machine=machine, management_source=management_source, text=message_item.get('text'), message_type=message_item.get('message_type'))) return object_queue
def process_messages(management_source, management_data, machine, object_queue): now = django.utils.timezone.now() for message_item in management_data.get('messages', []): object_queue['messages'].append( Message(machine=machine, management_source=management_source, text=message_item.get('text'), message_type=message_item.get('message_type'), date=message_item.get('date', now))) return object_queue
def process_messages(management_source, management_data, machine, object_queue): now = django.utils.timezone.now() for message_item in management_data.get("messages", []): object_queue["messages"].append( Message( machine=machine, management_source=management_source, text=message_item.get("text"), message_type=message_item.get("message_type"), date=message_item.get("date", now), ) ) return object_queue
def gen_backup(user, assignment): seconds_offset = random.randrange(-100000, 100000) messages = gen_messages(assignment, seconds_offset) submit = gen_bool(0.3) if submit: messages['file_contents']['submit'] = '' backup = Backup.create(created=assignment.due_date + datetime.timedelta(seconds=seconds_offset), submitter=user, assignment=assignment, submit=submit) backup.messages = [ Message(kind=k, contents=m) for k, m in messages.items() ] return backup
def test_files(self): backup = Backup(submitter_id=self.user1.id, assignment=self.assignment, submit=True) message = Message(kind='file_contents', backup=backup, contents={ 'hog.py': 'def foo():\n return', 'submit': True }) db.session.add(message) db.session.add(backup) db.session.commit() # submit should not show up assert backup.files() == {'hog.py': 'def foo():\n return'}
def _make_assignment(self, uids, assignment): # create a submission every 15 minutes message_dict = {'file_contents': {'backup.py': '1'}, 'analytics': {}} time = assignment.due_date for _ in range(20): for user_id in uids: time -= datetime.timedelta(minutes=15) backup = Backup(submitter_id=user_id, assignment=assignment, submit=True) messages = [ Message(kind=k, backup=backup, contents=m) for k, m in message_dict.items() ] db.session.add_all(messages) db.session.add(backup) db.session.commit()
async def _message_handler(self, data): """ Обрабатывает полученные сообщения :param data: :return: """ if data and "type" in data and "data" in data: if data["type"] == "message": user_data = self.chat(data["data"]) await self.send(user_data.to_json()) if user_data.notice == "OK": messages = data["data"]["message"] for message in [ messages[x:x + 256] for x in range(0, len(messages), 256) ]: data = ServerData(type="broadcast_message", data=dict( login=user_data.data["login"], message=message), notice="OK").to_json() await self._server.broadcast(self, data) elif data["type"] == "get_messages": if "token" in data["data"]: user = User.search_user(token=data["data"]["token"]) if user is not None: for i in Message.today_messages(): data = ServerData( type="get_messages", data=dict(message=i.message, date=i.date.strftime("%H:%M:%S"), login=User.search_user( id=i.user_id).login), notice="OK").to_json() await self.send(data) elif data["type"] == "authorization": data = self.authorization(data["data"]).to_json() await self.send(data) elif data["type"] == "registration": data = self.registration(data["data"]).to_json() await self.send(data)
def gen_backup(user, assignment): messages = { 'file_contents': { 'fizzbuzz.py': modified_file, 'moby_dick': 'Call me Ishmael.' }, 'analytics': {} } submit = gen_bool(0.1) if submit: messages['file_contents']['submit'] = '' backup = Backup(created=assignment.due_date - datetime.timedelta(seconds=random.randrange(-100000, 100)), submitter_id=user.id, assignment_id=assignment.id, submit=submit) backup.messages = [ Message(kind=k, contents=m) for k, m in messages.items() ] return backup
def _add_file(self, filename, contents): self.setup_course() email = '*****@*****.**' self.login(email) self.user = User.lookup(email) self.backup = Backup(submitter=self.user, assignment=self.assignment, submit=True) self.message = Message(backup=self.backup, contents={ filename: contents, 'submit': True }, kind='file_contents') db.session.add(self.backup) db.session.add(self.message) db.session.commit()
def setUp(self): """ Add submissions for 3 users. """ super(TestRevision, self).setUp() self.setup_course() message_dict = {'file_contents': {'backup.py': '1'}, 'analytics': {}} self.active_user_ids = [self.user1.id, self.user2.id, self.user3.id] self.assignment.revisions_allowed = True time = self.assignment.due_date # Set to dt.now(), so future subms are late for user_id in self.active_user_ids: time -= datetime.timedelta(minutes=15) backup = Backup(submitter_id=user_id, assignment=self.assignment, submit=True) # Revisions are submitted on time. backup.created = time messages = [ Message(kind=k, backup=backup, contents=m) for k, m in message_dict.items() ] db.session.add_all(messages) db.session.add(backup) # Put user 3 in a group with user 4 Group.invite(self.user3, self.user4, self.assignment) group = Group.lookup(self.user3, self.assignment) group.accept(self.user4) okversion = Version(name="ok-client", current_version="v1.5.0", download_link="http://localhost/ok") db.session.add(okversion) db.session.commit()
def submit_assignment(name): # TODO: Unify student & staff upload. assign = get_assignment(name) group = Group.lookup(current_user, assign) user_ids = assign.active_user_ids(current_user.id) fs = assign.final_submission(user_ids) if not assign.uploads_enabled: flash("This assignment cannot be submitted online", 'warning') return redirect(url_for('.assignment', name=assign.name)) extension = None # No need for an extension if not assign.active: extension = Extension.get_extension(current_user, assign) if not extension: flash("It's too late to submit this assignment", 'warning') return redirect(url_for('.assignment', name=assign.name)) if request.method == "POST": backup = Backup.create( submitter=current_user, assignment=assign, submit=True, ) assignment = backup.assignment if extension: backup.custom_submission_time = extension.custom_submission_time templates = assignment.files or [] files = {} def extract_file_index(file_ind): """ Get the index of of file objects. Used because request.files.getlist() does not handle uniquely indexed lists. >>> extract_file_index('file[12']) 12 """ brace_loc = file_ind.find('[') index_str = file_ind[brace_loc+1:-1] return int(index_str) # A list of one element lists sorted_uploads = sorted(list(request.files.items()), key=lambda x: extract_file_index(x[0])) uploads = [v[1] for v in sorted_uploads] full_path_names = list(request.form.listvalues())[0] template_files = assign.files or [] file_names = [os.path.split(f)[1] for f in full_path_names] missing = [t for t in template_files if t not in file_names] if missing: return jsonify({ 'error': ('Missing files: {}. The following files are required: {}' .format(', '.join(missing), ', '.join(template_files))) }), 400 backup_folder_postfix = time.time() for full_path, upload in zip(full_path_names, uploads): data = upload.read() if len(data) > MAX_UPLOAD_FILE_SIZE: # file is too large (over 25 MB) return jsonify({ 'error': ('{} is larger than the maximum file size of {} MB' .format(full_path, MAX_UPLOAD_FILE_SIZE/1024/1024)) }), 400 try: files[full_path] = str(data, 'utf-8') except UnicodeDecodeError: upload.stream.seek(0) # We've already read data, so reset before uploading dest_folder = "uploads/{}/{}/{}/".format(assign.name, current_user.id, backup_folder_postfix) bin_file = ExternalFile.upload(upload.stream, current_user.id, full_path, staff_file=False, prefix=dest_folder, course_id=assign.course.id, backup=backup, assignment_id=assign.id) db.session.add(bin_file) message = Message(kind='file_contents', contents=files) backup.messages.append(message) db.session.add(backup) db.session.commit() # Send to continuous autograder if assign.autograding_key and assign.continuous_autograding: try: submit_continuous(backup) except ValueError as e: flash('Did not send to autograder: {}'.format(e), 'warning') return jsonify({ 'backup': backup.hashid, 'url': url_for('.code', name=assign.name, submit=backup.submit, bid=backup.id) }) return render_template('student/assignment/submit.html', assignment=assign, group=group, course=assign.course)
def send_message(sender, target, header, body): message = Message(target=target, sender=sender, header=header, body=body) message.save() logger.log(Action.ACTION_MESSAGE, 'Message sent', sender)