Exemplo n.º 1
0
    def post(self):
        '''
        Creates a picture and corresponding activity. Then picture is 
        propagated to all trusted contacts.

        Errors are stored inside activity.
        '''

        filebody = self.request.body
        filename = self.get_argument("qqfile")
        try:
            tag = self.get_argument("tag")
        except:
            tag = "all"
        filetype = mimetypes.guess_type(filename)[0] or \
                'application/octet-stream'

        if filebody:

            picture = Picture(
                title = "New Picture", 
                path=filename,
                contentType=filetype, 
                authorKey = UserManager.getUser().key,
                author = UserManager.getUser().name,
                isMine = True,
                isFile = True,
                tags = [tag]
            )
            picture.save()

            picture.put_attachment(content=filebody, name=filename)            
            thumbnail = self.get_thumbnail(filebody, filename, (200, 200))
            thbuffer = thumbnail.read()        
            picture.put_attachment(thbuffer, "th_" + filename)
            os.remove("th_" + filename)           
            preview = self.get_thumbnail(filebody, filename, (1000, 1000))
            picture.put_attachment(preview.read(), "prev_" + filename)
            os.remove("th_" + filename)
            picture.save()

            self.create_owner_creation_activity(
                    picture, "publishes", "picture")

            self.send_files_to_contacts("pictures/contact/", 
                        fields = 
                          { "json": str(picture.toJson(localized=False)) },
                        files = [("picture", str(picture.path), thbuffer)],
                        tag=tag)
            
            logger.info("Picture %s successfuly posted." % filename)
            self.return_json(picture.toJson(), 201)

        else:
            self.return_failure("No picture posted.", 400)
Exemplo n.º 2
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)
Exemplo n.º 3
0
    def get_current_user(self):
        '''
        With tornado, authentication is handled in this method.
        '''

        user = UserManager.getUser()

        if user:

            if user.password is None:
                logger.error("User has no password registered")
                self.redirect("/register/password/")

            else:
                password = self.get_secure_cookie("password")

                if not password or  \
                   user.password != hashlib.sha224(password).hexdigest():
                    logger.error("User is not authenticated")
                    self.redirect("/login/")

                else:
                    return user

        else:
            logger.error("User is not authenticated")
            self.redirect("/register/")
Exemplo n.º 4
0
    def post(self):
        '''
        Sets given password as user password (after sha-224 encryption).
        '''

        user = UserManager.getUser()

        if user is None:
            self.return_failure("User does not exist.")

        elif user.password is not None:
            self.return_failure("Password is already set.")

        else:
            data = self.get_body_as_dict(expectedFields=["password"])

            if data:
                postedPassword = data["password"]

                if postedPassword and len(postedPassword) > 3:
                    password = \
                        hashlib.sha224(postedPassword).hexdigest()
                    user.password = password
                    user.save()
                    self.set_secure_cookie("password", postedPassword)
    
                    self.return_json(user.toJson())

                else:
                    self.return_failure(
                        "Password is too short. User password is not set.", 400)

            else:
                self.return_failure(
                        "Data are not correct. User password is not set.", 400)
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    def post(self):
        '''
        Creates a picture and corresponding activity. Then picture is 
        propagated to all trusted contacts.

        Errors are stored inside activity.
        '''

        file = self.request.files['picture'][0]

        if file:
            filebody = file["body"]
            filename = file['filename']

            picture = Picture(
                title = "New Picture", 
                path = filename,
                contentType =file["content_type"], 
                authorKey = UserManager.getUser().key,
                author = UserManager.getUser().name,
                isFile = True
            )
            picture.save()

            picture.put_attachment(filebody, filename)
            thumbnail = self.get_thumbnail(filebody, filename, (200, 200))     
            thbuffer = thumbnail.read()
            picture.put_attachment(thbuffer, "th_" + filename)
            os.remove("th_" + filename) 
            preview = self.get_thumbnail(filebody, filename, (1000, 1000))
            picture.put_attachment(preview.read(), "prev_" + filename)
            os.remove("th_" + filename)           
            picture.save()
        
            self.create_owner_creation_activity(
                    picture, "publishes", "picture")

            self.send_files_to_contacts("pictures/contact/", 
                        fields = 
                           { "json": str(picture.toJson(localized=False)) },
                        files = [("picture", str(picture.path), thbuffer)])
                        
            logger.info("Picture %s successfuly posted." % filename)
            self.return_json(picture.toJson(), 201)

        else:
            self.return_failure("No picture posted.", 400)
Exemplo n.º 7
0
    def get(self):
        '''
        Retrieves current user (newebe owner) data at JSON format.
        '''

        user = UserManager.getUser()

        self.return_document(user)
Exemplo n.º 8
0
    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)
Exemplo n.º 9
0
    def get(self):
        '''
        If no user exist, it redirects to register root page, else
        it returns register page.
        '''

        if UserManager.getUser():
           self.redirect("/") 
        else:
            self.render("../auth/templates/register.html",
                        isTheme=self.is_file_theme_exists())
Exemplo n.º 10
0
    def create_owner_deletion_activity(self, doc, verb, docType):
        '''
        Creates a new activity corresponding to a document deletion made 
        by owner.

        * doc: The deleted document.
        * verb: verb linked to this activity.
        * docType: Type of the deleted document.
        '''

        self.create_deletion_activity(
            UserManager.getUser().asContact(), doc, verb, docType, True)
Exemplo n.º 11
0
    def save(self):
        '''
        When document is saved, the last modified field is updated to 
        make sure it is always correct. 
        '''

        if not self.authorKey:
            user = UserManager.getUser()
            self.authorKey = user.key
            self.author = user.name

        self.lastModified = datetime.datetime.utcnow()
        NewebeDocument.save(self)
Exemplo n.º 12
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()

                self.return_success("Request received.")

            else:
                self.return_failure("Contact and owner have same url.")

        else:
            self.return_failure("Sent data are incorrects.")
Exemplo n.º 13
0
def given_there_are_3_posts_of_and_3_posts_of_my_contacts(step, 
                                                          nbposts, 
                                                          nbcontactposts):
    nbposts = int(nbposts)
    nbcontactposts = int(nbcontactposts)

    for i in range(1, nbposts + 1):
        micropost = MicroPost()
        micropost.author = UserManager.getUser().name
        micropost.authorKey = UserManager.getUser().key
        micropost.content = "my content {}".format(i)
        micropost.date = datetime.datetime(2011, i, 01, 11, 05, 12)
        micropost.isMine = True
        micropost.save()

    for i in range(1, nbcontactposts + 1):
        micropost = MicroPost()
        micropost.author = world.user2.name
        micropost.authorKey = world.user2.key        
        micropost.content = "contact content {}".format(i)
        micropost.date = datetime.datetime(2011, i, 10, 11, 05, 12)
        micropost.isMine = False
        micropost.save()
Exemplo n.º 14
0
    def get(self):
        '''
        If user does not have password it returns password registration page.
        '''

        user = UserManager.getUser()
        if user and user.password:
            self.redirect("/") 
        else:
            self.render("../auth/templates/password.html",
                        isTheme=self.is_file_theme_exists())

        self.render("../auth/templates/password.html",
                    isTheme=self.is_file_theme_exists())
Exemplo n.º 15
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.")
Exemplo n.º 16
0
    def post(self):
        '''
        Get password via a form. Set a secure cookie if password is OK 
        then redirects to root page.
        Else it redirects to login page.
        '''

        password = self.get_argument("password")
        user = UserManager.getUser()

        if user and user.password == hashlib.sha224(password).hexdigest():  
            self.set_secure_cookie("password", password)
            self.redirect("/")

        else:
            self.redirect("/login/")
Exemplo n.º 17
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)
Exemplo n.º 18
0
    def delete(self, id):
        '''
        Deletes picture corresponding to id.
        '''

        picture = PictureManager.get_picture(id)
        if picture:
            user = UserManager.getUser()
            
            if picture.authorKey == user.key:
                self.create_owner_deletion_activity(
                        picture, "deletes", "picture")
                self.send_deletion_to_contacts("pictures/contact/", picture)
          
            picture.delete()
            self.return_success("Picture deleted.")
        else:
            self.return_failure("Picture not found.", 404)
Exemplo n.º 19
0
    def set_default_user(self, url=ROOT_URL):
        """
        Set to DB default user. This is useful for automatic login.
        """

        self.root_url = url

        self.user = UserManager.getUser()
        if self.user:
            self.user.delete()

        self.user = User(
            name="John Doe",
            password=hashlib.sha224("password").hexdigest(),
            key="key",
            authorKey="authorKey",
            url=url,
            description="my description",
        )
        self.user.save()
Exemplo n.º 20
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.return_document(UserManager.getUser().asContact())
        else:
            self.return_failure("Contact does not exist.")
Exemplo n.º 21
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.")
Exemplo n.º 22
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)
                )
                
                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)
Exemplo n.º 23
0
    def post(self):
        '''
        Get password via a json object.  Sets a secure cookie if password 
        is OK. Else it returns an error response.
        '''
        data = self.get_body_as_dict(expectedFields=["password"])

        if data:
            password = data["password"]
            user = UserManager.getUser()
    
            if user \
               and user.password == hashlib.sha224(password).hexdigest():
                self.set_secure_cookie("password", password)
                self.return_success("You are now logged in.")

            else:
                self.return_failure("Wrong password.", 400)
            
        else:
            self.return_failure("Wrong password.", 400)
Exemplo n.º 24
0
    def get(self):
        '''
        Displaying page for logging in.
        '''

        user = UserManager.getUser()

        if user and user.password:
            password = self.get_secure_cookie("password")

            if not password or  \
               user.password != hashlib.sha224(password).hexdigest():
                self.render("../auth/templates/login.html",
                            isTheme=self.is_file_theme_exists())
            else:
                self.redirect("/")

        elif user and not user.password:
            self.redirect("/register/password/")

        elif not user:
            self.redirect("/register/")
Exemplo n.º 25
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)
Exemplo n.º 26
0
    def set_default_user_2(self, url=ROOT_URL):
        '''
        Set to DB default user. This is useful for automatic login.
        '''
        
        self.root_url = url
        User._db = db2

        self.user = UserManager.getUser()
        if self.user:
            self.user.delete()

        self.user = User(
            name = "Dan Frazer",
            password = hashlib.sha224("password").hexdigest(),
            key = "key2",
            authorKey = "authorKey2",
            url = url,
            description = "my description"
        )
        self.user.save()
        User._db = db
Exemplo n.º 27
0
    def put(self):
        '''
        Modifies current user data with sent data (user object at JSON format).
        Then forwards it to contacts after a pre-defined time.
        '''

        user = UserManager.getUser()
    
        data = self.get_body_as_dict(
                expectedFields=["name", "url", "description"])

        if data:
            user.name = data["name"]
            user.url = data["url"]
            user.description = data["description"]
            user.save()

            profile_updater.forward_profile()

            self.return_success("User successfully Modified.")
        else:
            self.return_failure("Wrong data were sent.")
Exemplo n.º 28
0
    def post(self):
        '''
        Creates a new note from received data.
        '''

        logger.info("Note creation received.")

        data = self.get_body_as_dict(expectedFields=["title", "content"])

        if data:
            note = Note(
                author = UserManager.getUser().name,
                title = data["title"],
                content = data["content"],
                isMine = True,
            )

            note.save()
            self.create_owner_creation_activity(note, "writes", "note")

            self.return_one_document(note, 201)
        else:
            self.return_failure("No data sent", 400)
Exemplo n.º 29
0
    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.")
Exemplo n.º 30
0
    def delete(self, id):
        '''
        Deletes the post of which id is equal to postId, add an activity and 
        forwards the delete request to each trusted contact.

        put instead of delete because tornado does not support body in DELETE 
        requests...
        '''

        micropost = MicroPostManager.get_micropost(id)

        if micropost:            
            user = UserManager.getUser()

            if micropost.authorKey == user.key:
                self.create_owner_deletion_activity(
                    micropost, "deletes", "micropost")  
                self.send_deletion_to_contacts(CONTACT_PATH, micropost)
            micropost.delete()
            self.return_success("Micropost deletion succeeds.")
            
        else:
            self.return_failure("Micropost not found.", 404)