def add_fake_message(db_session, namespace_id, thread=None, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None, received_date=None, subject='', body='', snippet=''): from inbox.models import Message from inbox.contacts.process_mail import update_contacts_from_message m = Message() m.namespace_id = namespace_id m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = received_date or datetime.utcnow() m.size = 0 m.is_read = False m.is_starred = False m.body = body m.snippet = snippet m.subject = subject if thread: thread.messages.append(m) update_contacts_from_message(db_session, m, thread.namespace) db_session.add(m) db_session.commit() return m
def add_fake_message(db_session, namespace_id, thread=None, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None, received_date=None, subject=None): from inbox.models import Message from inbox.contacts.process_mail import update_contacts_from_message m = Message() m.namespace_id = namespace_id m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = received_date or datetime.utcnow() m.size = 0 m.sanitized_body = '' m.snippet = '' m.subject = subject or '' if thread: thread.messages.append(m) update_contacts_from_message(db_session, m, thread.namespace) db_session.add(m) db_session.commit() return m
def create_imap_message(db_session, log, account, folder, msg): """ IMAP-specific message creation logic. This is the one function in this file that gets to take an account object instead of an account_id, because we need to relate the account to ImapUids for versioning to work, since it needs to look up the namespace. Returns ------- imapuid : inbox.models.tables.imap.ImapUid New db object, which links to new Message and Block objects through relationships. All new objects are uncommitted. """ new_msg = Message(account=account, mid=msg.uid, folder_name=folder.name, received_date=msg.internaldate, flags=msg.flags, body_string=msg.body) imapuid = ImapUid(account=account, folder=folder, msg_uid=msg.uid, message=new_msg) imapuid.update_imap_flags(msg.flags, msg.g_labels) new_msg.is_draft = imapuid.is_draft new_msg.is_read = imapuid.is_seen update_contacts_from_message(db_session, new_msg, account.id) # NOTE: This might be a good place to add FolderItem entries for # non-Gmail backends. return imapuid
def create_imap_message(db_session, log, account, folder, msg): """ IMAP-specific message creation logic. This is the one function in this file that gets to take an account object instead of an account_id, because we need to relate the account to ImapUids for versioning to work, since it needs to look up the namespace. Returns ------- imapuid : inbox.models.tables.imap.ImapUid New db object, which links to new Message and Block objects through relationships. All new objects are uncommitted. """ new_msg = Message.create_from_synced(account=account, mid=msg.uid, folder_name=folder.name, received_date=msg.internaldate, body_string=msg.body) # Check to see if this is a copy of a message that was first created # by the Inbox API. If so, don't create a new object; just use the old one. existing_copy = reconcile_message(new_msg, db_session) if existing_copy is not None: new_msg = existing_copy imapuid = ImapUid(account=account, folder=folder, msg_uid=msg.uid, message=new_msg) imapuid.update_flags_and_labels(msg.flags, msg.g_labels) new_msg.is_draft = imapuid.is_draft new_msg.is_read = imapuid.is_seen update_contacts_from_message(db_session, new_msg, account.namespace) return imapuid
def create_imap_message(db_session, account, folder, msg): """ IMAP-specific message creation logic. Returns ------- imapuid : inbox.models.backends.imap.ImapUid New db object, which links to new Message and Block objects through relationships. All new objects are uncommitted. """ new_message = Message.create_from_synced( account=account, mid=msg.uid, folder_name=folder.name, received_date=msg.internaldate, body_string=msg.body ) # Check to see if this is a copy of a message that was first created # by the Nylas API. If so, don't create a new object; just use the old one. existing_copy = reconcile_message(new_message, db_session) if existing_copy is not None: new_message = existing_copy imapuid = ImapUid(account=account, folder=folder, msg_uid=msg.uid, message=new_message) imapuid.update_flags(msg.flags) if msg.g_labels is not None: imapuid.update_labels(msg.g_labels) # Update the message's metadata with db_session.no_autoflush: is_draft = imapuid.is_draft and (folder.canonical_name == "drafts" or folder.canonical_name == "all") update_message_metadata(db_session, account, new_message, is_draft) update_contacts_from_message(db_session, new_message, account.namespace) return imapuid
def add_fake_message(db_session, namespace_id, thread=None, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None, received_date=None, subject='', body='', snippet='', add_sent_category=False): from inbox.models import Message, Category from inbox.contacts.process_mail import update_contacts_from_message m = Message() m.namespace_id = namespace_id m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = received_date or datetime.utcnow() m.size = 0 m.is_read = False m.is_starred = False m.body = body m.snippet = snippet m.subject = subject if thread: thread.messages.append(m) update_contacts_from_message(db_session, m, thread.namespace) db_session.add(m) db_session.commit() if add_sent_category: category = Category.find_or_create( db_session, namespace_id, 'sent', 'sent', type_='folder') if category not in m.categories: m.categories.add(category) db_session.commit() return m
def add_fake_message(account_id, thread, to_email, received_date, db_session): """ One-off helper function to add 'fake' messages to the datastore.""" m = Message() m.from_addr = [('', to_email)] m.received_date = received_date m.size = 0 m.sanitized_body = '' m.snippet = '' m.thread = thread update_contacts_from_message(db_session, m, account_id) db_session.add(m) db_session.commit()
def add_fake_message(db_session, namespace_id, thread=None, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None, received_date=None, subject='', body='', snippet='', g_msgid=None, add_sent_category=False): from inbox.models import Message, Category from inbox.contacts.process_mail import update_contacts_from_message m = Message() m.namespace_id = namespace_id m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = received_date or datetime.utcnow() m.size = 0 m.is_read = False m.is_starred = False m.body = body m.snippet = snippet m.subject = subject m.g_msgid = g_msgid if thread: thread.messages.append(m) update_contacts_from_message(db_session, m, thread.namespace) db_session.add(m) db_session.commit() if add_sent_category: category = Category.find_or_create(db_session, namespace_id, 'sent', 'sent', type_='folder') if category not in m.categories: m.categories.add(category) db_session.commit() return m
def add_fake_message(db_session, thread, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None): m = Message() m.namespace_id = NAMESPACE_ID m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = datetime.utcnow() m.size = 0 m.sanitized_body = '' m.snippet = '' m.thread = thread update_contacts_from_message(db_session, m, thread.namespace) db_session.add(m) db_session.commit() return m
def add_fake_message(db_session, thread, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None): m = Message() m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = datetime.utcnow() m.size = 0 m.sanitized_body = '' m.snippet = '' m.thread = thread account_id = thread.namespace.account_id update_contacts_from_message(db_session, m, account_id) db_session.add(m) db_session.commit() return m
def add_fake_message(db_session, namespace_id, thread, from_addr=None, to_addr=None, cc_addr=None, bcc_addr=None, received_date=None, subject=None): from inbox.models import Message from inbox.contacts.process_mail import update_contacts_from_message m = Message() m.namespace_id = namespace_id m.from_addr = from_addr or [] m.to_addr = to_addr or [] m.cc_addr = cc_addr or [] m.bcc_addr = bcc_addr or [] m.received_date = received_date or datetime.utcnow() m.size = 0 m.sanitized_body = '' m.snippet = '' m.subject = subject or '' m.thread = thread update_contacts_from_message(db_session, m, thread.namespace) db_session.add(m) db_session.commit() return m
def create_imap_message(db_session, account, folder, msg): """ IMAP-specific message creation logic. Returns ------- imapuid : inbox.models.backends.imap.ImapUid New db object, which links to new Message and Block objects through relationships. All new objects are uncommitted. """ new_message = Message.create_from_synced(account=account, mid=msg.uid, folder_name=folder.name, received_date=msg.internaldate, body_string=msg.body) # Check to see if this is a copy of a message that was first created # by the Inbox API. If so, don't create a new object; just use the old one. existing_copy = reconcile_message(new_message, db_session) if existing_copy is not None: new_message = existing_copy imapuid = ImapUid(account=account, folder=folder, msg_uid=msg.uid, message=new_message) imapuid.update_flags(msg.flags) if msg.g_labels is not None: imapuid.update_labels(msg.g_labels) # Update the message's metadata with db_session.no_autoflush: is_draft = imapuid.is_draft and (folder.canonical_name == 'drafts' or folder.canonical_name == 'all') update_message_metadata(db_session, account, new_message, is_draft) update_contacts_from_message(db_session, new_message, account.namespace) return imapuid
def update_draft(db_session, account, draft, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, from_addr=None, reply_to=None): """ Update draft with new attributes. """ def update(attr, value=None): if value is not None: setattr(draft, attr, value) if attr == 'body': # Update size, snippet too draft.size = len(value) draft.snippet = draft.calculate_html_snippet( value) update('to_addr', to_addr) update('cc_addr', cc_addr) update('bcc_addr', bcc_addr) update('reply_to', reply_to) update('from_addr', from_addr) update('subject', subject if subject else None) update('body', body if body else None) update('received_date', datetime.utcnow()) # Remove any attachments that aren't specified new_block_ids = [b.id for b in blocks] for part in filter(lambda x: x.block_id not in new_block_ids, draft.parts): draft.parts.remove(part) db_session.delete(part) # Parts require special handling for block in blocks: # Don't re-add attachments that are already attached if block.id in [p.block_id for p in draft.parts]: continue part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True draft.parts.append(part) thread = draft.thread if len(thread.messages) == 1: # If there are no prior messages on the thread, update its subject and # dates to match the draft. thread.subject = draft.subject thread.subjectdate = draft.received_date thread.recentdate = draft.received_date # Remove previous message-contact associations, and create new ones. draft.contacts = [] update_contacts_from_message(db_session, draft, account.namespace) # The draft we're updating may or may not be one authored through the API: # - Ours: is_created = True, Message-Id = public_id+version # - Not Ours: is_created = False, Message-Id = ??? # Mark that the draft is now created by us draft.is_created = True # Save the current Message-Id so we know which draft to delete in syncback old_message_id_header = draft.message_id_header # Increment version and rebuild the message ID header. draft.version += 1 draft.regenerate_nylas_uid() # Sync to remote schedule_action('update_draft', draft, draft.namespace.id, db_session, version=draft.version, old_message_id_header=old_message_id_header) db_session.commit() return draft
def update_draft(db_session, account, draft, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, from_addr=None, reply_to=None): """ Update draft with new attributes. """ def update(attr, value=None): if value is not None: setattr(draft, attr, value) if attr == 'body': # Update size, snippet too draft.size = len(value) draft.snippet = draft.calculate_html_snippet(value) update('to_addr', to_addr) update('cc_addr', cc_addr) update('bcc_addr', bcc_addr) update('reply_to', reply_to) update('from_addr', from_addr) update('subject', subject if subject else None) update('body', body if body else None) update('received_date', datetime.utcnow()) # Remove any attachments that aren't specified new_block_ids = [b.id for b in blocks] for part in filter(lambda x: x.block_id not in new_block_ids, draft.parts): draft.parts.remove(part) db_session.delete(part) # Parts require special handling for block in blocks: # Don't re-add attachments that are already attached if block.id in [p.block_id for p in draft.parts]: continue part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True draft.parts.append(part) thread = draft.thread if len(thread.messages) == 1: # If there are no prior messages on the thread, update its subject and # dates to match the draft. thread.subject = draft.subject thread.subjectdate = draft.received_date thread.recentdate = draft.received_date # Remove previous message-contact associations, and create new ones. draft.contacts = [] update_contacts_from_message(db_session, draft, account.namespace) # The draft we're updating may or may not be one authored through the API: # - Ours: is_created = True, Message-Id = public_id+version # - Not Ours: is_created = False, Message-Id = ??? # Mark that the draft is now created by us draft.is_created = True # Save the current Message-Id so we know which draft to delete in syncback old_message_id_header = draft.message_id_header # Increment version and rebuild the message ID header. draft.version += 1 draft.regenerate_nylas_uid() # Sync to remote schedule_action('update_draft', draft, draft.namespace.id, db_session, version=draft.version, old_message_id_header=old_message_id_header) db_session.commit() return draft
def create_draft(data, namespace, db_session, syncback): """ Construct a draft object (a Message instance) from `data`, a dictionary representing the POST body of an API request. All new objects are added to the session, but not committed.""" # Validate the input and get referenced objects (thread, attachments) # as necessary. to_addr = get_recipients(data.get('to'), 'to') cc_addr = get_recipients(data.get('cc'), 'cc') bcc_addr = get_recipients(data.get('bcc'), 'bcc') from_addr = get_recipients(data.get('from'), 'from') reply_to = get_recipients(data.get('reply_to'), 'reply_to') if from_addr and len(from_addr) > 1: raise InputError("from_addr field can have at most one item") if reply_to and len(reply_to) > 1: raise InputError("reply_to field can have at most one item") subject = data.get('subject') if subject is not None and not isinstance(subject, basestring): raise InputError('"subject" should be a string') body = data.get('body', '') if not isinstance(body, basestring): raise InputError('"body" should be a string') blocks = get_attachments(data.get('file_ids'), namespace.id, db_session) reply_to_thread = get_thread(data.get('thread_id'), namespace.id, db_session) reply_to_message = get_message(data.get('reply_to_message_id'), namespace.id, db_session) if reply_to_message is not None and reply_to_thread is not None: if reply_to_message not in reply_to_thread.messages: raise InputError('Message {} is not in thread {}'. format(reply_to_message.public_id, reply_to_thread.public_id)) with db_session.no_autoflush: account = namespace.account dt = datetime.utcnow() uid = generate_public_id() to_addr = to_addr or [] cc_addr = cc_addr or [] bcc_addr = bcc_addr or [] blocks = blocks or [] if subject is None: # If this is a reply with no explicitly specified subject, set the # subject from the prior message/thread by default. # TODO(emfree): Do we want to allow changing the subject on a reply # at all? if reply_to_message is not None: subject = reply_to_message.subject elif reply_to_thread is not None: subject = reply_to_thread.subject subject = subject or '' message = Message() message.namespace = namespace message.is_created = True message.is_draft = True message.from_addr = from_addr if from_addr else \ [(account.name, account.email_address)] # TODO(emfree): we should maybe make received_date nullable, so its # value doesn't change in the case of a drafted-and-later-reconciled # message. message.received_date = dt message.subject = subject message.body = body message.to_addr = to_addr message.cc_addr = cc_addr message.bcc_addr = bcc_addr message.reply_to = reply_to # TODO(emfree): this is different from the normal 'size' value of a # message, which is the size of the entire MIME message. message.size = len(body) message.is_read = True message.is_sent = False message.public_id = uid message.version = 0 message.regenerate_inbox_uid() # Set the snippet message.snippet = message.calculate_html_snippet(body) # Associate attachments to the draft message for block in blocks: # Create a new Part object to associate to the message object. # (You can't just set block.message, because if block is an # attachment on an existing message, that would dissociate it from # the existing message.) part = Part(block=block) part.namespace_id = namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True message.parts.append(part) update_contacts_from_message(db_session, message, namespace) if reply_to_message is not None: message.is_reply = True _set_reply_headers(message, reply_to_message) thread = reply_to_message.thread message.reply_to_message = reply_to_message elif reply_to_thread is not None: message.is_reply = True thread = reply_to_thread # Construct the in-reply-to and references headers from the last # message currently in the thread. previous_messages = [m for m in thread.messages if not m.is_draft] if previous_messages: last_message = previous_messages[-1] message.reply_to_message = last_message _set_reply_headers(message, last_message) else: # If this isn't a reply to anything, create a new thread object for # the draft. We specialize the thread class so that we can, for # example, add the g_thrid for Gmail later if we reconcile a synced # message with this one. This is a huge hack, but works. message.is_reply = False thread_cls = account.thread_cls thread = thread_cls( subject=message.subject, recentdate=message.received_date, namespace=namespace, subjectdate=message.received_date) message.thread = thread db_session.add(message) if syncback: schedule_action('save_draft', message, namespace.id, db_session, version=message.version) db_session.flush() return message
def update_draft(db_session, account, draft, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, from_addr=None, reply_to=None): """ Update draft with new attributes. """ def update(attr, value=None): if value is not None: setattr(draft, attr, value) if attr == 'body': # Update size, snippet too draft.size = len(value) draft.snippet = draft.calculate_html_snippet( value) update('to_addr', to_addr) update('cc_addr', cc_addr) update('bcc_addr', bcc_addr) update('reply_to', reply_to) update('from_addr', from_addr) update('subject', subject if subject else None) update('body', body if body else None) update('received_date', datetime.utcnow()) # Remove any attachments that aren't specified new_block_ids = [b.id for b in blocks] for part in filter(lambda x: x.block_id not in new_block_ids, draft.parts): draft.parts.remove(part) db_session.delete(part) # Parts require special handling for block in blocks: # Don't re-add attachments that are already attached if block.id in [p.block_id for p in draft.parts]: continue part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True draft.parts.append(part) thread = draft.thread if len(thread.messages) == 1: # If there are no prior messages on the thread, update its subject and # dates to match the draft. thread.subject = draft.subject thread.subjectdate = draft.received_date thread.recentdate = draft.received_date # Remove previous message-contact associations, and create new ones. draft.contacts = [] update_contacts_from_message(db_session, draft, account.namespace) prior_inbox_uid = draft.inbox_uid prior_message_id_header = draft.message_id_header # Update version + inbox_uid (is_created is already set) draft.version += 1 draft.regenerate_inbox_uid() # Sync to remote schedule_action('save_draft', draft, draft.namespace.id, db_session, version=draft.version) # Delete previous version on remote schedule_action('delete_draft', draft, draft.namespace.id, db_session, inbox_uid=prior_inbox_uid, message_id_header=prior_message_id_header) db_session.commit() return draft
def update_draft(db_session, account, original_draft, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, tags=None): """ Update draft. To maintain our messages are immutable invariant, we create a new draft message object. Returns ------- Message The new draft message object. Notes ----- Messages, including draft messages, are immutable in Inbox. So to update a draft, we create a new draft message object and return its public_id (which is different than the original's). """ def update(attr, value=None): if value is not None: setattr(original_draft, attr, value) if attr == 'sanitized_body': # Update size, snippet too original_draft.size = len(value) original_draft.snippet = original_draft.calculate_html_snippet( value) update('to_addr', to_addr) update('cc_addr', cc_addr) update('bcc_addr', bcc_addr) update('subject', subject if subject else None) update('sanitized_body', body if body else None) update('received_date', datetime.utcnow()) # Remove any attachments that aren't specified new_block_ids = [b.id for b in blocks] for part in filter(lambda x: x.block_id not in new_block_ids, original_draft.parts): original_draft.parts.remove(part) db_session.delete(part) # Parts, tags require special handling for block in blocks: # Don't re-add attachments that are already attached if block.id in [p.block_id for p in original_draft.parts]: continue part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True original_draft.parts.append(part) db_session.add(part) thread = original_draft.thread if tags: tags_to_keep = {tag for tag in thread.tags if not tag.user_created} thread.tags = tags | tags_to_keep # Remove previous message-contact associations, and create new ones. original_draft.contacts = [] update_contacts_from_message(db_session, original_draft, account.namespace) # Delete previous version on remote schedule_action('delete_draft', original_draft, original_draft.namespace.id, db_session, inbox_uid=original_draft.inbox_uid, message_id_header=original_draft.message_id_header) # Update version + inbox_uid (is_created is already set) version = generate_public_id() update('version', version) update('inbox_uid', version) # Sync to remote schedule_action('save_draft', original_draft, original_draft.namespace.id, db_session) db_session.commit() return original_draft
def create_and_save_draft(db_session, account, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, new_tags=None, thread=None, is_reply=False, syncback=True): """Create a draft object and commit it to the database.""" with db_session.no_autoflush: dt = datetime.utcnow() uid = generate_public_id() version = generate_public_id() to_addr = to_addr or [] cc_addr = cc_addr or [] bcc_addr = bcc_addr or [] blocks = blocks or [] body = body or '' if subject is None and thread is not None: # Set subject from thread by default. subject = thread.subject subject = subject or '' message = Message() message.namespace = account.namespace message.is_created = True message.is_draft = True message.state = 'draft' message.from_addr = [(account.name, account.email_address)] # TODO(emfree): we should maybe make received_date nullable, so its # value doesn't change in the case of a drafted-and-later-reconciled # message. message.received_date = dt message.subject = subject message.sanitized_body = body message.to_addr = to_addr message.cc_addr = cc_addr message.bcc_addr = bcc_addr # TODO(emfree): this is different from the normal 'size' value of a # message, which is the size of the entire MIME message. message.size = len(body) message.is_read = True message.is_sent = False message.is_reply = is_reply message.public_id = uid message.version = version message.inbox_uid = version # Set the snippet message.snippet = message.calculate_html_snippet(body) # Associate attachments to the draft message for block in blocks: # Create a new Part object to associate to the message object. # (You can't just set block.message, because if block is an # attachment on an existing message, that would dissociate it from # the existing message.) part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True message.parts.append(part) db_session.add(part) update_contacts_from_message(db_session, message, account.namespace) if is_reply: message.is_reply = True # Construct the in-reply-to and references headers from the last # message currently in the thread. _set_reply_headers(message, thread) if thread is None: # Create a new thread object for the draft. # We specialize the thread class so that we can, for example, add # the g_thrid for Gmail later if we reconcile a synced message with # this one. This is a huge hack, but works. thread_cls = account.thread_cls thread = thread_cls(subject=message.subject, recentdate=message.received_date, namespace=account.namespace, subjectdate=message.received_date) db_session.add(thread) message.thread = thread thread.apply_tag(account.namespace.tags['drafts']) if new_tags: tags_to_keep = {tag for tag in thread.tags if not tag.user_created} thread.tags = new_tags | tags_to_keep if syncback: schedule_action('save_draft', message, message.namespace.id, db_session) db_session.add(message) db_session.commit() return message
def update_draft(db_session, account, draft, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, from_addr=None, reply_to=None): """ Update draft with new attributes. """ def update(attr, value=None): if value is not None: setattr(draft, attr, value) if attr == 'body': # Update size, snippet too draft.size = len(value) draft.snippet = draft.calculate_html_snippet(value) update('to_addr', to_addr) update('cc_addr', cc_addr) update('bcc_addr', bcc_addr) update('reply_to', reply_to) update('from_addr', from_addr) update('subject', subject if subject else None) update('body', body if body else None) update('received_date', datetime.utcnow()) # Remove any attachments that aren't specified new_block_ids = [b.id for b in blocks] for part in filter(lambda x: x.block_id not in new_block_ids, draft.parts): draft.parts.remove(part) db_session.delete(part) # Parts require special handling for block in blocks: # Don't re-add attachments that are already attached if block.id in [p.block_id for p in draft.parts]: continue part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True draft.parts.append(part) thread = draft.thread if len(thread.messages) == 1: # If there are no prior messages on the thread, update its subject and # dates to match the draft. thread.subject = draft.subject thread.subjectdate = draft.received_date thread.recentdate = draft.received_date # Remove previous message-contact associations, and create new ones. draft.contacts = [] update_contacts_from_message(db_session, draft, account.namespace) # Update version + inbox_uid (is_created is already set) draft.version += 1 draft.regenerate_inbox_uid() # Sync to remote schedule_action('update_draft', draft, draft.namespace.id, db_session, version=draft.version) db_session.commit() return draft
def create_message_from_json(data, namespace, db_session, is_draft): """ Construct a Message instance from `data`, a dictionary representing the POST body of an API request. All new objects are added to the session, but not committed.""" # Validate the input and get referenced objects (thread, attachments) # as necessary. to_addr = get_recipients(data.get('to'), 'to') cc_addr = get_recipients(data.get('cc'), 'cc') bcc_addr = get_recipients(data.get('bcc'), 'bcc') from_addr = get_recipients(data.get('from'), 'from') reply_to = get_recipients(data.get('reply_to'), 'reply_to') if from_addr and len(from_addr) > 1: raise InputError("from_addr field can have at most one item") if reply_to and len(reply_to) > 1: raise InputError("reply_to field can have at most one item") subject = data.get('subject') if subject is not None and not isinstance(subject, basestring): raise InputError('"subject" should be a string') body = data.get('body', '') if not isinstance(body, basestring): raise InputError('"body" should be a string') blocks = get_attachments(data.get('file_ids'), namespace.id, db_session) reply_to_thread = get_thread(data.get('thread_id'), namespace.id, db_session) reply_to_message = get_message(data.get('reply_to_message_id'), namespace.id, db_session) if reply_to_message is not None and reply_to_thread is not None: if reply_to_message not in reply_to_thread.messages: raise InputError('Message {} is not in thread {}'.format( reply_to_message.public_id, reply_to_thread.public_id)) with db_session.no_autoflush: account = namespace.account dt = datetime.utcnow() uid = generate_public_id() to_addr = to_addr or [] cc_addr = cc_addr or [] bcc_addr = bcc_addr or [] blocks = blocks or [] if subject is None: # If this is a reply with no explicitly specified subject, set the # subject from the prior message/thread by default. # TODO(emfree): Do we want to allow changing the subject on a reply # at all? if reply_to_message is not None: subject = reply_to_message.subject elif reply_to_thread is not None: subject = reply_to_thread.subject subject = subject or '' message = Message() message.namespace = namespace message.is_created = True message.is_draft = is_draft message.from_addr = from_addr if from_addr else \ [(account.name, account.email_address)] # TODO(emfree): we should maybe make received_date nullable, so its # value doesn't change in the case of a drafted-and-later-reconciled # message. message.received_date = dt message.subject = subject message.body = body message.to_addr = to_addr message.cc_addr = cc_addr message.bcc_addr = bcc_addr message.reply_to = reply_to # TODO(emfree): this is different from the normal 'size' value of a # message, which is the size of the entire MIME message. message.size = len(body) message.is_read = True message.is_sent = False message.public_id = uid message.version = 0 message.regenerate_inbox_uid() # Set the snippet message.snippet = message.calculate_html_snippet(body) # Associate attachments to the draft message for block in blocks: # Create a new Part object to associate to the message object. # (You can't just set block.message, because if block is an # attachment on an existing message, that would dissociate it from # the existing message.) part = Part(block=block) part.namespace_id = namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True message.parts.append(part) update_contacts_from_message(db_session, message, namespace) if reply_to_message is not None: message.is_reply = True _set_reply_headers(message, reply_to_message) thread = reply_to_message.thread message.reply_to_message = reply_to_message elif reply_to_thread is not None: message.is_reply = True thread = reply_to_thread # Construct the in-reply-to and references headers from the last # message currently in the thread. previous_messages = [m for m in thread.messages if not m.is_draft] if previous_messages: last_message = previous_messages[-1] message.reply_to_message = last_message _set_reply_headers(message, last_message) else: # If this isn't a reply to anything, create a new thread object for # the draft. We specialize the thread class so that we can, for # example, add the g_thrid for Gmail later if we reconcile a synced # message with this one. This is a huge hack, but works. message.is_reply = False thread_cls = account.thread_cls thread = thread_cls(subject=message.subject, recentdate=message.received_date, namespace=namespace, subjectdate=message.received_date) message.thread = thread db_session.add(message) if is_draft: schedule_action('save_draft', message, namespace.id, db_session, version=message.version) db_session.flush() return message
def create_and_save_draft(db_session, account, to_addr=None, subject=None, body=None, blocks=None, cc_addr=None, bcc_addr=None, new_tags=None, thread=None, is_reply=False, syncback=True): """Create a draft object and commit it to the database.""" with db_session.no_autoflush: dt = datetime.utcnow() uid = generate_public_id() version = generate_public_id() to_addr = to_addr or [] cc_addr = cc_addr or [] bcc_addr = bcc_addr or [] blocks = blocks or [] body = body or '' if subject is None and thread is not None: # Set subject from thread by default. subject = thread.subject subject = subject or '' message = Message() message.namespace = account.namespace message.is_created = True message.is_draft = True message.state = 'draft' message.from_addr = [(account.name, account.email_address)] # TODO(emfree): we should maybe make received_date nullable, so its # value doesn't change in the case of a drafted-and-later-reconciled # message. message.received_date = dt message.subject = subject message.sanitized_body = body message.to_addr = to_addr message.cc_addr = cc_addr message.bcc_addr = bcc_addr # TODO(emfree): this is different from the normal 'size' value of a # message, which is the size of the entire MIME message. message.size = len(body) message.is_read = True message.is_sent = False message.is_reply = is_reply message.public_id = uid message.version = version message.inbox_uid = version # Set the snippet message.snippet = message.calculate_html_snippet(body) # Associate attachments to the draft message for block in blocks: # Create a new Part object to associate to the message object. # (You can't just set block.message, because if block is an # attachment on an existing message, that would dissociate it from # the existing message.) part = Part(block=block) part.namespace_id = account.namespace.id part.content_disposition = 'attachment' part.is_inboxapp_attachment = True message.parts.append(part) db_session.add(part) update_contacts_from_message(db_session, message, account.namespace) if is_reply: message.is_reply = True # Construct the in-reply-to and references headers from the last # message currently in the thread. _set_reply_headers(message, thread) if thread is None: # Create a new thread object for the draft. # We specialize the thread class so that we can, for example, add # the g_thrid for Gmail later if we reconcile a synced message with # this one. This is a huge hack, but works. thread_cls = account.thread_cls thread = thread_cls( subject=message.subject, recentdate=message.received_date, namespace=account.namespace, subjectdate=message.received_date) db_session.add(thread) message.thread = thread thread.apply_tag(account.namespace.tags['drafts']) if new_tags: tags_to_keep = {tag for tag in thread.tags if not tag.user_created} thread.tags = new_tags | tags_to_keep if syncback: schedule_action('save_draft', message, message.namespace.id, db_session) db_session.add(message) db_session.commit() return message