def post(self): ''' Creates a common and corresponding activity. Then common is propagated to all trusted contacts. Errors are stored inside activity. ''' file = self.request.files['common'][0] if file: filebody = file["body"] filename = file['filename'] common = Common(title="New Common", path=filename, contentType=file["content_type"], authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isFile=True) common.save() common.put_attachment(filebody, filename) common.save() self.create_owner_creation_activity(common, "publishes", "common") self.send_creation_to_contacts(CONTACT_PATH, common) logger.info("Common %s successfuly posted." % filename) self.return_json(common.toJson(), 201) else: self.return_failure("No common posted.", 400)
def createMicropost(content): micropost = MicroPost() micropost.author = UserManager.getUser().name micropost.authorKey = UserManager.getUser().key micropost.content = content micropost.isMine = True micropost.save() return micropost
def post(self): ''' Creates a picture and corresponding activity. Then picture is propagated to all trusted contacts. Errors are stored inside activity. ''' filebody = self.request.body filename = self.get_argument("qqfile") try: tag = self.get_argument("tag") except: tag = "all" filetype = mimetypes.guess_type(filename)[0] or \ 'application/octet-stream' if filebody: picture = Picture( title="New Picture", path=filename, contentType=filetype, authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isMine=True, isFile=True, tags=[tag] ) picture.save() picture.put_attachment(content=filebody, name=filename) thumbnail = self.get_thumbnail(filebody, filename, (200, 200)) thbuffer = thumbnail.read() picture.put_attachment(thbuffer, "th_" + filename) thpath = os.path.join(CONFIG.main.path, "th_" + filename) os.remove(thpath) preview = self.get_thumbnail(filebody, filename, (1000, 1000)) picture.put_attachment(preview.read(), "prev_" + filename) os.remove(thpath) picture.save() self.create_owner_creation_activity( picture, "publishes", "picture") self.send_files_to_contacts("pictures/contact/", fields={"json": str(picture.toJson(localized=False))}, files=[("picture", str(picture.path), thbuffer)], tag=tag) logger.info("Picture %s successfuly posted." % filename) self.return_json(picture.toJson(), 201) else: self.return_failure("No picture posted.", 400)
def post(self): ''' Creates a picture and corresponding activity. Then picture is propagated to all trusted contacts. Errors are stored inside activity. ''' filebody = self.request.body filename = self.get_argument("qqfile") try: tag = self.get_argument("tag") except: tag = "all" filetype = mimetypes.guess_type(filename)[0] or \ 'application/octet-stream' if filebody: picture = Picture(title="New Picture", path=filename, contentType=filetype, authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isMine=True, isFile=True, tags=[tag]) picture.save() picture.put_attachment(content=filebody, name=filename) thumbnail = self.get_thumbnail(filebody, filename, (200, 200)) thbuffer = thumbnail.read() picture.put_attachment(thbuffer, "th_" + filename) thpath = os.path.join(CONFIG.main.path, "th_" + filename) os.remove(thpath) preview = self.get_thumbnail(filebody, filename, (1000, 1000)) picture.put_attachment(preview.read(), "prev_" + filename) os.remove(thpath) picture.save() self.create_owner_creation_activity(picture, "publishes", "picture") self.send_files_to_contacts( "pictures/contact/", fields={"json": str(picture.toJson(localized=False))}, files=[("picture", str(picture.path), thbuffer)], tag=tag) logger.info("Picture %s successfuly posted." % filename) self.return_json(picture.toJson(), 201) else: self.return_failure("No picture posted.", 400)
def post(self): """ Creates a picture and corresponding activity. Then picture is propagated to all trusted contacts. Errors are stored inside activity. """ file = self.request.files["picture"][0] if file: filebody = file["body"] picture = Picture( title="New Picture", contentType=file["content_type"], authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isFile=True, ) picture.save() filename = "%s.jpg" % picture._id picture.path = filename picture.put_attachment(filebody, filename) thumbnail = self.get_thumbnail(filebody, filename, (200, 200)) thbuffer = thumbnail.read() picture.put_attachment(thbuffer, "th_" + filename) thpath = os.path.join(CONFIG.main.path, "th_" + filename) os.remove(thpath) preview = self.get_thumbnail(filebody, filename, (1000, 1000)) picture.put_attachment(preview.read(), "prev_" + filename) os.remove(thpath) picture.save() self.create_owner_creation_activity(picture, "publishes", "picture") self.send_files_to_contacts( "pictures/contact/", fields={"json": str(picture.toJson(localized=False))}, files=[("picture", str(picture.path), thbuffer)], ) logger.info("Picture %s successfuly posted." % filename) self.return_json(picture.toJson(), 201) else: self.return_failure("No picture posted.", 400)
def post(self, slug): ''' When post request is received, contact of which slug is equal to slug is retrieved. If its state is Pending or Error, the contact request is send again. ''' logger = logging.getLogger("newebe.contact") self.contact = ContactManager.getContact(slug) owner = UserManager.getUser() if self.contact and self.contact.url != owner.url: try: data = owner.asContact().toJson() client = ContactClient() client.post(self.contact, "contacts/request/", data, self.on_contact_response) except Exception: import traceback logger.error("Error on adding contact:\n %s" % traceback.format_exc()) self.contact.state = STATE_ERROR self.contact.save() else: self.return_failure("Contact does not exist", 404)
def delete(self, id): ''' Deletes the post of which id is equal to postId, add an activity and forwards the delete request to each trusted contact. put instead of delete because tornado does not support body in DELETE requests... ''' micropost = MicroPostManager.get_micropost(id) if micropost: user = UserManager.getUser() if micropost.authorKey == user.key: self.create_owner_deletion_activity( micropost, "deletes", "micropost") self.send_deletion_to_contacts(CONTACT_PATH, micropost) postIndexer = indexer.Indexer() postIndexer.remove_doc(micropost) micropost.delete() self.return_success("Micropost deletion succeeds.") else: self.return_failure("Micropost not found.", 404)
def delete(self, id): ''' Deletes the post of which id is equal to postId, add an activity and forwards the delete request to each trusted contact. put instead of delete because tornado does not support body in DELETE requests... ''' micropost = MicroPostManager.get_micropost(id) if micropost: user = UserManager.getUser() if micropost.authorKey == user.key: self.create_owner_deletion_activity(micropost, "deletes", "micropost") self.send_deletion_to_contacts(CONTACT_PATH, micropost) postIndexer = indexer.Indexer() postIndexer.remove_doc(micropost) micropost.delete() self.return_success("Micropost deletion succeeds.") else: self.return_failure("Micropost not found.", 404)
def get_current_user(self): ''' With tornado, authentication is handled in this method. ''' user = UserManager.getUser() if user: if user.password is None: logger.error("User has no password registered") self.redirect("/#register/password/") else: password = self.get_secure_cookie("password") if not password or \ user.password != hashlib.sha224(password).hexdigest(): logger.error("User is not authenticated") self.redirect("/#login/") else: return user else: logger.error("User is not registered") self.redirect("/#register")
def put(self, key): """ Resend deletion of micropost with *key* as key to the contact given in the posted JSON. Corresponding activity ID is given inside the posted json. Here is the format : {"contactId":"data","activityId":"data"} """ data = self.get_body_as_dict(expectedFields=["contactId", "activityId", "extra"]) if data: contactId = data["contactId"] activityId = data["activityId"] date = data["extra"] contact = ContactManager.getTrustedContact(contactId) activity = ActivityManager.get_activity(activityId) if not contact: self.return_failure("Contact not found", 404) elif not activity: self.return_failure("Activity not found", 404) else: user = UserManager.getUser() picture = Picture(authorKey=user.key, date=date_util.get_date_from_db_date(date)) info = "Attempt to resend a picture deletion to contact: {}." logger.info(info.format(contact.name)) self.forward_to_contact(picture, contact, activity, method="PUT") else: self.return_failure("Micropost not found", 404)
def get_current_user(self): ''' With tornado, authentication is handled in this method. ''' user = UserManager.getUser() if user: if user.password is None: logger.error("User has no password registered") self.redirect("/#register/password/") else: #password = self.get_secure_cookie("password") # if not password or \ # user.password != hashlib.sha224(password).hexdigest(): # logger.error("User is not authenticated") # self.redirect("/#login/") #else: return user else: logger.error("User is not registered") self.redirect("/#register")
def on_picture_found(self, picture, id): ''' ''' self.picture = picture data = dict() data["picture"] = picture.toDict(localized=False) data["contact"] = UserManager.getUser().asContact().toDict() print CURRENT_DOWNLOADS print "data picture id %s" % data["picture"]["_id"] for download in CURRENT_DOWNLOADS: print "download %s " % download if download == data["picture"]["_id"]: return self.return_success('already downloading') CURRENT_DOWNLOADS.append(data["picture"]["_id"]) contact = ContactManager.getTrustedContact(picture.authorKey) client = ContactClient() body = json_encode(data) try: client.post(contact, u"pictures/contact/download/", body, self.on_download_finished) except HTTPError: self.return_failure("Cannot download picture from contact.")
def post(self): ''' Create a new user (if user exists, error response is returned) from sent data (user object at JSON format). ''' if UserManager.getUser(): self.return_failure("User already exists.") else: data = self.get_body_as_dict(expectedFields=["name"]) if data: user = User() user.name = data['name'] user.save() user.key = user._id user.save() self.return_json(user.toJson(), 201) else: self.return_failure( "Data are not correct. User has not been created.", 400)
def put(self, key): ''' Resend deletion of micropost with *key* as key to the contact given in the posted JSON. Corresponding activity ID is given inside the posted json. Here is the format : {"contactId":"data","activityId":"data"} ''' data = self.get_body_as_dict( expectedFields=["contactId", "activityId", "extra"]) if data: contactId = data["contactId"] activityId = data["activityId"] date = data["extra"] contact = ContactManager.getTrustedContact(contactId) activity = ActivityManager.get_activity(activityId) if not contact: self.return_failure("Contact not found", 404) elif not activity: self.return_failure("Activity not found", 404) else: user = UserManager.getUser() micropost = MicroPost( authorKey=user.key, date=date_util.get_date_from_db_date(date) ) logger.info( "Attempt to resend a post deletion to contact: {}.".format( contact.name)) httpClient = ContactClient() body = micropost.toJson(localized=False) try: httpClient.put(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") if response.error: self.return_failure( "Deleting micropost to contact failed.") else: for error in activity.errors: if error["contactKey"] == contact.key: activity.errors.remove(error) activity.save() self.return_success( "Micropost correctly redeleted.") except: self.return_failure("Deleting micropost to contact failed.") else: self.return_failure("Micropost not found", 404)
def post(self, slug): ''' When post request is received, contact of which slug is equal to slug is retrieved. If its state is Pending or Error, the contact request is send again. ''' logger = logging.getLogger("newebe.contact") self.contact = ContactManager.getContact(slug) owner = UserManager.getUser() if self.contact and self.contact.url != owner.url: try: data = owner.asContact().toJson() client = ContactClient() client.post(self.contact, "contacts/request/", data, self.on_contact_response) except Exception: import traceback logger.error("Error on adding contact:\n %s" % traceback.format_exc()) self.contact.state = STATE_ERROR self.contact.save() self.return_one_document(self.contact) else: self.return_failure("Contact does not exist", 404)
def post(self, postId): """ Grab from contact the file corresponding to given path and given post (post of which ID is equal to *postId*). """ data = self.get_body_as_dict(expectedFields=["path"]) micropost = MicroPostManager.get_micropost(postId) contact = ContactManager.getTrustedContact(micropost.authorKey) user = UserManager.getUser() if micropost and data and contact: path = data["path"] client = ContactClient() body = {"date": date_util.get_db_date_from_date(micropost.date), "contactKey": user.key, "path": path} client.post( contact, "microposts/contacts/attach/", json_encode(body), callback=(yield gen.Callback("getattach")) ) response = yield gen.Wait("getattach") if response.error: self.return_failure("An error occured while retrieving picture.") else: micropost.put_attachment(response.body, data["path"]) self.return_success("Download succeeds.") else: if not data: self.return_failure("Wrong data.", 400) elif not contact: self.return_failure("Contact no more available.", 400) else: self.return_failure("Micropost not found.", 404)
def post(self): ''' Creates a new contact from web client data (contact object at JSON format). And send a contact request to the newly created contact. State of contact is set to PENDING. ''' logger = logging.getLogger("newebe.contact") data = self.get_body_as_dict(["url"]) if data: url = data["url"] owner = UserManager.getUser() if owner.url != url: slug = slugify(url) self.contact = Contact( url=url, slug=slug ) self.contact.save() try: data = UserManager.getUser().asContact().toJson() client = ContactClient() client.post(self.contact, "contacts/request/", data, self.on_contact_response) except Exception: import traceback logger.error("Error on adding contact:\n %s" % traceback.format_exc()) self.contact.state = STATE_ERROR self.contact.save() return self.return_one_document(self.contact, 201) else: return self.return_failure( "Wrong data. Url is same as owner URL.", 400) else: return self.return_failure( "Wrong data. Contact has not been created.", 400)
def post(self): ''' Creates a picture and corresponding activity. Then picture is propagated to all trusted contacts. Errors are stored inside activity. ''' file = self.request.files['picture'][0] if file: filebody = file["body"] picture = Picture(title="New Picture", contentType=file["content_type"], authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isFile=True) picture.save() filename = '%s.jpg' % picture._id picture.path = filename picture.put_attachment(filebody, filename) thumbnail = self.get_thumbnail(filebody, filename, (200, 200)) thbuffer = thumbnail.read() picture.put_attachment(thbuffer, "th_" + filename) thpath = os.path.join(CONFIG.main.path, "th_" + filename) os.remove(thpath) preview = self.get_thumbnail(filebody, filename, (1000, 1000)) picture.put_attachment(preview.read(), "prev_" + filename) os.remove(thpath) picture.save() self.create_owner_creation_activity(picture, "publishes", "picture") self.send_files_to_contacts( "pictures/contact/", fields={"json": str(picture.toJson(localized=False))}, files=[("picture", str(picture.path), thbuffer)]) logger.info("Picture %s successfuly posted." % filename) self.return_json(picture.toJson(), 201) else: self.return_failure("No picture posted.", 400)
def get(self): ''' Retrieves current user (newebe owner) data at JSON format. ''' user = UserManager.getUser() userDict = user.toDict() del userDict["password"] self.return_json(userDict)
def post(self): ''' Creates a new contact from web client data (contact object at JSON format). And send a contact request to the newly created contact. State of contact is set to PENDING. ''' logger = logging.getLogger("newebe.contact") data = self.get_body_as_dict(["url"]) if data: url = data["url"] owner = UserManager.getUser() if owner.url != url: slug = slugify(url) self.contact = Contact( url=url, slug=slug ) self.contact.save() try: data = UserManager.getUser().asContact().toJson() client = ContactClient() client.post(self.contact, "contacts/request/", data, self.on_contact_response) except Exception: import traceback logger.error("Error on adding contact:\n %s" % traceback.format_exc()) self.contact.state = STATE_ERROR self.contact.save() else: return self.return_failure( "Wrong data. Url is same as owner URL.", 400) else: return self.return_failure( "Wrong data. Contact has not been created.", 400)
def send_picture_to_contact(self, contact): user = UserManager.getUser() picture = user.fetch_attachment("small_picture.jpg") self.send_files_to_contact( contact, "contact/update-profile/picture/", fields={"key": user.key}, files=[("smallpicture", "smallpicture.jpg", picture)] )
def post(self): ''' Creates a common and corresponding activity. Then common is propagated to all trusted contacts. Errors are stored inside activity. ''' filebody = self.request.body filename = self.get_argument("qqfile") try: tag = self.get_argument("tag") except: tag = "all" filetype = mimetypes.guess_type(filename)[0] or \ 'application/octet-stream' if filebody: common = Common( title="New Common", path=filename, contentType=filetype, authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isMine=True, isFile=True, tags=[tag] ) common.save() common.put_attachment(content=filebody, name=filename) common.save() self.create_owner_creation_activity( common, "publishes", "common") self.send_creation_to_contacts(CONTACT_PATH, common) logger.info("Common %s successfuly posted." % filename) self.return_json(common.toJson(), 201) else: self.return_failure("No common posted.", 400)
def get(self): ''' Returns current profile picture as a jpeg file. ''' try: user = UserManager.getUser() file = user.fetch_attachment("picture.jpg") self.return_file("picture.jpg", file) except ResourceNotFound: self.return_failure("Picture not found.", 404)
def get(self, key): ''' Returns an HTML representation of contact corresponding to given ID. If ID is equal to null Newebe owner representation is returned. ''' if key == "null" or key == UserManager.getUser().key: contact = UserManager.getUser().asContact() else: contact = ContactManager.getTrustedContact(key) if contact: #if contact.description: # contact.description = markdown.markdown(contact.description) self.render("templates/contact_render.html", contact=contact) else: return self.return_failure("Contact not found.", 404)
def post(self): ''' Create a new contact from sent data (contact object at JSON format). Sets its status to Wait For Approval ''' data = self.get_body_as_dict(expectedFields=["url"]) if data: url = data["url"] owner = UserManager.getUser() if owner.url != url: slug = slugify(url) contact = ContactManager.getContact(slug) owner = UserManager.getUser() if contact is None: contact = Contact( name=data["name"], url=url, slug=slug, key=data["key"], state=STATE_WAIT_APPROVAL, requestDate=datetime.datetime.utcnow(), description=data["description"] ) contact.save() contact.state = STATE_WAIT_APPROVAL contact.save() for websocket_client in websocket_clients: websocket_client.write_message(contact.toJson()) self.return_success("Request received.") else: self.return_failure("Contact and owner have same url.") else: self.return_failure("Sent data are incorrects.")
def get(self): ''' If no user exist, it redirects to register root page, else it returns register page. ''' if UserManager.getUser(): self.redirect("/") else: self.render("../auth/templates/register.html", isTheme=self.is_file_theme_exists())
def post(self): ''' Creates a common and corresponding activity. Then common is propagated to all trusted contacts. Errors are stored inside activity. ''' filebody = self.request.body filename = self.get_argument("qqfile") try: tag = self.get_argument("tag") except: tag = "all" filetype = mimetypes.guess_type(filename)[0] or \ 'application/octet-stream' if filebody: common = Common(title="New Common", path=filename, contentType=filetype, authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isMine=True, isFile=True, tags=[tag]) common.save() common.put_attachment(content=filebody, name=filename) common.save() self.create_owner_creation_activity(common, "publishes", "common") self.send_creation_to_contacts(CONTACT_PATH, common) logger.info("Common %s successfuly posted." % filename) self.return_json(common.toJson(), 201) else: self.return_failure("No common posted.", 400)
def create_owner_deletion_activity(self, doc, verb, docType): ''' Creates a new activity corresponding to a document deletion made by owner. * doc: The deleted document. * verb: verb linked to this activity. * docType: Type of the deleted document. ''' self.create_deletion_activity( UserManager.getUser().asContact(), doc, verb, docType, True)
def create_owner_deletion_activity(self, doc, verb, docType): ''' Creates a new activity corresponding to a document deletion made by owner. * doc: The deleted document. * verb: verb linked to this activity. * docType: Type of the deleted document. ''' self.create_deletion_activity(UserManager.getUser().asContact(), doc, verb, docType, True)
def given_there_are_3_posts_of_and_3_posts_of_my_contacts( step, nbposts, nbcontactposts): nbposts = int(nbposts) nbcontactposts = int(nbcontactposts) for i in range(1, nbposts + 1): micropost = MicroPost() micropost.author = UserManager.getUser().name micropost.authorKey = UserManager.getUser().key micropost.content = "my content {}".format(i) micropost.date = datetime.datetime(2011, i, 01, 11, 05, 12) micropost.isMine = True micropost.save() for i in range(1, nbcontactposts + 1): micropost = MicroPost() micropost.author = world.user2.name micropost.authorKey = world.user2.key micropost.content = "contact content {}".format(i) micropost.date = datetime.datetime(2011, i, 10, 11, 05, 12) micropost.isMine = False micropost.save()
def save(self): ''' When document is saved, the last modified field is updated to make sure it is always correct. ''' if not self.authorKey: user = UserManager.getUser() self.authorKey = user.key self.author = user.name self.lastModified = datetime.datetime.utcnow() NewebeDocument.save(self)
def get(self): ''' If user does not have password it returns password registration page. ''' user = UserManager.getUser() if user and user.password: self.redirect("/") else: self.render("../auth/templates/password.html", isTheme=self.is_file_theme_exists()) self.render("../auth/templates/password.html", isTheme=self.is_file_theme_exists())
def get(self): user = UserManager.getUser() password = self.get_secure_cookie("password") is_authenticated = password is not None and user is not None and \ user.password == hashlib.sha224(password).hexdigest() userState = { 'registered': user is not None, 'password': user is not None and user.password is not None, 'authenticated': is_authenticated } self.return_json(userState)
def given_there_are_3_posts_of_and_3_posts_of_my_contacts(step, nbposts, nbcontactposts): nbposts = int(nbposts) nbcontactposts = int(nbcontactposts) for i in range(1, nbposts + 1): micropost = MicroPost() micropost.author = UserManager.getUser().name micropost.authorKey = UserManager.getUser().key micropost.content = "my content {}".format(i) micropost.date = datetime.datetime(2011, i, 01, 11, 05, 12) micropost.isMine = True micropost.save() for i in range(1, nbcontactposts + 1): micropost = MicroPost() micropost.author = world.user2.name micropost.authorKey = world.user2.key micropost.content = "contact content {}".format(i) micropost.date = datetime.datetime(2011, i, 10, 11, 05, 12) micropost.isMine = False micropost.save()
def send_profile_to_contacts(self): ''' External methods to not send too much times the changed profile. A timer is set to wait for other modifications before running this function that sends modification requests to every contacts. ''' client = HTTPClient() self.sending_data = False user = UserManager.getUser() jsonbody = user.toJson() activity = Activity( authorKey=user.key, author=user.name, verb="modifies", docType="profile", method="PUT", docId="none", isMine=True ) activity.save() for contact in ContactManager.getTrustedContacts(): try: request = HTTPRequest( "%scontacts/update-profile/" % contact.url, method="PUT", body=jsonbody, validate_cert=False) response = client.fetch(request) if response.error: logger.error(""" Profile sending to a contact failed, error infos are stored inside activity. """) activity.add_error(contact) activity.save() except: logger.error(""" Profile sending to a contact failed, error infos are stored inside activity. """) activity.add_error(contact) activity.save() logger.info("Profile update sent to all contacts.")
def post(self): ''' Creates a common and corresponding activity. Then common is propagated to all trusted contacts. Errors are stored inside activity. ''' file = self.request.files['common'][0] if file: filebody = file["body"] filename = file['filename'] common = Common( title="New Common", path=filename, contentType=file["content_type"], authorKey=UserManager.getUser().key, author=UserManager.getUser().name, isFile=True ) common.save() common.put_attachment(filebody, filename) common.save() self.create_owner_creation_activity( common, "publishes", "common") self.send_creation_to_contacts(CONTACT_PATH, common) logger.info("Common %s successfuly posted." % filename) self.return_json(common.toJson(), 201) else: self.return_failure("No common posted.", 400)
def delete(self, id): """ Deletes picture corresponding to id. """ picture = PictureManager.get_picture(id) if picture: user = UserManager.getUser() if picture.authorKey == user.key: self.create_owner_deletion_activity(picture, "deletes", "picture") self.send_deletion_to_contacts("pictures/contact/", picture) picture.delete() self.return_success("Picture deleted.") else: self.return_failure("Picture not found.", 404)
def post(self): ''' Get password via a form. Set a secure cookie if password is OK then redirects to root page. Else it redirects to login page. ''' password = self.get_argument("password") user = UserManager.getUser() if user and user.password == hashlib.sha224(password).hexdigest(): self.set_secure_cookie("password", password) self.redirect("/") else: self.redirect("/login/")
def get(self): ''' Asks for all contacts to resend their data from last month. As answer contacts send their profile. So contact data are updated, then contacts resend all their from their last month just like they were posted now. Current newebe has to check himself if he already has these data. ''' client = ContactClient() user = UserManager.getUser() self.contacts = dict() for contact in ContactManager.getTrustedContacts(): self.ask_to_contact_for_sync(client, user, contact) self.return_success("", 200)
def delete(self, id): ''' Deletes common corresponding to id. ''' common = CommonManager.get_common(id) if common: user = UserManager.getUser() if common.authorKey == user.key: self.create_owner_deletion_activity( common, "deletes", "common") self.send_deletion_to_contacts("commons/contact/", common) common.delete() self.return_success("Common deleted.") else: self.return_failure("Common not found.", 404)
def delete(self, id): ''' Deletes picture corresponding to id. ''' picture = PictureManager.get_picture(id) if picture: user = UserManager.getUser() if picture.authorKey == user.key: self.create_owner_deletion_activity(picture, "deletes", "picture") self.send_deletion_to_contacts("pictures/contact/", picture) picture.delete() self.return_success("Picture deleted.") else: self.return_failure("Picture not found.", 404)
def delete(self, id): ''' Deletes common corresponding to id. ''' common = CommonManager.get_common(id) if common: user = UserManager.getUser() if common.authorKey == user.key: self.create_owner_deletion_activity(common, "deletes", "common") self.send_deletion_to_contacts("commons/contact/", common) common.delete() self.return_success("Common deleted.") else: self.return_failure("Common not found.", 404)
def set_default_user(self, url=ROOT_URL): ''' Set to DB default user. This is useful for automatic login. ''' self.root_url = url self.user = UserManager.getUser() if self.user: self.user.delete() self.user = User(name="John Doe", password=hashlib.sha224("password").hexdigest(), key="key", authorKey="authorKey", url=url, description="my description") self.user.save()
def on_common_found(self, common, id): ''' ''' self.common = common data = dict() data["common"] = common.toDict(localized=False) data["contact"] = UserManager.getUser().asContact().toDict() contact = ContactManager.getTrustedContact(common.authorKey) client = ContactClient() body = json_encode(data) try: client.post(contact, u"commons/contact/download/", body, self.on_download_finished) except HTTPError: self.return_failure("Cannot download common from contact.")
def post(self): ''' Get password via a json object. Sets a secure cookie if password is OK. Else it returns an error response. ''' data = self.get_body_as_dict(expectedFields=["password"]) if data: password = data["password"] user = UserManager.getUser() if user \ and user.password == hashlib.sha224(password).hexdigest(): self.set_secure_cookie("password", password) self.return_success("You are now logged in.") else: self.return_failure("Wrong password.", 400) else: self.return_failure("Wrong password.", 400)
def post(self): ''' When sync request is received, if contact is a trusted contact, it sends again all posts from last month to contact. ''' client = ContactClient() now = datetime.datetime.utcnow() date = now - datetime.timedelta(365 / 12) contact = self.get_body_as_dict() localContact = ContactManager.getTrustedContact(contact.get("key", "")) if localContact: self.send_posts_to_contact(client, localContact, now, date) self.send_pictures_to_contact(client, localContact, now, date) self.send_commons_to_contact(client, localContact, now, date) self.return_document(UserManager.getUser().asContact()) else: self.return_failure("Contact does not exist.")