def _create_note(self, user, file_name, file_path): note = Note(parent=ndb.Key("User", user.nickname()), title=self.request.get('title'), content=self.request.get('content')) item_titles = self.request.get('checklist_items').split(',') for item_title in item_titles: if not item_title: continue item = CheckListItem(title=item_title) note.checklist_items.append(item) note.put() if file_name and file_path: url, thumbnail_url = self._get_urls_for(file_name) f = NoteFile(parent=note.key, name=file_name, url=url, thumbnail_url=thumbnail_url, full_path=file_path) f.put() note.files.append(f.key) note.put() inc_note_counter()
class CreateNoteHandler(mail_handlers.InboundMailHandler): def _reload_user(self, user_instance): u_loader = UserLoader.query().filter( UserLoader.user == user_instance).get() if u_loader is not None: return u_loader.user ctx = ndb.get_context() ctx.set_cache_policy(lambda key: key.kind() != 'UserLoader') UserLoader(user=user_instance).put() u_loader = UserLoader.query(UserLoader.user == user_instance).get() return u_loader.user def receive(self, mail_message): email_pattern = re.compile(r'([\w\-\.]+@(\w[\w\-]+\.)+[\w\-]+)') match = email_pattern.findall(mail_message.sender) email_addr = match[0][0] if match else '' try: user = users.User(email_addr) user = self._reload_user(user) except users.UserNotFoundError: return self.error(403) title = mail_message.subject content = '' for content_t, body in mail_message.bodies('text/plain'): content += body.decode() attachments = getattr(mail_message, 'attachments', None) self._create_note(user, title, content, attachments) channel.send_message( get_notification_client_id(user), json.dumps("A new note was created! " "Refresh the page to see it.")) @ndb.transactional def _create_note(self, user, title, content, attachments): note = Note(parent=ndb.Key("User", user.nickname()), title=title, content=content) note.put() if attachments: bucket_name = app_identity.get_default_gcs_bucket_name() for file_name, file_content in attachments: content_t = mimetypes.guess_type(file_name)[0] real_path = os.path.join('/', bucket_name, user.user_id(), file_name) with cloudstorage.open(real_path, 'w', content_type=content_t, options={'x-goog-acl': 'public-read'}) as f: f.write(file_content.decode()) key = blobstore.create_gs_key('/gs' + real_path) try: url = images.get_serving_url(key, size=0) thumbnail_url = images.get_serving_url(key, size=150, crop=True) except images.TransformationError, images.NotImageError: url = "http://storage.googleapis.com{}".format(real_path) thumbnail_url = None f = NoteFile(parent=note.key, name=file_name, url=url, thumbnail_url=thumbnail_url, full_path=real_path) f.put() note.files.append(f.key) note.put() inc_note_counter()