예제 #1
0
파일: clubapis.py 프로젝트: RJJ11/SAMPLE
   def getPosts(self, request):
        print("Entered Get Posts Portion")
        temp = request.collegeId
        temp2 = request.clubId
        print "temp" + str(temp)
        print "temp2" + str(temp2)
        if(temp2==None):
            print "None"
            collegeId = ndb.Key('CollegeDb',int(temp))
            posts = Post.query(Post.collegeId==collegeId).order(-Post.timestamp)
        elif(temp==None):
            print "None"
            clubId = ndb.Key('Club',int(temp2))
            posts = Post.query(Post.club_id==clubId).order(-Post.timestamp)

        else:
            print "Not None"
            collegeId = ndb.Key('CollegeDb',int(temp))
            clubId = ndb.Key('Club',int(temp2))
            posts = Post.query(Post.collegeId==collegeId,Post.club_id==clubId).order(-Post.timestamp)

        #pylist =[copyPostToForm(x) for x in posts]
        #print "the list"
        #print pylist

        return Posts(items=list(reversed([copyPostToForm(x) for x in posts])))
    def load(request: Request):
        user = request.user
        post_id = int(request.inputs['ext'][0])

        post = Post.query().select().where('id', post_id).getOne()

        post_like: Post_like = Post_like.query().select().where(
            'post_id', post_id).where('user_id', user.id).getOne()

        liked = False
        if post_like is not None:
            liked = True

        if post is None:
            posts = Post.query().select().where('user_id', user.id).get()
            view = View(
                'post.view', {
                    'user': user,
                    'posts': posts,
                    'error': 'Incorrect index position. Please try again.'
                }, request.json)
        else:
            view = View('post.load', {
                'user': user,
                'post': post,
                'whether_post_liked_by_user': liked
            }, request.json)
        return Response(ResponseType.valid, view)
예제 #3
0
 def mutate(self, info, title, body, username):
     user = User.query.filter_by(username=username).first()
     post = Post(title=title, body=body)
     if user is not None:
         post.author = user
     db.session.add(post)
     db.session.commit()
     return CreatePost(post=post)
    def show(request: Request):
        user = request.user

        posts = Post.query().select().where('user_id', user.id).get()

        view = View('post.view', {'user': user, 'posts': posts}, request.json)
        return Response(ResponseType.valid, view)
예제 #5
0
    def add(request: Request):
        user = request.user
        post_id = int(request.inputs['ext'][0])
        content = request.inputs['content']

        Comment.query().insert(
            [post_id, user.id, content,
             datetime.today(),
             datetime.today()])

        post = Post.query().select().where('id', post_id).getOne()

        post_like: Post_like = Post_like.query().select().where(
            'post_id', post_id).where('user_id', user.id).getOne()

        liked = False
        if post_like is not None:
            liked = True

        view = View('post.load', {
            'user': user,
            'post': post,
            'whether_post_liked_by_user': liked
        }, request.json)
        return Response(ResponseType.valid, view)
    def add(request: Request):
        user: User = request.user
        title = request.inputs['title']
        content = request.inputs['content']
        allow_comments = 0 if request.inputs['allow_comments'] == 'n' else 1
        visibility = 0 if request.inputs['visibility'] == '0' else 1
        tags = request.inputs['tags']

        Post.query().insert([
            user.id, title, content, allow_comments, visibility, tags,
            datetime.today(),
            datetime.today()
        ])

        view = View('home', {'user': user}, request.json)
        return Response(ResponseType.valid, view)
예제 #7
0
def test_post_4():
    post1 = Post.Post("74127630069740107909", "75641188490278536508",
                      "Test Post 4", "This is a description for test post 4.",
                      "These are notes for test post 4.", 0, 0,
                      "Wilmington, NC", "", "The moon")
    assert post1.id == "74127630069740107909"
    assert post1.userid == "75641188490278536508"
    assert post1.title == "Test Post 4"
    assert post1.description == "This is a description for test post 4."
    assert post1.notes == "These are notes for test post 4."
    assert post1.rating == 0
    assert post1.numRatings == 0
    assert post1.start == "Wilmington, NC"
    assert post1.waypoints == ""
    assert post1.end == "The moon"
    assert post1.getDatabaseModel() == {
        'id': "74127630069740107909",
        'userid': "75641188490278536508",
        'title': "Test Post 4",
        'description': "This is a description for test post 4.",
        'notes': "These are notes for test post 4.",
        'rating': 0,
        'numRatings': 0,
        'start': "Wilmington, NC",
        'waypoints': "",
        'end': "The moon"
    }
예제 #8
0
def test_post_3():
    post1 = Post.Post(
        "09082850095949731619", "03256889542760712902", "Test Post 3",
        "This is a description for test post 3.",
        "These are notes for test post 3.", 5, 1, "Cleveland, OH",
        "[{\"location\": \"Toledo, OH\", \"stopover\": true}, {\"location\": \"Dayton, OH\", \"stopover\": true}, {\"location\": \"Columbus, OH\", \"stopover\": true}]",
        "Orrville, OH")
    assert post1.id == "09082850095949731619"
    assert post1.userid == "03256889542760712902"
    assert post1.title == "Test Post 3"
    assert post1.description == "This is a description for test post 3."
    assert post1.notes == "These are notes for test post 3."
    assert post1.rating == 5
    assert post1.numRatings == 1
    assert post1.start == "Cleveland, OH"
    assert post1.waypoints == "[{\"location\": \"Toledo, OH\", \"stopover\": true}, {\"location\": \"Dayton, OH\", \"stopover\": true}, {\"location\": \"Columbus, OH\", \"stopover\": true}]"
    assert post1.end == "Orrville, OH"
    assert post1.getDatabaseModel() == {
        'id': "09082850095949731619",
        'userid': "03256889542760712902",
        'title': "Test Post 3",
        'description': "This is a description for test post 3.",
        'notes': "These are notes for test post 3.",
        'rating': 5,
        'numRatings': 1,
        'start': "Cleveland, OH",
        'waypoints':
        "[{\"location\": \"Toledo, OH\", \"stopover\": true}, {\"location\": \"Dayton, OH\", \"stopover\": true}, {\"location\": \"Columbus, OH\", \"stopover\": true}]",
        'end': "Orrville, OH"
    }
예제 #9
0
def test_post_1():
    post1 = Post.Post("96822060868999399931", "50583170224718302358",
                      "Test Post 1", "This is a description for test post 1.",
                      "These are notes for test post 1.", 3, 12, "Kent, OH",
                      "[{\"location\": \"Toledo, OH\", \"stopover\": true}]",
                      "Columbus, OH")
    assert post1.id == "96822060868999399931"
    assert post1.userid == "50583170224718302358"
    assert post1.title == "Test Post 1"
    assert post1.description == "This is a description for test post 1."
    assert post1.notes == "These are notes for test post 1."
    assert post1.rating == 3
    assert post1.numRatings == 12
    assert post1.start == "Kent, OH"
    assert post1.waypoints == "[{\"location\": \"Toledo, OH\", \"stopover\": true}]"
    assert post1.end == "Columbus, OH"
    assert post1.getDatabaseModel() == {
        'id': "96822060868999399931",
        'userid': "50583170224718302358",
        'title': "Test Post 1",
        'description': "This is a description for test post 1.",
        'notes': "These are notes for test post 1.",
        'rating': 3,
        'numRatings': 12,
        'start': "Kent, OH",
        'waypoints': "[{\"location\": \"Toledo, OH\", \"stopover\": true}]",
        'end': "Columbus, OH"
    }
예제 #10
0
def test_post_2():
    post1 = Post.Post("44165755922574917641", "02423638768591586899",
                      "Test Post 2", "This is a description for test post 2.",
                      "These are notes for test post 2.", 4, 6, "Akron, OH",
                      "[{\"location\": \"Canton, OH\", \"stopover\": true}]",
                      "Wooster, OH")
    assert post1.id == "44165755922574917641"
    assert post1.userid == "02423638768591586899"
    assert post1.title == "Test Post 2"
    assert post1.description == "This is a description for test post 2."
    assert post1.notes == "These are notes for test post 2."
    assert post1.rating == 4
    assert post1.numRatings == 6
    assert post1.start == "Akron, OH"
    assert post1.waypoints == "[{\"location\": \"Canton, OH\", \"stopover\": true}]"
    assert post1.end == "Wooster, OH"
    assert post1.getDatabaseModel() == {
        'id': "44165755922574917641",
        'userid': "02423638768591586899",
        'title': "Test Post 2",
        'description': "This is a description for test post 2.",
        'notes': "These are notes for test post 2.",
        'rating': 4,
        'numRatings': 6,
        'start': "Akron, OH",
        'waypoints': "[{\"location\": \"Canton, OH\", \"stopover\": true}]",
        'end': "Wooster, OH"
    }
예제 #11
0
def test_post_5():
    post1 = Post.Post(
        "81937702717455924447", "29784136616602750877", "Test Post 5",
        "This is a description for test post 5.",
        "These are notes for test post 5.", 7, 3000000, "Athens, OH",
        "[{\"location\": \"Los Angeles, CA\", \"stopover\": true}]",
        "Athens, OH")
    assert post1.id == "81937702717455924447"
    assert post1.userid == "29784136616602750877"
    assert post1.title == "Test Post 5"
    assert post1.description == "This is a description for test post 5."
    assert post1.notes == "These are notes for test post 5."
    assert post1.rating == 7
    assert post1.numRatings == 3000000
    assert post1.start == "Athens, OH"
    assert post1.waypoints == "[{\"location\": \"Los Angeles, CA\", \"stopover\": true}]"
    assert post1.end == "Athens, OH"
    assert post1.getDatabaseModel() == {
        'id': "81937702717455924447",
        'userid': "29784136616602750877",
        'title': "Test Post 5",
        'description': "This is a description for test post 5.",
        'notes': "These are notes for test post 5.",
        'rating': 7,
        'numRatings': 3000000,
        'start': "Athens, OH",
        'waypoints':
        "[{\"location\": \"Los Angeles, CA\", \"stopover\": true}]",
        'end': "Athens, OH"
    }
예제 #12
0
 def post(self):
     new_post = Post(title=request.json['title'],
                     content=request.json['content'])
     db.session.add(new_post)
     db.session.commit()
     result = post_schema.dump(new_post)
     return {"status": 'success', 'data': result}, 201
예제 #13
0
    def add_form(request: Request):
        user = request.user
        post_id = int(request.inputs['ext'][0])

        post = Post.query().select().where('id', post_id).getOne()

        view = View('comment.add', {'user': user, 'post': post}, request.json)
        return Response(ResponseType.valid, view)
    def show_all(request: Request):
        user: User = request.user
        posts = Post.query().select().where('public_visibility',
                                            1).sortBy('created_at',
                                                      False).get()

        view = View('post.view', {'user': user, 'posts': posts}, request.json)
        return Response(ResponseType.valid, view)
예제 #15
0
   def getPosts(self, request):
        print("Entered Get Posts Portion")
        temp = request.collegeId
        temp2 = request.clubId
        print "temp2" + str(temp2)
        if(temp2==None):
            print "None"
            collegeId = ndb.Key('CollegeDb',int(temp))
            posts = Post.query(Post.collegeId==collegeId)
        elif(temp==None):
            print "None"
            clubId = ndb.Key('Club',int(temp2))
            posts = Post.query(Post.club_id==clubId)

        else:
            print "Not None"
            collegeId = ndb.Key('CollegeDb',int(temp))
            clubId = ndb.Key('Club',int(temp2))
            posts = Post.query(Post.collegeId==collegeId,Post.club_id==clubId)

        return Posts(items=[copyPostToForm(x) for x in posts])
예제 #16
0
 def test_Helper_fill_object_from_data(self):
     post = Post()
     data = {
         'title': 'title-test',
         'name': 'name-test'
     }
     Helper().fill_object_from_data(post, data, ['title', 'name'])
     payload_1 = 'title-test'
     payload_2 = 'name-test'
     response_1 = post.title
     response_2 = post.name
     self.assertEqual(payload_1, response_1, 'Helper().fill_object_from_data does not return \'title-test\'.')
     self.assertEqual(payload_2, response_2, 'Helper().fill_object_from_data does not return \'name-test\'.')
예제 #17
0
    def view(request: Request):
        user = request.user
        post_id = int(request.inputs['ext'][0])

        post = Post.query().select().where('id', post_id).getOne()
        comments: List[Comment] = Comment.query().select().where(
            'post_id', post_id).sortBy('created_at', False).get()

        view = View('comment.load', {
            'user': user,
            'post': post,
            'comments': comments
        }, request.json)
        return Response(ResponseType.valid, view)
예제 #18
0
 def get(self, post_id):
     if self.user_logged_in(self.user):
         post = self.post_exists(post_id)
         if post:
             if self.users_own_post(self.user, post):
                 post.delete()
                 posts = greetings = Post.all().order('-created')
                 self.redirect('/blog/')
             else:
                 postComm = Comment.all().filter('post_id =', post_id)
                 self.render(
                     "permalink.html",
                     post=post,
                     error="You don't have access to delete this record.",
                     comments=postComm)
    def home(request: Request):
        loggedUserId: int = request.json['user_id']
        user: User = User.query().select().where('id', loggedUserId).getOne()

        notifications: List[Notification] = Notification.query().select(
        ).where('is_read', 0).get()
        posts = Post.query().select().where('user_id', user.id).get()

        view = View(
            'home', {
                'user': user,
                'notification_count': len(notifications),
                'my_post_count': len(posts)
            }, request.json)

        return Response(ResponseType.valid, view)
예제 #20
0
파일: clubapis.py 프로젝트: RJJ11/SAMPLE
 def dontTouch(self, request):
     pid = ndb.Key('Profile',int(request.pid))
     clubId = Club.query(Club.admin==pid)
     pylist=[]
     for x in clubId:
         print x.key
         posts = Post.query(Post.club_id==x.key).order(-Post.timestamp)
         events = Event.query(Event.club_id==x.key).order(-Post.timestamp)
         list1=[]
         list2=[]
         list1 = [copyToCollegeFeed(y) for y in events]
         list2 = [copyToCollegeFeed(z) for z in posts]
         list1+=list2
         print "List-1",list1
         pylist+=list1
     pylist.sort(key=lambda x: x.timestamp, reverse=True)
     return CollegeFeed(items=pylist)
예제 #21
0
 def process(session, data):
     post = Post()
     Helper().fill_object_from_data(post, data, ['name', 'title', 'description', 'status', 'is_protected', 'has_comments'])
     post.publish_on = Helper().get_null_if_empty(data['publish_on'])
     post.expire_on = Helper().get_null_if_empty(data['expire_on'])
     post.created = Helper().get_current_datetime()
     post.edited = Helper().get_current_datetime()
     self.add_foreign_keys(post, data, session, [('parent_id', Post), ('post_type_id', PostType), ('language_id', Language), ('user_id', User)])
     self.raise_if_has_term_and_not_is_post_page(data, session)
     self.add_many_to_many_relationship('terms', post, data, Term, session)
     session.add(post)
     session.commit()
     return self.handle_success(None, None, 'create', 'Post', post.id)
예제 #22
0
def get_post(postid):
    conn = mysql.connect()
    cursor = conn.cursor()
    sql_string = "select postid, authorid, pageid, postdate, content from Posts where postid=%s"
    cursor.execute(sql_string, (postid))
    data = cursor.fetchone()
    if not data:
        return None
    # create Post object
    authorname = userid_to_object(data[1]).username
    post = Post(data[0], data[1], data[2], data[3], data[4], authorname)
    post.set_likes(get_post_likes(post.postid))
    post.set_comments(get_comments(post.postid))

    return post
예제 #23
0
   def getEvents(self, request):
        print("Entered Get Events Portion")
        temp = request.collegeId
        temp2 = request.clubId
        print "temp2" + str(temp2)
        if(temp2==None):
            print "No CLubId"
            collegeId = ndb.Key('CollegeDb',int(temp))
            events = Event.query(Event.collegeId==collegeId)
        elif(temp==None):
            print "No collegeID"
            clubId = ndb.Key('Club',int(temp2))
            events = Event.query(Event.clubId==clubId)

        else:
            print "Not None"
            collegeId = ndb.Key('CollegeDb',int(temp))
            clubId = ndb.Key('Club',int(temp2))
            events = Post.query(Event.collegeId==collegeId,Event.clubId==clubId)


        return Events(items=[copyEventToForm(x) for x in events])
    def login(request: Request):
        username = request.json['inputs']['name']
        password: str = request.json['inputs']['password']

        passHash = hashlib.sha256(password.encode())
        passHash = passHash.hexdigest()

        users: List[User] = User.query().select().where(
            'name', username).where('passwordHash', passHash).get()
        if not users:
            view = View('',
                        {'error': 'Invalid credentials. Please try again...'},
                        request.json)
            return Response(ResponseType.error, view)

        user = users[0]
        token = user.hash()

        User_auth.query().insert(
            [user.id, token,
             datetime.today(),
             datetime.today()])

        notifications: List[Notification] = Notification.query().select(
        ).where('is_read', 0).get()
        posts = Post.query().select().where('user_id', user.id).get()

        view = View(
            'home', {
                'user': user,
                'notification_count': len(notifications),
                'my_post_count': len(posts)
            }, {
                'user_id': user.id,
                'authToken': token
            })

        return Response(ResponseType.valid, view)
    def edit_password(request: Request):
        loggedUserId: int = request.json['user_id']
        old_password = request.json['inputs']['old_password']
        password = request.json['inputs']['password']
        re_password = request.json['inputs']['re_password']

        user: User = User.query().select().where('id', loggedUserId).getOne()

        if password != re_password:
            view = View('user.edit', {'error': 'passwords do not match'},
                        request.json)
            return Response(ResponseType.valid, view)

        passHash = hashlib.sha256(old_password.encode())
        passHash = passHash.hexdigest()

        if user.passwordHash != passHash:
            view = View('user.edit', {'error': 'old password is wrong'},
                        request.json)
            return Response(ResponseType.valid, view)

        passHash = hashlib.sha256(password.encode())
        passHash = passHash.hexdigest()

        user.passwordHash = passHash
        user.save()

        notifications: List[Notification] = Notification.query().select(
        ).where('is_read', 0).get()
        posts = Post.query().select().where('user_id', user.id).get()

        view = View(
            'home', {
                'user': user,
                'notification_count': len(notifications),
                'my_post_count': len(posts)
            }, request.json)
        return Response(ResponseType.valid, view)
    def like(request: Request):
        user = request.user
        post_id = int(request.inputs['ext'][0])

        post_like: Post_like = Post_like.query().select().where(
            'post_id', post_id).where('user_id', user.id).getOne()
        liked = False

        if post_like is None:
            liked = True
            Post_like.query().insert(
                [user.id, post_id,
                 datetime.today(),
                 datetime.today()])
        else:
            post_like.delete()

        post = Post.query().select().where('id', post_id).getOne()
        view = View('post.load', {
            'user': user,
            'post': post,
            'whether_post_liked_by_user': liked
        }, request.json)
        return Response(ResponseType.valid, view)
예제 #27
0
    def post(self):
        if not self.user:
            return self.redirect('/blog')

        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            p = Post(parent=blog_key(), subject=subject, content=content)
            p.user_id = str(self.user.key().id())
            p.put()
            postComm = Comment.all().filter('post_id =', p.key().id())
            self.render("permalink.html", post=p, comments=postComm)
        else:
            error = "subject and content, please!"
            self.render("newpost.html",
                        subject=subject,
                        content=content,
                        error=error)
예제 #28
0
def get_posts(pageid):
    conn = mysql.connect()
    cursor = conn.cursor()
    # get posts on pageid from most recent to least recent
    sql_string = "select postid, authorid, pageid, postdate, content from Posts where pageid=%s order by postdate desc"
    cursor.execute(sql_string, (pageid))
    data = cursor.fetchall()

    posts = []  # list to store post objects
    for d in data:
        #get username of post writer from id
        authorname = userid_to_object(d[1]).username

        post = Post(d[0], d[1], d[2], d[3], d[4], authorname)

        # get users who liked post
        post.set_likes(get_post_likes(post.postid))

        # get comments on post
        post.set_comments(get_comments(post.postid))

        posts.append(post)

    return posts
예제 #29
0
def postEntry(requestentity=None,check=0):

        newPost = Post()
        #college = CollegeDb(name = 'NITK',student_sup='Anirudh',collegeId='NITK-123')
        #college_key = college.put()
        query = CollegeDb.query()
        club_name = Club.query()
        if check==0:
            print "The request entity key is " + requestentity.club_id
            key1 = ndb.Key('Club',int(requestentity.club_id))
            key2 = ndb.Key('Profile',int(requestentity.from_pid))
        else:
            key1 = requestentity.club_id
            key2 = requestentity.from_pid

        persons = Profile.query()
        #print club_name[0]
        #print "The key is " + club_name[0].key
        club_key = key1
        profile_key = key2
        flag = 0
        print "Profile Key " + str(profile_key)
        for x in persons:
            print x.key
            if(x.key == profile_key):
                print "Same"
                flag=1
            else:
                print "NOPE"
                    #setattr(clubRequest, field, profile_key)

        if(flag==1):
            if requestentity:
                for field in ('title','description','club_id','from_pid','likes','views'):

                    if hasattr(requestentity, field):
                        print(field,"is there")
                        val = getattr(requestentity, field)
                        if(field=="club_id"):
                            print "Club_Id stage"
                            setattr(newPost, field, club_key)

                        elif field == "from_pid":
                            print "Entered here"
                            person = profile_key.get()
                            print "Person's email-id ", person.email
                            person_collegeId = person.collegeId
                            print "His college Id ", person.collegeId
                            college_details = person_collegeId.get()
                            print "The sup is ", college_details.student_sup
                            setattr(newPost, field, profile_key)
                            print "Put PID"
                            setattr(newPost,'collegeId',person_collegeId)
                            print "Put college id"

                        elif val:
                            print("Value is",val)
                            setattr(newPost, field, str(val))


                    else:
                        setattr(newPost, "likes", 0)
                        setattr(newPost, "views", 0)

            print("About to create Post")
            print(newPost)
            newPost.put()


        else:
             print "Invalid Person"



        return
예제 #30
0
파일: ClubAPI.py 프로젝트: RJJ11/SAMPLE
def deleteClub(request):
    #Steps to be incorporated for deletion of a club
    #1) Remove the club key from the clubsJoined list of every profile
    #2) Remove the club key from the follows list of every profile
    #3) Remove the club key from the admin list of everyprofile
    #4) Remove from college group list
    #5) Remove notifications that have the club id = given club id
    #6)Remove Join Creations and Join Requests
    #Call deleteEvent and deletePost for all events and posts that belong to the club
    #Delete the club entity

    club_key_id = request.club_id
    pid = request.pid
    print("Club_key_id", club_key_id)
    clubKey = ndb.Key('Club', int(request.club_id))
    pidKey = ndb.Key('Profile', int(request.pid))
    profileconsidered = pidKey.get()
    club = clubKey.get()
    print("Club to be removed", club)
    # Check if the club's collegeId and Profile's collegeId are the same

    print("club.coolegeId", club.collegeId)
    print("profileconsidered.collegeId", profileconsidered.collegeId)
    if (club.collegeId == profileconsidered.collegeId):

        #check if the profile is the admin of the club or if he is the super admin of the college
        print("entered first part")
        print("Club.admin", club.admin)
        print("pidKey", pidKey)

        if (club.admin == pidKey
                or club.collegeId in profileconsidered.superadmin):

            # Operation 1 : for every profile key in member list of club, extract profile and remove the club
            # from the clubsJoined list
            print("Ive Entered Corrctly")
            for profile_key in club.members:
                profile = profile_key.get()
                profile.clubsJoined.remove(clubKey)
                profile.put()
    # Operation 2 : for every profile key in follows list of club, extract profile and remove the club
    # from the follows list of Profile
            for profile_key in club.follows:
                profile = profile_key.get()
                profile.follows.remove(clubKey)
                profile.put()

    #Operation 3 : Get the profile of the admin and remove the club key from his admin list
            adminProfile = club.admin.get()
            adminProfile.admin.remove(clubKey)
            adminProfile.put()
            #Operation 4 : Get the college and remove the club key from his grouplist
            college = club.collegeId.get()
            college.group_list.remove(clubKey)
            college.put()
            #Operation 5 : Get all notifications where it matches with clubKey and remove them

            notificationsRet = Notifications.query(
                Notifications.clubId == clubKey)
            for notif in notificationsRet:
                notif.key.delete()

    #Operation 6 : Get all JoinCreations and JoinRequests where it matches with clubKey and remove them

            joinCreationRet = Join_Creation.query(
                Join_Creation.club_id == clubKey)
            for jc in joinCreationRet:
                jc.key.delete()

            joinReqRet = Join_Request.query(Join_Request.club_id == clubKey)
            for jr in joinReqRet:
                jr.key.delete()
            postReqRet = Post_Request.query(Post_Request.club_id == clubKey)
            for pr in postReqRet:
                pr.key.delete()

    #Operation 7 - Posts and Events delete
            postRet = Post.query(Post.club_id == clubKey)

            for posts in postRet:
                likePostmini = LikePost()
                likePostmini.from_pid = str(club.admin.id())
                likePostmini.postId = str(posts.key.id())
                deletePost(likePostmini)

            eventRet = Event.query(Event.club_id == clubKey)

            for events in eventRet:
                modifyeventmini = ModifyEvent()
                modifyeventmini.from_pid = str(club.admin.id())
                modifyeventmini.eventId = str(events.key.id())
                deleteEvent(modifyeventmini)

    #Operation 8 - delete club
            clubKey.delete()
예제 #31
0
def deleteClub(request):
    # Steps to be incorporated for deletion of a club
    # 1) Remove the club key from the clubsJoined list of every profile
    # 2) Remove the club key from the follows list of every profile
    # 3) Remove the club key from the admin list of everyprofile
    # 4) Remove from college group list
    # 5) Remove notifications that have the club id = given club id
    # 6)Remove Join Creations and Join Requests
    # Call deleteEvent and deletePost for all events and posts that belong to the club
    # Delete the club entity

    club_key_id = request.club_id
    pid = request.pid
    print("Club_key_id", club_key_id)
    clubKey = ndb.Key("Club", int(request.club_id))
    pidKey = ndb.Key("Profile", int(request.pid))
    profileconsidered = pidKey.get()
    club = clubKey.get()
    print("Club to be removed", club)
    # Check if the club's collegeId and Profile's collegeId are the same

    print("club.coolegeId", club.collegeId)
    print("profileconsidered.collegeId", profileconsidered.collegeId)
    if club.collegeId == profileconsidered.collegeId:

        # check if the profile is the admin of the club or if he is the super admin of the college
        print("entered first part")
        print("Club.admin", club.admin)
        print("pidKey", pidKey)

        if club.admin == pidKey or club.collegeId in profileconsidered.superadmin:

            # Operation 1 : for every profile key in member list of club, extract profile and remove the club
            # from the clubsJoined list
            print("Ive Entered Corrctly")
            for profile_key in club.members:
                profile = profile_key.get()
                profile.clubsJoined.remove(clubKey)
                profile.put()
            # Operation 2 : for every profile key in follows list of club, extract profile and remove the club
            # from the follows list of Profile
            for profile_key in club.follows:
                profile = profile_key.get()
                profile.follows.remove(clubKey)
                profile.put()

            # Operation 3 : Get the profile of the admin and remove the club key from his admin list
            adminProfile = club.admin.get()
            adminProfile.admin.remove(clubKey)
            adminProfile.put()
            # Operation 4 : Get the college and remove the club key from his grouplist
            college = club.collegeId.get()
            college.group_list.remove(clubKey)
            college.put()
            # Operation 5 : Get all notifications where it matches with clubKey and remove them

            notificationsRet = Notifications.query(Notifications.clubId == clubKey)
            for notif in notificationsRet:
                notif.key.delete()

            # Operation 6 : Get all JoinCreations and JoinRequests where it matches with clubKey and remove them

            joinCreationRet = Join_Creation.query(Join_Creation.club_id == clubKey)
            for jc in joinCreationRet:
                jc.key.delete()

            joinReqRet = Join_Request.query(Join_Request.club_id == clubKey)
            for jr in joinReqRet:
                jr.key.delete()
            postReqRet = Post_Request.query(Post_Request.club_id == clubKey)
            for pr in postReqRet:
                pr.key.delete()

            # Operation 7 - Posts and Events delete
            postRet = Post.query(Post.club_id == clubKey)

            for posts in postRet:
                likePostmini = LikePost()
                likePostmini.from_pid = str(club.admin.id())
                likePostmini.postId = str(posts.key.id())
                deletePost(likePostmini)

            eventRet = Event.query(Event.club_id == clubKey)

            for events in eventRet:
                modifyeventmini = ModifyEvent()
                modifyeventmini.from_pid = str(club.admin.id())
                modifyeventmini.eventId = str(events.key.id())
                deleteEvent(modifyeventmini)

            # Operation 8 - delete club
            clubKey.delete()
    def register(request: Request):
        username = request.json['inputs']['name']
        email = request.json['inputs']['email']
        password: str = request.json['inputs']['password']
        re_password = request.json['inputs']['re_password']
        role = 1 if request.json['inputs']['role'] == '1' else 2

        if len(password) < 8:
            view = View(
                '',
                objects={'error': 'Password too short. Please try again...'})
            return Response(ResponseType.error, view)
        if password != re_password:
            view = View('',
                        objects={
                            'error':
                            'Passwords do not match. Please try again...'
                        })
            return Response(ResponseType.error, view)
        if '@' not in email or '.' not in email:
            view = View('',
                        objects={
                            'error':
                            'Email format is wrong. Please try again...'
                        })
            return Response(ResponseType.error, view)

        user = User.query().select().where('name', username).getOne()
        if user is not None:
            view = View('',
                        objects={
                            'error':
                            'Username already taken. Please try again...'
                        })
            return Response(ResponseType.error, view)

        passHash = hashlib.sha256(password.encode())
        passHash = passHash.hexdigest()

        User.query().insert([
            username, email, '', passHash, role,
            datetime.today(),
            datetime.today()
        ])

        user: User = User.query().select().where('name', username).getOne()
        token = user.hash()

        User_auth.query().insert(
            [user.id, token,
             datetime.today(),
             datetime.today()])

        NotificationController.notifyUser(
            user,
            'Welcome to freelancerHub, Feel free to look around the site.')

        notifications: List[Notification] = Notification.query().select(
        ).where('is_read', 0).get()
        posts = Post.query().select().where('user_id', user.id).get()

        view = View(
            'home', {
                'user': user,
                'notification_count': len(notifications),
                'my_post_count': len(posts)
            }, {
                'user_id': user.id,
                'authToken': token
            })
        return Response(ResponseType.valid, view)
예제 #33
0
def update():
    allfeeds = Feed.gql("")
    allposts = Post.gql("")
예제 #34
0
def parseFeed(feed, user):
    index = open(feed.url)  # gets html index
    index = index.read()  # continues

    soupd = soup(index)  # parse the hml with BeautifulSoup

    rsslink = soupd.findAll("link", type="application/rss+xml")  # this little mess will get the  # rss link
    if rsslink == "[]":
        rsslink = soupd.findAll("link", type="application/rdf+xml")  # or rdf
    elif rsslink == "[]":
        rsslink = soupd.findAll("link", type="application/atom+xml")  # or atom
    rsslink = str(rsslink)  # and put to a string

    # no need to understand this as none will ever comprehend RegExp
    # a hint, it strips the link out of the html tag
    link = re.search('href=".*?"', rsslink)
    if link == 0:
        link = link.group()
        link = re.search('HREF=".*?"', rsslink)
        link = link.strip("HREF=")
        link = str(link)
        link = link.strip('""')
    elif link == 0:
        print "erro, linha 94 engine.py, link para rss n encontrado!"
    else:
        link = link.group()
        link = str(link)
        link = link.strip("href=")
        link = link.strip('""')
    feed.rsslink = link  # we will need to store this, for updates
    # now some more fun, getting the real thing, xml content
    # from the link we have
    xml = open(link)
    xml = xml.read()
    # time to parse it with FeedParser
    k = feedparse(xml)
    feed.title = k.feed.title
    feed.put()
    # now let's parse the posts one-by-one
    for x in range(len(k.entries)):

        p = str(x)
        post = Post(url=k.entries[x].link, owner=user)
        # now that the post model is set, let us play!
        # ugly but necessary:
        if k.entries[x].has_key("author") is True:
            post.author = k.entries[x].author + " sings "
        else:
            post.author = "Anonymous"
        if k.entries[x].has_key("category") is True:
            post.category = " on " + k.entries[x].category
        else:
            post.category = ""
        if k.entries[x].has_key("date_parsed") is True:
            date = parseDate(k.entries[x].date_parsed)
            post.date = date

        if k.entries[x].has_key("summary") is True:
            post.summary = k.entries[x].summary
        else:
            post.summary = "No private dancing, cowboy..."

        if k.entries[x].has_key("title") is True:
            post.title = k.entries[x].title

        if len(post.title) == 0:
            post.title = "Untitled"

        post.feed = feed.key()
        post.put()

    return feed
예제 #35
0
파일: clubapis.py 프로젝트: RJJ11/SAMPLE
   def collegeFeed(self, request):
       print "Entered the Like Posts Section"
       temp = request.clubId
       flag =0
       pageLimit = 5
       skipCount=0
       upperBound=pageLimit
       print request.pageNumber

       try:
        skipCount = (int(request.pageNumber)-1)*pageLimit
        upperBound = int(request.pageNumber)*pageLimit

       except:
          print "Didnt give pageNumber-Default to 1"

       if request.date != None:
        date = datetime.strptime(getattr(request,"date"),"%Y-%m-%d").date()
        flag = 1
       #print "TYPE-DATE", type(date)
       if (temp==None):
           collegeId = ndb.Key('CollegeDb',int(request.collegeId))
           posts = Post.query(Post.collegeId==collegeId).order(-Post.timestamp)
           events = Event.query(Event.collegeId==collegeId).order(-Event.timestamp)
           print "TEMP IS NONE"
       else:
           clubId = ndb.Key('Club',int(request.clubId))
           posts = Post.query(Post.club_id==clubId).order(-Post.timestamp)
           events = Event.query(Event.club_id==clubId).order(-Event.timestamp)

       print events
       #CollegeFeed(items=[copyEventToForm(x) for x in posts])
       #CollegeFeed(items=[copyEventToForm(x) for x in events])
       #pylist = [copyToCollegeFeed(x) for x in events]
       pylist=[]
       for x in events:
           print "TImestamp",type(x.timestamp.strftime("%Y-%m-%d"))
           if flag==1:
            if x.timestamp.strftime("%Y-%m-%d") == str(date):
                pylist.append(copyToCollegeFeed(x))
           else:
               pylist.append(copyToCollegeFeed(x))
       print pylist
       pylist2 = []
       for x in posts:
           print "TImestamp",type(x.timestamp.strftime("%Y-%m-%d"))
           if flag==1:
            if x.timestamp.strftime("%Y-%m-%d") == str(date):
                pylist.append(copyToCollegeFeed(x))
           else:
               pylist.append(copyToCollegeFeed(x))
       #pylist2 = [copyToCollegeFeed(x) for x in posts]
       pylist+=pylist2
       #pylist.append(copyToCollegeFeed(x) for x in events)
       pylist.sort(key=lambda x: x.timestamp, reverse=True)
       #print pylist[1].timestamp
       #print pylist
       #CollegeFeed(items=pylist)
       #return CollegeFeed(items=[copyToCollegeFeed(x) for x in events])
       #return CollegeFeed(items=pylist)

       finalList = []
       for i in xrange(skipCount,upperBound):
           if(i>=len(pylist)):
            break
           finalList.append(pylist[i])

       cf = CollegeFeed()
       cf.items = finalList
       cf.completed=str(0)
       if(upperBound>=len(pylist)):
                cf.completed=str(1)
       #print pylist[1].timestamp
       #print pylist

       CollegeFeed(items=finalList)
       #return CollegeFeed(items=[copyToCollegeFeed(x) for x in events])
       return cf
예제 #36
0
파일: clubapis.py 프로젝트: RJJ11/SAMPLE
   def personalFeed(self, request):
       pid = ndb.Key('Profile',int(request.pid))
       profile = pid.get()
       posts = []
       events = []
       pylist = []
       pylist2 = []
       pageLimit = 5
       skipCount=0
       upperBound=pageLimit
       print request.pageNumber

       try:
        skipCount = (int(request.pageNumber)-1)*pageLimit
        upperBound = int(request.pageNumber)*pageLimit

       except:
          print "Didnt give pageNumber-Default to 1"



       list1=[]
       list2=[]
       for x in profile.follows:
           print x
           print "LOOP-1"
           posts = (Post.query(Post.club_id==x))
           events = (Event.query(Event.club_id==x))
           list1=[]
           list2=[]
           #list1 = [copyToCollegeFeed(y) for y in events]
           #list2 = [copyToCollegeFeed(z) for z in posts]
           iteration=0
           for y in posts:
               #if(iteration>=skipCount and iteration<upperBound):
               list1.append(copyToCollegeFeed(y))

               #iteration+=1
               #if(iteration==upperBound):
               #    break

           iteration=0

           for z in events:
               #if(iteration>=skipCount and iteration<upperBound):
                list1.append(copyToCollegeFeed(z))
                #iteration+=1
               #if(iteration==upperBound):
               #    break

           print "LIST-1"
           print list1
           pylist+=list1
           pylist2+=list2
       #for x in events:
       #    print x


       #pylist = [copyToCollegeFeed(x) for x in events]
       #pylist2 = [copyToCollegeFeed(x) for x in posts]
       pylist+=pylist2
       #pylist.append(copyToCollegeFeed(x) for x in events)
       pylist.sort(key=lambda x: x.timestamp, reverse=True)
       finalList = []
       for i in xrange(skipCount,upperBound):
           if(i>=len(pylist)):
            break
           finalList.append(pylist[i])

       cf = CollegeFeed()
       cf.items = finalList
       cf.completed=str(0)
       if(upperBound>=len(pylist)):
                cf.completed=str(1)
       #print pylist[1].timestamp
       #print pylist

       CollegeFeed(items=finalList)
       #return CollegeFeed(items=[copyToCollegeFeed(x) for x in events])
       return cf