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, 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 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, 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 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 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 forward_to_contact(self, common, contact, activity, method="POST"): ''' *common is sent to *contact* via a request of which method is set as *method*. If request succeeds, error linked to this contact is removed. Else nothing is done and error code is returned. ''' client = ContactClient() body = common.toJson() try: if method == "POST": client.post(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") else: body = common.toJson(localized=False) response = client.put(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") if response.error: message = "Retry common request to a contact failed ({})." self.return_failure(message.format(method)) else: for error in activity.errors: if error["contactKey"] == contact.key: activity.errors.remove(error) activity.save() self.return_success("Common request correctly resent.") except: self.return_failure("Common resend to a contact failed again.")
def forward_to_contact(self, micropost, contact, activity, method="POST"): ''' *micropost* is sent to *contact* via a request of which method is set as *method*. If request succeeds, error linked to this contact is removed. Else nothing is done and error code is returned. ''' httpClient = ContactClient() body = micropost.toJson(localized=False) try: httpClient.post(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") if response.error: self.return_failure("Posting 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 resent.") # TODO: handle case where error is not found. except: self.return_failure("Posting micropost to contact failed.")
def forward_to_contact(self, micropost, contact, activity, method="POST"): ''' *micropost* is sent to *contact* via a request of which method is set as *method*. If request succeeds, error linked to this contact is removed. Else nothing is done and error code is returned. ''' httpClient = ContactClient() body = micropost.toJson(localized=False) try: httpClient.post(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") if response.error: self.return_failure("Posting 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 resent.") # TODO: handle case where error is not found. except: self.return_failure("Posting micropost to contact failed.")
def send_files_to_contact(self, contact, path, fields, files): ''' Sends in a form given file and fields to given contact (at given path). ''' if not hasattr(self, "activity"): self.activity = None client = ContactClient(self.activity) try: client.post_files(contact, path, fields=fields, files=files) except HTTPError: self.activity.add_error(contact) self.activity.save()
def send_files_to_contact(self, contact, path, fields, files): ''' Sends in a form given file and fields to given contact (at given path). ''' if not hasattr(self, "activity"): self.activity = None client = ContactClient(self.activity) try: client.post_files(contact, path, fields=fields, files=files) except HTTPError: self.activity.add_error(contact) self.activity.save()
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_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 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 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_creation_to_contacts(self, path, doc): ''' Sends a POST request to all trusted contacts. Request body contains object to post at JSON format. ''' tag = None if doc.tags: tag = doc.tags[0] contacts = ContactManager.getTrustedContacts(tag=tag) 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_files_to_contacts(self, path, fields, files, tag=None): ''' 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(tag=tag) if not hasattr(self, "activity"): self.activity = None 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 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 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 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 forward_to_contact(self, picture, contact, activity, method="POST"): ''' *picture is sent to *contact* via a request of which method is set as *method*. If request succeeds, error linked to this contact is removed. Else nothing is done and error code is returned. ''' client = ContactClient() try: if method == "POST": client.post_files( contact, CONTACT_PATH, {"json": str(picture.toJson(localized=False))}, [("picture", str(picture.path), picture.fetch_attachment("th_" + picture.path))], callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") else: body = picture.toJson(localized=False) response = client.put(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") if response.error: message = "Retry picture request to a contact failed ({})." self.return_failure(message.format(method)) else: for error in activity.errors: if error["contactKey"] == contact.key: activity.errors.remove(error) activity.save() self.return_success( "Picture request correctly resent.") except: self.return_failure("Picture resend to a contact failed again.")
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 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 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 forward_to_contact(self, picture, contact, activity, method = "POST"): ''' *picture is sent to *contact* via a request of which method is set as *method*. If request succeeds, error linked to this contact is removed. Else nothing is done and error code is returned. ''' client = ContactClient() try: if method == "POST": client.post_files(contact, CONTACT_PATH, { "json": str(picture.toJson(localized=False)) }, [("picture", str(picture.path), picture.fetch_attachment("th_" + picture.path))], callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") else: body = picture.toJson(localized=False) response = client.put(contact, CONTACT_PATH, body, callback=(yield gen.Callback("retry"))) response = yield gen.Wait("retry") if response.error: self.return_failure( "Retry picture request to a contact failed ({}).".format(method)) else: for error in activity.errors: if error["contactKey"] == contact.key: activity.errors.remove(error) activity.save() self.return_success("Picture request correctly resent.") except: self.return_failure("Picture resend to a contact failed again.")
def put(self, slug): ''' Confirm contact request or update tag data. ''' data = self.get_body_as_dict(["tags", "state"]) state = data["state"] tags = data.get("tags", None) self.contact = ContactManager.getContact(slug) if self.contact: if self.contact.state != STATE_TRUSTED and state == STATE_TRUSTED: 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.") elif tags != None: self.contact.tags = tags self.contact.save() self.return_success("Contact tags updated.") else: self.return_success("Nothing to change.") else: self.return_failure("Contact to confirm does not exist.")
def put(self, slug): ''' Confirm contact request or update tag data. ''' data = self.get_body_as_dict(["state"]) state = data["state"] tags = data.get("tags", None) self.contact = ContactManager.getContact(slug) if self.contact: if self.contact.state != STATE_TRUSTED and state == STATE_TRUSTED: 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.") elif tags != None: self.contact.tags = tags self.contact.save() self.return_success("Contact tags updated.") else: self.return_success("Nothing to change.") else: self.return_failure("Contact to confirm does not exist.")
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 on_picture_found(self, picture, id): """ """ self.picture = picture data = dict() data["picture"] = picture.toDict(localized=False) data["contact"] = UserManager.getUser().asContact().toDict() if picture._id in CURRENT_DOWNLOADS: self.return_success("already downloading") else: CURRENT_DOWNLOADS.append(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 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 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.")
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)