Ejemplo n.º 1
0
    def delete(self, id):
        '''
        Deletes given tag.
        '''

        tag = ContactManager.getTag(id)
        name = tag.name
        tag.delete()

        for contact in ContactManager.getTrustedContacts():
            if name in contact.tags:
                contact.tags.remove(name)
                contact.save()

        self.return_success("Tag successfully deleted.", 204)
Ejemplo n.º 2
0
    def delete(self, id):
        '''
        Deletes given tag.
        '''

        tag = ContactManager.getTag(id)
        name = tag.name
        tag.delete()

        for contact in ContactManager.getTrustedContacts():
            if name in contact.tags:
                contact.tags.remove(name)
                contact.save()

        self.return_success("Tag successfully deleted.", 204)
Ejemplo n.º 3
0
    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:
                    info_str = "Attempt to resend a post to contact: %s."
                    logger.info(info_str % contact.name)
                self.forward_to_contact(micropost, contact, activity)
        else:
            self.return_failure("Micropost not found", 404)
Ejemplo n.º 4
0
    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:
                    info_str = "Attempt to resend a post to contact: %s."
                    logger.info(info_str % contact.name)
                self.forward_to_contact(micropost, contact, activity)
        else:
            self.return_failure("Micropost not found", 404)
Ejemplo n.º 5
0
    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.send_picture_to_contact(contact)
                self.return_success("Contact trusted.")

                for websocket_client in websocket_clients:
                    websocket_client.write_message(contact.toJson())

            else:
                self.return_failure("No contact for this slug.", 400)

        else:
            self.return_failure("Sent data are incorrects.", 400)
Ejemplo n.º 6
0
    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.tags = data["tags"]
                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.")
Ejemplo n.º 7
0
    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)
Ejemplo n.º 8
0
    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.")
Ejemplo n.º 9
0
    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")
                postIndexer = indexer.Indexer()
                postIndexer.remove_doc(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)
Ejemplo n.º 10
0
    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"}
        '''
        common = CommonManager.get_common(key)
        idInfos = self.request.body

        ids = json_decode(idInfos)

        if common 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:
                info = "Attemp to resend a common to contact: {}."
                logger.info(info.format(contact.name))
                self.forward_to_contact(common, contact, activity)
        else:
            self.return_failure("Common not found", 404)
Ejemplo n.º 11
0
    def put(self):
        '''
        Delete common of which data are given inside request.
        Common 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:
                common = CommonManager.get_contact_common(
                    contact.key, data.get("date", ""))

                if common:
                    self.create_deletion_activity(contact, common, "deletes",
                                                  "common")
                    common.delete()

                self.return_success("Deletion succeeds")

            else:
                self.return_failure("Author is not trusted.", 400)

        else:
            self.return_failure("No data sent.", 405)
Ejemplo n.º 12
0
    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.")
Ejemplo n.º 13
0
    def get(self):
        '''
        Retrieves whole contact list at JSON format.
        '''
        contacts = ContactManager.getContacts()

        self.return_documents(contacts)
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
    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)
Ejemplo n.º 17
0
    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)
Ejemplo n.º 18
0
    def put(self):
        '''
        When a put request is received, contact thumbnail is expected.
        If contact key is one of the trusted contact key, its data are updated
        with received ones.
        '''

        picfile = self.request.files['small_picture'][0]
        contactKey = self.get_argument("key")
        import pdb; pdb.set_trace()

        if picfile and contactKey:
            contact = ContactManager.getTrustedContact(contactKey)

            if contact:
                contact.save()
                contact.put_attachment(content=picfile["body"],
                                       name="small_picture.jpg")
                contact.save()
                self.return_success("Contact picture successfully modified.")
            else:
                self.return_failure(
                    "No contact found corresponding to given contact", 404)

        else:
            self.return_failure("Empty data or missing field.")
Ejemplo n.º 19
0
    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")
                postIndexer = indexer.Indexer()
                postIndexer.remove_doc(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)
Ejemplo n.º 20
0
    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)
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
    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)
Ejemplo n.º 23
0
    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:
                info = "Attemp to resend a picture to contact: {}."
                logger.info(info.format(contact.name))
                self.forward_to_contact(picture, contact, activity)
        else:
            self.return_failure("Picture not found", 404)
Ejemplo n.º 24
0
    def put(self):
        '''
        When a put request is received, contact thumbnail is expected.
        If contact key is one of the trusted contact key, its data are updated
        with received ones.
        '''

        picfile = self.request.files['small_picture'][0]
        contactKey = self.get_argument("key")

        if picfile and contactKey:
            contact = ContactManager.getTrustedContact(contactKey)

            if contact:
                contact.save()
                contact.put_attachment(content=picfile["body"],
                                       name="small_picture.jpg")
                contact.save()
                self.return_success("Contact picture successfully modified.")
            else:
                self.return_failure(
                    "No contact found corresponding to given contact", 404)

        else:
            self.return_failure("Empty data or missing field.")
Ejemplo n.º 25
0
    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.")
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
0
    def get(self):
        '''
        Returns the list of available tags.
        '''

        tags = ContactManager.getTags()
        tags.insert(0, ContactTag(name="all"))
        self.return_documents(tags)
Ejemplo n.º 28
0
    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.")
Ejemplo n.º 29
0
    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.")
Ejemplo n.º 30
0
    def get(self):
        '''
        Returns the list of available tags.
        '''

        tags = ContactManager.getTags()
        tags.insert(0, ContactTag(name="all"))
        self.return_documents(tags)
Ejemplo n.º 31
0
    def get(self):
        '''
        Retrieve whole contact list at JSON format.
        '''

        contacts = ContactManager.getTrustedContacts()

        self.return_documents(contacts)
Ejemplo n.º 32
0
    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)
Ejemplo n.º 33
0
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)
Ejemplo n.º 34
0
    def post(self):
        '''
        Creates a new tag.
        '''

        data = self.get_body_as_dict(["name"])
        tag = ContactManager.getTagByName(data["name"])
        if tag is None:
            tag = ContactTag(name=data["name"])
            tag.save()
        self.return_one_document(tag, 201)
Ejemplo n.º 35
0
    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.")
Ejemplo n.º 36
0
    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.")
Ejemplo n.º 37
0
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)
Ejemplo n.º 38
0
    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.")
Ejemplo n.º 39
0
    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(
                        _id=data.get("_id", ""),
                        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_" + picture._id)
                    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)
Ejemplo n.º 40
0
    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", []),
                        pictures_to_download=data.get("pictures", []),
                        commons_to_download=data.get("commons", []),
                        isMine=False,
                        tags=contact.tags)
                    micropost.save()

                    self.create_creation_activity(contact, micropost, "writes",
                                                  "micropost")
                    self._write_create_log(micropost)

                    postIndexer = indexer.Indexer()
                    postIndexer.index_micropost(micropost)
                    for websocket_client in websocket_clients:
                        websocket_client.write_message(micropost.toJson())

                self.return_json(micropost.toJson(), 201)

            else:
                self.return_failure("Contact is not registered.", 405)

        else:
            self.return_failure("No data sent.", 405)
Ejemplo n.º 41
0
    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.")
Ejemplo n.º 42
0
    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", []),
                        pictures_to_download=data.get("pictures", []),
                        commons_to_download=data.get("commons", []),
                        isMine=False,
                        tags=contact.tags,
                    )
                    micropost.save()

                    self.create_creation_activity(contact, micropost, "writes", "micropost")
                    self._write_create_log(micropost)

                    postIndexer = indexer.Indexer()
                    postIndexer.index_micropost(micropost)
                    for websocket_client in websocket_clients:
                        websocket_client.write_message(micropost.toJson())

                self.return_json(micropost.toJson(), 201)

            else:
                self.return_failure("Contact is not registered.", 405)

        else:
            self.return_failure("No data sent.", 405)
Ejemplo n.º 43
0
    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(_id=data.get("_id", ""),
                                      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_" + picture._id)
                    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)
Ejemplo n.º 44
0
    def post(self):
        '''
        Extract common and file linked to the common from request, then
        creates a common in database for the contact who sends it. An
        activity is created too.

        If author is not inside trusted contacts, the request is rejected.
        '''

        data = self.get_body_as_dict(
            expectedFields=["title", "path", "contentType", "authorKey",
                             "author", "date"])

        if file and data:
            contact = ContactManager.getTrustedContact(
                    data.get("authorKey", ""))

            if contact:
                date = date_util.get_date_from_db_date(data.get("date", ""))

                common = CommonManager.get_contact_common(
                            contact.key, data.get("date", ""))

                if not common:
                    common = Common(
                        _id=data.get("_id", ""),
                        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
                    )
                    common.save()

                    self.create_creation_activity(contact,
                            common, "publishes", "common")

                logger.info("New common 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)
Ejemplo n.º 45
0
    def put(self, slug):
        '''
        Grab tags sent inside request to set is on given contact.
        '''

        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)
Ejemplo n.º 46
0
    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)
        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()
Ejemplo n.º 47
0
    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)
Ejemplo n.º 48
0
    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)
Ejemplo n.º 49
0
    def post(self):
        '''
        Extract common and file linked to the common from request, then
        creates a common in database for the contact who sends it. An
        activity is created too.

        If author is not inside trusted contacts, the request is rejected.
        '''

        data = self.get_body_as_dict(expectedFields=[
            "title", "path", "contentType", "authorKey", "author", "date"
        ])

        if file and data:
            contact = ContactManager.getTrustedContact(
                data.get("authorKey", ""))

            if contact:
                date = date_util.get_date_from_db_date(data.get("date", ""))

                common = CommonManager.get_contact_common(
                    contact.key, data.get("date", ""))

                if not common:
                    common = Common(_id=data.get("_id", ""),
                                    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)
                    common.save()

                    self.create_creation_activity(contact, common, "publishes",
                                                  "common")

                logger.info("New common 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)
Ejemplo n.º 50
0
    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()
Ejemplo n.º 51
0
    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()
Ejemplo n.º 52
0
    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()
Ejemplo n.º 53
0
    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.")
Ejemplo n.º 54
0
    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.")
Ejemplo n.º 55
0
    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.")
Ejemplo n.º 56
0
    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()
Ejemplo n.º 57
0
    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.")
Ejemplo n.º 58
0
    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)