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 put(self): ''' Delete picture of which data are given inside request. Picture is found with contact key and creation date. If author is not inside trusted contacts, the request is rejected. ''' data = self.get_body_as_dict() if data: contact = ContactManager.getTrustedContact( data.get("authorKey", "")) if contact: picture = PictureManager.get_contact_picture( contact.key, data.get("date", "")) if picture: self.create_deletion_activity(contact, picture, "deletes", "picture") picture.delete() self.return_success("Deletion succeeds") else: self.return_failure("Author is not trusted.", 400) else: self.return_failure("No data sent.", 405)
def get(self): ''' Retrieves whole contact list at JSON format. ''' contacts = ContactManager.getContacts() self.return_documents(contacts)
def put(self): ''' When a put request is received, contact data are expected. If contact key is one of the trusted contact key, its data are updated with received ones. ''' data = self.get_body_as_dict(["key", "url", "name", "description"]) if data: key = data["key"] contact = ContactManager.getTrustedContact(key) if contact: contact.url = data["url"] contact.description = data["description"] contact.name = data["name"] contact.save() self.create_modify_activity(contact, "modifies", "profile") self.return_success("Contact successfully modified.") else: self.return_failure( "No contact found corresponding to given contact", 404) else: self.return_failure("Empty data or missing field.")
def put(self): ''' When a delete request from a contact is incoming, it executes the delete request locally then it creates a new activity corresponding to this deletion. ''' data = self.get_body_as_dict(expectedFields=["date", "authorKey"]) if data: authorKey = data["authorKey"] date = data["date"] micropost = MicroPostManager.get_contact_micropost(authorKey, date) contact = ContactManager.getTrustedContact(authorKey) if micropost and contact: self.create_deletion_activity(contact, micropost, "deletes", "micropost") micropost.delete() self._write_delete_log(micropost) self.return_success("Micropost deleted.") else: self.return_failure("Micropost not found", 404) else: self.return_failure("No data sent.", 400)
def post(self, key): ''' Resend post 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"} ''' picture = PictureManager.get_picture(key) idInfos = self.request.body ids = json_decode(idInfos) if picture and idInfos: contactId = ids["contactId"] activityId = ids["activityId"] 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: logger.info("Attemp to resend a picture to contact: {}.".format( contact.name)) self.forward_to_contact(picture, contact, activity) else: self.return_failure("Picture not found", 404)
def post(self): ''' Returns file which is attached to post corresponding to a given date (we assumed a user can't post two posts at the same time). Expected data : * path : file name * date : date on which post was posted * contactKey : the key of the contact which claims the file. ''' data = self.get_body_as_dict(expectedFields=["path", "date", "contactKey"]) if data: contact = ContactManager.getTrustedContact(data["contactKey"]) micropost = MicroPostManager.get_first(data["date"]) if micropost and contact: try: fileContent = micropost.fetch_attachment(data["path"]) self.return_file(data["path"], fileContent) except ResourceNotFound: self.return_failure("File not found", 404) else: self.return_failure("Micropost not found.", 404) else: self.return_failure("Wrong data.", 400)
def post(self, key): ''' Resend post 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"} ''' micropost = MicroPostManager.get_micropost(key) data = self.get_body_as_dict(expectedFields=["contactId", "activityId"]) if micropost and data: contactId = data["contactId"] activityId = data["activityId"] 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: if contact.name: logger.info("Attempt to resend a post to contact: %s." % contact.name) self.forward_to_contact(micropost, contact, activity) else: self.return_failure("Micropost not found", 404)
def post(self): ''' Updates contact from sent data (contact object at JSON format). Sets its status to Trusted. ''' data = self.get_body_as_dict(expectedFields=["url", "key", "name"]) if data: url = data["url"] slug = slugify(url) contact = ContactManager.getContact(slug) if contact: contact.state = STATE_TRUSTED contact.key = data["key"] contact.name = data["name"] contact.save() self.return_success("Contact trusted.") else: self.return_failure("No contact for this slug.", 400) else: self.return_failure("Sent data are incorrects.", 400)
def get(self, slug): ''' Retrieves contact corresponding to slug at JSON format. ''' contact = ContactManager.getContact(slug) self.return_one_document_or_404(contact, "Contact does not exist.")
def get(self): ''' Return the list of tags set on owner contacts. ''' tags = ContactManager.getTags() if "all" not in tags: tags.append("all") self.return_list(tags)
def delete(self, slug): ''' Deletes contact corresponding to slug. ''' contact = ContactManager.getContact(slug) if contact: contact.delete() return self.return_success("Contact has been deleted.") else: self.return_failure("Contact does not exist.")
def check_that_request_date_is_set_to_europe_paris_timezone(step, timezone): Contact._db = db2 contact = ContactManager.getRequestedContacts().first() Contact._db = db date = date_util.get_date_from_db_date(world.contacts[0]["requestDate"]) tz = pytz.timezone(timezone) date = date.replace(tzinfo=tz) assert_equals( date_util.convert_utc_date_to_timezone(contact.requestDate, tz), date)
def post(self): ''' Extract picture and file linked to the picture from request, then creates a picture in database for the contact who sends it. An activity is created too. If author is not inside trusted contacts, the request is rejected. ''' file = self.request.files['picture'][0] data = json_decode(self.get_argument("json")) if file and data: contact = ContactManager.getTrustedContact( data.get("authorKey", "")) if contact: date = date_util.get_date_from_db_date(data.get("date", "")) picture = PictureManager.get_contact_picture( contact.key, data.get("date", "")) if not picture: picture = Picture( title = data.get("title", ""), path = data.get("path", ""), contentType = data.get("contentType", ""), authorKey = data.get("authorKey", ""), author = data.get("author", ""), tags = contact.tags, date = date, isMine = False, isFile = False ) picture.save() picture.put_attachment(content=file["body"], name="th_" + file['filename']) picture.save() self.create_creation_activity(contact, picture, "publishes", "picture") logger.info("New picture from %s" % contact.name) self.return_success("Creation succeeds", 201) else: self.return_failure("Author is not trusted.", 400) else: self.return_failure("No data sent.", 405)
def send_creation_to_contacts(self, path, doc): ''' Sends a POST request to all trusted contacts. Request body contains object to post at JSON format. ''' contacts = ContactManager.getTrustedContacts() client = ContactClient(self.activity) for contact in contacts: try: client.post(contact, path, doc.toJson(localized=False)) except HTTPError: self.activity.add_error(contact) self.activity.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 send_files_to_contacts(self, path, fields, files): ''' Sends in a form given file and fields to all trusted contacts (at given path). If any error occurs, it is stored in linked activity. ''' contacts = ContactManager.getTrustedContacts() client = ContactClient(self.activity) for contact in contacts: try: client.post_files(contact, path, fields = fields, files = files) except HTTPError: self.activity.add_error(contact) self.activity.save()
def put(self, slug): ''' Grab tags sent inside request to set is on contact matching slug. ''' contact = ContactManager.getContact(slug) data = self.get_body_as_dict(["tags"]) if contact: if data: contact.tags = data["tags"] contact.save() else: self.return_failure("No tags were sent") else: self.return_failure("Contact to modify does not exist.", 404)
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 post(self): ''' When post request is received, micropost content is expected inside a string under *content* of JSON object. It is extracted from it then stored inside a new Microposts object. Micropost author and date are set from incoming data. ''' data = self.get_body_as_dict(expectedFields=["date", "authorKey"]) if data: db_date = data.get("date") date = date_util.get_date_from_db_date(db_date) authorKey = data.get("authorKey") contact = ContactManager.getTrustedContact(authorKey) micropost = MicroPostManager.get_contact_micropost( authorKey, db_date) if contact: if not micropost: micropost = MicroPost( authorKey = authorKey, author = data["author"], content = data['content'], date = date, attachments = data.get("attachments", []), isMine = False, tags = contact.tags ) micropost.save() self._notify_suscribers(micropost) self.create_creation_activity(contact, micropost, "writes", "micropost") self._write_create_log(micropost) self.return_json(micropost.toJson(), 201) else: self.return_failure("Contact is not registered.", 405) else: self.return_failure("No data sent.", 405)
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 send_deletion_to_contacts(self, path, doc): ''' Send a delete request (PUT because Tornado don't handle DELETE request with a body) to all trusted contacts. Request body contains object to delete at JSON format. ''' contacts = ContactManager.getTrustedContacts() client = ContactClient(self.activity) date = date_util.get_db_date_from_date(doc.date) for contact in contacts: try: client.delete(contact, path, doc.toJson(localized=False), date) except HTTPError: import pdb pdb.set_trace() self.activity.add_error(contact, extra=date) self.activity.save()
def on_picture_found(self, picture, id): ''' ''' self.picture = picture data = dict() data["picture"] = picture.toDict(localized=False) data["contact"] = UserManager.getUser().asContact().toDict() 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): ''' 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.return_document(UserManager.getUser().asContact()) else: self.return_failure("Contact does not exist.")
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) ) logger.info( "Attemp to resend a picture deletion to contact: {}.".format( contact.name)) self.forward_to_contact(picture, contact, activity, method = "PUT") else: self.return_failure("Micropost not found", 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): ''' 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() self.return_success("Request received.") else: self.return_failure("Contact and owner have same url.") else: self.return_failure("Sent data are incorrects.")
def put(self, slug): ''' Confirm contact request. ''' self.contact = ContactManager.getContact(slug) if self.contact: self.contact.state = STATE_TRUSTED self.contact.save() user = UserManager.getUser() data = user.asContact().toJson(localized=False) try: client = ContactClient() client.post(self.contact, "contacts/confirm/", data, self.on_contact_response) except: self.contact.state = STATE_ERROR self.contact.save() self.return_failure("Error occurs while confirming contact.") else: self.return_failure("Contact to confirm does not exist.")
def post(self): ''' When a post request is sent, the newebe downloads full size version of picture specified in the request from the contact also specified in the request. ''' data = self.get_body_as_dict() contact = ContactManager.getTrustedContact(data["contact"]["key"]) if contact: date = data["picture"]["date"] picture = PictureManager.get_owner_last_pictures(date).first() if picture: self.on_picture_found(picture, id) else: logger.info("Picture no more available.") self.return_failure("Picture not found.", 404) else: logger.info("Contact unknown") self.return_failure("Picture not found", 404)
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)