Esempio n. 1
0
    def get(self, request, Format=None):
        logger.info('-' * 100)
        logger.info('Client Salesforce OAuth request =>')

        # Get the org_id from the request, I need to save it in cache because the callback
        # cannnot have a Bearer token Authorization header
        client_org = request.user
        # Save valid state integer in cache with the org_id linked to the client_org
        state = Utils.save_valid_state_in_cache('salesforce_oauth',
                                                client_org.salesforce_org_id)
        logger.debug(
            f'Saving salesforce_oauth_{state} in cache with status pending')

        oauth_url = Utils.make_url_with_params(
            self.endpoint_url,
            response_type='code',
            client_id=self.client_id,
            prompt='consent',
            redirect_uri=self.redirect_uri,
            scope='full refresh_token',
            state=state,
        )
        return Response({
            'oauth_url': oauth_url,
            'state': state
        },
                        status=status.HTTP_200_OK)
Esempio n. 2
0
    def test_median(self):
        """Test median function"""

        # test different medians
        table = np.array([[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6]])
        self.assertEqual([{
            'Response': {
                'median': 1
            }
        }, 200], Utils.median(table, [0, 1]))
        self.assertEqual([{
            'Response': {
                'median': 2
            }
        }, 200], Utils.median(table, [0, 2]))
        self.assertEqual([{
            'Response': {
                'median': 2
            }
        }, 200], Utils.median(table, [0, 3]))
        self.assertEqual([{
            'Response': {
                'median': 2
            }
        }, 200], Utils.median(table, [0, 4]))
        self.assertEqual([{
            'Response': {
                'median': 3
            }
        }, 200], Utils.median(table, [0, 5]))
Esempio n. 3
0
    def get(self, request, Format=None):
        logger.info('-' * 100)
        logger.info('Reddit Oauth request =>')

        # Create a valid state integer and save it to cache
        state = Utils.save_valid_state_in_cache('oauth')
        logger.debug(f'Saving oauth_{state} in cache with status pending')

        # Obtain authorization URL
        reddit = reddit = Utils.get_reddit_instance()
        # scopes = ['*'] All OAuth scopes available
        scopes = [
            'edit',
            'history',
            'identity',
            'mysubreddits',
            'read',
            'submit',
            'subscribe',
            'vote',
        ]
        auth_url = reddit.auth.url(scopes, state)
        logger.debug(f'Reddit auth url: {auth_url}')

        return Response({
            'oauth_url': auth_url,
            'state': state
        },
                        status=status.HTTP_200_OK)
Esempio n. 4
0
    def patch(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Comment "{id}" patch =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        comment = CommentsUtils.get_comment_if_exists(id, reddit)
        if comment is None:
            raise exceptions.NotFound(
                detail={'detail': f'No comment exists with the id: {id}.'})

        # Get the markdown content from json body attribute
        markdown_body = Utils.validate_body_value(request.data.get('body'))

        status_code = status.HTTP_200_OK
        updated_comment_data = None
        if not reddit.read_only:
            # Only can modify the comment if author is the same as the client redditor
            # So check for comment redditor and client data
            comment_redditor = comment.author
            redditor_id, redditor_name = ClientsUtils.get_redditor_id_name(
                client_org)

            if comment_redditor.id == redditor_id:
                # Try to delete the comment now
                try:
                    updated_comment = comment.edit(markdown_body)
                    # Here I need to call refresh() to get the actual replies count
                    updated_comment.refresh()
                    updated_comment_data = CommentsUtils.get_comment_data(
                        updated_comment)
                    msg = f'Comment \'{updated_comment.id}\' successfully edited.'
                    logger.info(msg)
                except Exception as ex:
                    msg = f'Error edit comment. Exception raised: {repr(ex)}.'
                    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                    logger.error(msg)
            else:
                msg = (
                    f'Cannot edit the comment with id: {id}. '
                    f'The authenticated reddit user u/{redditor_name} '
                    f'needs to be the same as the comment\'s author u/{comment_redditor.name}'
                )
                status_code = status.HTTP_403_FORBIDDEN
                logger.info(msg)
        else:
            msg = f'Reddit instance is read only. Cannot edit comment with id: {id}.'
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({
            'detail': msg,
            'comment': updated_comment_data
        },
                        status=status_code)
Esempio n. 5
0
 def test_get_database(self):
     """Test get_database function"""
     database = {}
     database[0] = 'yes'
     database[1] = 'even more yes'
     # check good value
     self.assertEqual('yes', Utils.get_database(database, 0))
     # check bad indexing
     self.assertNotEqual('yes', Utils.get_database(database, 1))
     # key is not valid
     self.assertRaises(ValueError, Utils.get_database, database, 3)
Esempio n. 6
0
def handle_pip(user, package):
    if request.method == 'GET':
        if package != '--list--':
            return format_return(Utils.get_pip(package))
        else:
            return format_return(Utils.get_pip_list())
    elif request.method == 'PUT':
        return format_return(Utils.put_pip(package))
    elif request.method == 'DELETE':
        return format_return(Utils.delete_pip(package))

    else:
        return 'access to that service not allowed', 204
Esempio n. 7
0
    def post(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" reply =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        # Get the markdown content from json body attribute
        markdown_body = Utils.validate_body_value(request.data.get('body'))

        comment_data = None
        status_code = status.HTTP_201_CREATED
        if not reddit.read_only:
            # Try to post the comment to the submission
            try:
                comment = submission.reply(markdown_body)
                comment_data = CommentsUtils.get_comment_data(comment)
                _, redditor_name = ClientsUtils.get_redditor_id_name(client_org)
                msg = (
                    f'New comment posted by u/{redditor_name} with id \'{comment.id}\' '
                    f'to submission with id: {id}'
                )
                logger.info(msg)
            except Exception as ex:
                if isinstance(ex, Forbidden):
                    msg = (
                        f'Cannot create a comment in submission with id: {id}. '
                        f'Forbidden exception: {repr(ex)}'
                    )
                    status_code = status.HTTP_403_FORBIDDEN
                else:
                    msg = (
                        f'Error creating comment in submission with id: {id}. '
                        f'Exception raised: {repr(ex)}.'
                    )
                    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                logger.error(msg)
        else:
            msg = f'Reddit instance is read only. Cannot create comment in submission with id: {id}.'
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({'detail': msg, 'comment': comment_data}, status=status_code)
Esempio n. 8
0
def cpf_validator(value):
    if len(value) != 11 or len(set(value)) == 1:
        raise serializers.ValidationError("CPF precisa ter 11 caracteres")

    first_cpf_weight = [10, 9, 8, 7, 6, 5, 4, 3, 2]
    second_cpf_weight = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
    first_part = value[:9]
    first_digit = value[9]
    second_digit = value[10]

    if not ((first_digit == Utils().get_first_digit(number=first_part,
                                                    weight=first_cpf_weight)
             and second_digit == Utils().get_second_digit(
                 updated_number=value[:10], weight=second_cpf_weight))):
        raise serializers.ValidationError("CPF Inválido")
Esempio n. 9
0
    def get(self, request, Format=None):
        logger.info('-' * 100)
        logger.info('Client information request =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)

        subreddits = []
        if reddit.read_only:
            redditor_data = RedditorsUtils.get_dummy_redditor_data()
            redditor_id = redditor_data['id']
        else:
            # Get the current authenticated reddit user data
            api_redditor = reddit.user.me()
            redditor_id = api_redditor.id
            redditor_data = RedditorsUtils.get_redditor_data(api_redditor)
            for sub in reddit.user.subreddits():
                subreddits.append(
                    SubredditsUtils.get_subreddit_data_simple(sub))

        # Create or update redditor object for this client
        redditor = Redditor.objects.get_or_none(id=redditor_id)
        serializer = RedditorSerializer(instance=redditor, data=redditor_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        redditor_data = serializer.data

        redditor_data.update(subscriptions=subreddits)
        return Response(data=redditor_data, status=status.HTTP_200_OK)
Esempio n. 10
0
    def delete(self, request, name, Format=None):
        logger.info('-' * 100)
        logger.info(f'Subreddit "{name}" disconnect =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        subreddit = SubredditsUtils.get_sub_if_available(name, reddit)
        if subreddit is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No subreddit exists with the name: {name}.'
                })

        subreddit_obj = Subreddit.objects.get_or_none(id=subreddit.id)
        if subreddit_obj is None:
            raise exceptions.NotFound(
                detail={
                    'detail':
                    'No subreddit found with the name provided to make the disconnection.'
                })
        # Remove the client connection from both sides
        subreddit_obj.clients.remove(client_org)
        client_org.subreddit_set.remove(subreddit_obj)

        return Response(
            data={'detail': 'Client disconnected subreddit succesfully.'},
            status=status.HTTP_200_OK,
        )
Esempio n. 11
0
def handle_service(user, service, action):
    if service in [
            'nodered', 'motion', 'pigpiod', 'm2ag-core', 'm2ag-builder',
            'mosquitto'
    ]:
        return format_return(Utils.service_action(service, action))
    else:
        return 'access to that service not allowed', 200
Esempio n. 12
0
    def delete(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" delete =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        status_code = status.HTTP_200_OK
        if not reddit.read_only:
            # Only can delete the submission if author is the same as the reddit instance
            # So check for submission redditor and reddit redditor
            submission_redditor = submission.author
            if submission_redditor:
                redditor_id, redditor_name = ClientsUtils.get_redditor_id_name(
                    client_org
                )
                if submission_redditor.id == redditor_id:
                    # Try to delete the submission now
                    try:
                        submission.delete()
                        msg = f'Submission \'{id}\' successfully deleted.'
                        logger.info(msg)
                    except Exception as ex:
                        msg = (
                            f'Error deleting submission. Exception raised: {repr(ex)}.'
                        )
                        status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                        logger.error(msg)
                else:
                    msg = (
                        f'Cannot delete the submission with id: {id}. '
                        f'The authenticated reddit user u/{redditor_name} '
                        f'needs to be the same as the submission\'s author u/{submission_redditor.name}'
                    )
                    status_code = status.HTTP_403_FORBIDDEN
                    logger.info(msg)
            else:
                msg = (
                    f'Cannot delete the submission with id: {id}. '
                    'The submission was already deleted or there is no '
                    'way to verify the author at this moment.'
                )
                status_code = status.HTTP_404_NOT_FOUND
                logger.info(msg)
        else:
            msg = (
                f'Reddit instance is read only. Cannot delete submission with id: {id}.'
            )
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({'detail': msg}, status=status_code)
Esempio n. 13
0
 def DELETE(self, environ,start_response):
     self.content = ''
     req = Request(environ)
     self.userName = req.headers.get('X-Auth-User', '')
     self.userKey = req.headers.get('X-Auth-Key', '')
     self.domain = req.headers.get('domain', '')
     self.object = req.headers.get('object', '')
     self.size = req.headers.get('content-length', '')
     containers_object = req.headers.get('container','')
     containers_object.append(str(self.object))
     Log().info("start object GET operation username:"******",domain:"+self.domain+",container:"+str(containers_object)+
                ",object:"+self.object)
     c_len = len(containers_object)# the length of the container
     root_id = Utils.getRootContainerId(self.domain)
     parent_id = root_id
     if parent_id == '':
         Log().error('can not get the domain ['+self.domain+"] id")
         start_response(HTTPNotFound,[("Content-type", "text/plain"),])
         return ''
     resheaders = []
     for i in xrange(c_len):
         c_name = containers_object[i].encode("UTF-8")
         kwargs = {'m_name':c_name, 'm_parent_id':parent_id}
         containers_object_get = DataLogic().get_by_kwargs(**kwargs)
         if len(containers_object_get) == 0:
             if i == c_len-1:
                 Log().error('can not get the object ['+c_name+"] id")
                 start_response(HTTPNotFound,[("Content-type", "text/plain"),])
                 return ''
             else:
                 Log().error('can not get the container ['+c_name+"] id")
                 start_response(HTTPNotFound,[("Content-type", "text/plain"),])
                 return ''
             break
         else:
             if i == c_len-1:
                 self.object = containers_object_get[0].m_storage_name
             else:
                 self.container = containers_object_get[0].m_storage_name
             parent_id = containers_object_get[0].id
     try:
         Log().info('START DELETE_OBJECT by '+self.userName+': '+self.domain+'/'+self.container+'/'+self.object)
         token = req.headers['token']
         url = req.headers['auth_url']
         dic = {"storage_url":url, 'token':token, 'container':self.container,'headers':{}, \
                'object':self.object,}
         ApiMapping().scloud_delete_object(**dic)
         kwargs = {
                     'id': parent_id,
             }      
         DataLogic().delete_data_by_id(**kwargs)
         start_response(HTTPOk, [("Content-type", "text/plain"),])
         return ''
     except Exception,e:
         Log().error('DELETE_OBJECT by '+req.headers.get('X-Auth-User')+': '+req.headers['domain']+'/'+str(req.headers['container'])+' '+str(e))
         start_response(HTTPInternalServerError, resheaders)
         return ''
Esempio n. 14
0
    def GET(self, environ,start_response):
        req = Request(environ)
        self.userName = req.headers.get('X-Auth-User', '')
        self.userKey = req.headers.get('X-Auth-Key', '')
        self.domain = req.headers.get('domain', '')
        self.token = ''
        resheaders = []
        root_id = Utils.getRootContainerId(self.domain)
        if root_id == '':
            Log().error('can not get the domain ['+self.domain+"] id")
            start_response(HTTPNotFound,[("Content-type", "text/plain"),])
            return ''
        try:
            kwargs = {'m_parent_id':root_id}
            cons_objs_get = DataLogic().get_by_kwargs(**kwargs)
        
            if len(cons_objs_get) == 0:
                start_response(HTTPNoContent,[("Content-type", "text/plain"),])
                return ''
            #
            #modify by zhangkaixuan
            #
            containers = '[' 
            objects = '['

            for x in range(len(cons_objs_get)):
                if cons_objs_get[x].m_content_type == 'container':
                    #containers.append(cons_objs_get[x].m_name)
                    containers  = containers + cons_objs_get[x].m_name + ','
                elif cons_objs_get[x].m_content_type == 'object':
                    #objects.append(cons_objs_get[x].m_name)
                    objects = objects + cons_objs_get[x].m_name + ','       
            #cons = ('containers',str(containers))
            #objs = ('objects', str(objects))
            #count = ('count', len(cons_objs_get))
            
            if containers != '[':
                containers = containers[:-1]
            if objects != '[':
                objects = objects[:-1]  
            all = containers + "]#" + objects +"]"
            print all    
            param = str(len(all))+'s'                                                 
            bytes = struct.pack(str(param),all)
            self.content = bytes
            #resheaders.append(cons)
            #resheaders.append(objs)
            #resheaders.append(count)
            #
            #modify by zhangkaixuan
            #
            start_response(HTTPOk,resheaders)
            return self.content
        except Exception,e:
            Log().error('GET_DOMAIN by '+req.headers.get('X-Auth-User')+': '+req.headers['domain']+' '+str(e))
            start_response(HTTPInternalServerError, resheaders)
            return ''
Esempio n. 15
0
 def POST(self, environ,start_response):
     
     '''POST can be used to change object metadata
     object rename
     '''
     self.content = ''
     req = Request(environ)
     self.userName = req.headers.get('X-Auth-User', '')
     self.userKey = req.headers.get('X-Auth-Key', '')
     self.domain = req.headers.get('domain', '')
     self.original_name = req.headers.get('object','').encode("UTF-8")
     self.current_name = req.headers.get('current-name','').encode("UTF-8")
     
     containers = req.headers.get('container','')
     Log().info("start object POST operation username:"******",domain:"+self.domain+",container:"+str(containers)+",original-name:"+self.original_name+",current-name:"+self.current_name)  
     c_len = len(containers)# the length of the container
     root_id = Utils.getRootContainerId(self.domain)
     parent_id = root_id
     if parent_id == '':
         Log().error('can not get the domain ['+self.domain+"] id")
         start_response(HTTPNotFound,[("Content-type", "text/plain"),])
         return ''
     resheaders = []
     if self.current_name == '':
         start_response(HTTPBadRequest,[("Content-type", "text/plain"),])
         return 'current_name not assigned\n'
     for i in xrange(c_len):
         c_name = containers[i].encode("UTF-8")
         # get all the containers corresponding to such conditions    
         kwargs = {'m_name':c_name, 'm_parent_id':parent_id,  'm_content_type':'container'}
         containers_get = DataLogic().get_by_kwargs(**kwargs)
         if len(containers_get) != 0:
             parent_id = containers_get[0].id
             if i == c_len-1:
                 try:
                     kws = {'m_name':self.original_name, 'm_parent_id':parent_id, 'm_content_type':'object'}
                     o_get = DataLogic().get_by_kwargs(**kws)
                     object_id = o_get[0].id
                     kwsExisting = {'m_name':self.current_name, 'm_parent_id':parent_id, 'm_content_type':'object'}
                     o_get_2 = DataLogic().get_by_kwargs(**kwsExisting)
                     if len(o_get_2) == 0:
                         kwargs = {'id':object_id, 'm_name':self.current_name}
                         DataLogic().update_data_by_id(**kwargs)
                         start_response(HTTPOk, resheaders)
                         return self.content
                     else:
                         start_response(HTTPConflict, resheaders)
                         return self.content
                 except Exception,e:
                     Log().error('POST_OBJECT by '+req.headers.get('X-Auth-User')+': '+req.headers['domain']+'/'+str(req.headers['container'])+' '+str(e))
                     start_response(HTTPInternalServerError, resheaders)
                     return self.content
         else:
             Log().error('Containers not Found, POST_OBJECT by '+req.headers.get('X-Auth-User')+': '+req.headers['domain']+'/'+str(req.headers['container']))
             start_response(HTTPNotFound, resheaders)
             return self.content    
Esempio n. 16
0
    def test_convert_string_date_int(self):
        """Test convert_string_date_int function"""

        # good values
        self.assertEqual(1547035200000000000,
                         Utils.convert_string_date_int('2019-01-09T12:00:00'))
        self.assertEqual(1547035200000000000,
                         Utils.convert_string_date_int('2019-01-09T12:00:00Z'))

        #assert int increases with time
        self.assertLess(154703520000,
                        Utils.convert_string_date_int('2019-01-09T12:00:01'))
        self.assertLess(154703520000,
                        Utils.convert_string_date_int('2019-01-09T12:00:01'))

        # assert it can crash if not date or wrong format
        self.assertRaises(ValueError, Utils.convert_string_date_int, '')
        self.assertRaises(ValueError, Utils.convert_string_date_int,
                          '2019-01-0912:00:01Z')
Esempio n. 17
0
 def test_check_inputs(self):
     """Test check_inputs function"""
     # successful run
     self.assertEqual(('2019-01-09T12:00:00', '2019-01-09T12:00:00'),
                      Utils.check_inputs('2019-01-09T12:00:00',
                                         '2019-01-09T12:00:00'))
     # one of the inputs is missing
     self.assertRaises(ValueError, Utils.check_inputs,
                       '2019-01-09T12:00:00', '')
     self.assertRaises(ValueError, Utils.check_inputs, '',
                       '2019-01-09T12:00:00')
     self.assertRaises(ValueError, Utils.check_inputs, '', '')
Esempio n. 18
0
    def get(self, request, name, Format=None):
        logger.info('-' * 100)
        logger.info(f'Subreddit "{name}" rules =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        subreddit = SubredditsUtils.get_sub_if_available(name, reddit)
        if subreddit is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No subreddit exists with the name: {name}.'
                })

        return Response(subreddit.rules(), status=status.HTTP_200_OK)
Esempio n. 19
0
    def get(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" comments =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get submission instance with the id provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        sort = request.query_params.get('sort', 'best')
        flat = request.query_params.get('flat', False)
        limit = request.query_params.get('limit', 10)
        offset = request.query_params.get('offset', 0)

        sort, limit, offset = self._validate_query_params(sort, flat, limit, offset)
        logger.info(f'Sort type: {sort}')
        logger.info(f'Limit: {limit}')
        logger.info(f'Offset: {offset}')
        logger.info(f'Flat: {flat}')

        # Get submissions generator according to query_params and with the limit + offset?
        comments_generator = self._get_comments(submission, sort, limit + offset, flat)

        comments = []
        for index, comment in enumerate(comments_generator, start=1):
            if index > offset:
                comments.append(CommentsUtils.get_comment_data_simple(comment))
                # For some reason the comment_limit attr in the submission instance does not work
                # as suggested in docs, so breaking here when it reaches limit comments
                if len(comments) > limit - 1:
                    break

        logger.info(f'Total comments retrieved: {len(comments)}')

        return Response(
            {
                'comments': comments,
                'sort_type': sort,
                'limit_request': limit,
                'offset': offset,
                'flat': flat,
            },
            status=status.HTTP_200_OK,
        )
Esempio n. 20
0
    def get(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" info request =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        # Get data I need from submission instance
        submission_data = SubmissionsUtils.get_submission_data(submission)
        return Response(submission_data, status=status.HTTP_200_OK)
Esempio n. 21
0
    def post(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" vote =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        # Get vote value from data json and check if valid
        vote_value = self._validate_vote_value(request.data.get('vote_value'))

        submission_data = None
        status_code = status.HTTP_200_OK
        if reddit.read_only:
            msg = f'Vote action \'dummy\' successful for submission with id: {id}.'
        else:
            try:
                if vote_value == -1:
                    vote_action = 'Downvote'
                    submission.downvote()
                elif vote_value == 0:
                    vote_action = 'Clear Vote'
                    submission.clear_vote()
                else:
                    vote_action = 'Upvote'
                    submission.upvote()
                submission_data = SubmissionsUtils.get_submission_data_simple(
                    submission
                )
                msg = f'Vote action \'{vote_action}\' successful for submission with id: {id}.'
                logger.info(msg)
            except Exception as ex:
                status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                msg = (
                    f'Error posting vote to submission with id: {id}. '
                    f'Exception raised: {repr(ex)}.'
                )
                logger.error(msg)

        return Response(
            {'detail': msg, 'submission': submission_data}, status=status_code,
        )
Esempio n. 22
0
    def get(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Comment "{id}" replies =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get submission instance with the id provided
        comment = CommentsUtils.get_comment_if_exists(id, reddit)
        if comment is None:
            raise exceptions.NotFound(
                detail={'detail': f'No comment exists with the id: {id}.'})

        flat = request.query_params.get('flat', False)
        limit = request.query_params.get('limit', 10)
        offset = request.query_params.get('offset', 0)

        limit, offset = self._validate_query_params(flat, limit, offset)
        logger.info(f'Limit: {limit}')
        logger.info(f'Offset: {offset}')

        # Here I need to call refresh() for some reason to get the actual replies count
        comment.refresh()
        logger.info(f'Total top replies: {len(comment.replies)}')

        # Get replies generator from the comment instance
        replies_generator = self._get_replies(comment, flat)

        replies = []
        for index, reply in enumerate(replies_generator, start=1):
            if index > offset:
                replies.append(CommentsUtils.get_comment_data_simple(reply))
                # For some reason the comment_limit attr in the submission instance does not work
                # as suggested in docs, so breaking here when it reaches limit comments
                if len(replies) > limit - 1:
                    break

        logger.info(f'Total comments retrieved: {len(replies)}')

        return Response(
            {
                'replies': replies,
                'limit_request': limit,
                'offset': offset,
                'flat': flat,
            },
            status=status.HTTP_200_OK,
        )
Esempio n. 23
0
    def post(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Comment "{id}" vote =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        comment = CommentsUtils.get_comment_if_exists(id, reddit)
        if comment is None:
            raise exceptions.NotFound(
                detail={'detail': f'No comment exists with the id: {id}.'})

        # Get vote value from data json and check if valid
        vote_value = self._validate_vote_value(request.data.get('vote_value'))

        comment_data = None
        status_code = status.HTTP_200_OK
        if reddit.read_only:
            msg = f'Vote action \'dummy\' successful for comment with id: {id}.'
        else:
            try:
                if vote_value == -1:
                    vote_action = 'Downvote'
                    comment.downvote()
                elif vote_value == 0:
                    vote_action = 'Clear Vote'
                    comment.clear_vote()
                else:
                    vote_action = 'Upvote'
                    comment.upvote()
                # Need to force refresh to get replies count
                comment.refresh()
                comment_data = CommentsUtils.get_comment_data_simple(comment)
                msg = f'Vote action \'{vote_action}\' successful for comment with id: {id}.'
                logger.info(msg)
            except Exception as ex:
                status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                msg = (f'Error posting vote to comment with id: {id}. '
                       f'Exception raised: {repr(ex)}.')
                logger.error(msg)

        return Response(
            {
                'detail': msg,
                'comment': comment_data,
            },
            status=status_code,
        )
Esempio n. 24
0
    def delete(self, request, Format=None):
        """
        Method to disconnect a Salesforce Org Client. Revokes access token from Reddit and
        deletes oauth token in database changing the Client Org to inactive status in the process
        """
        logger.info('-' * 100)
        logger.info('Client Reddit access token revoke =>')

        # If the request is authenticated correctly by the bearer token then I can get
        # the client_org from the request.user. Return tuple from TokenAuthentication:
        # (request.user, request.auth) = (client_org, bearer_token)

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        try:
            reddit._core._authorizer.revoke()
            logger.info('Reddit access token revoked succesfully.')
        except Exception as ex:
            logger.error(
                f'Error revoking access. Exception raised: {repr(ex)}.')

        # Now I need to delete the oauth_token from database and change the status to inactive
        _, salesforce_org_name = ClientsUtils.get_salesforce_org_id_name(
            client_org)
        logger.info(
            f'Deleting Reddit access token for org \'{salesforce_org_name}\' '
            'and changing status to inactive for client.')
        serializer = ClientOrgSerializer(
            instance=client_org,
            data={
                'disconnected_at': now(),
                'reddit_token': None,
                'is_active': False
            },
        )
        serializer.is_valid(raise_exception=True)
        client_org = serializer.save()

        bearer_token = request.auth
        logger.debug(repr(bearer_token))
        bearer_token.delete()

        return Response(
            data={'detail': 'Account disconnected succesfully.'},
            status=status.HTTP_200_OK,
        )
Esempio n. 25
0
    def post(self, request, name, Format=None):
        """POST request that expects the subreddit name to connect the client to.
        Arguments:
                request {[type]} -- DRF Request object
                name {[string]} -- Subreddit name
        Keyword Arguments:
                Format {[string]} -- [description] (default: {None})
        """
        logger.info('-' * 100)
        logger.info(f'Subreddit "{name}" connect =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        subreddit = SubredditsUtils.get_sub_if_available(name, reddit)
        if subreddit is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No subreddit exists with the name: {name}.'
                })

        logger.info(f'Connecting to Subreddit \'{subreddit.name}\'')
        if not reddit.read_only and not subreddit.user_is_subscriber:
            logger.info(
                'Client is not subscribed, so I need to subscribe him here...')
            status_code, msg = SubredditsUtils.subscribe_action(
                reddit, logger, name, client_org, subreddit)
            if status_code != status.HTTP_200_OK:
                return Response({'detail': msg}, status=status_code)

        # Get data I need from subreddit instance
        subreddit_data = SubredditsUtils.get_subreddit_data(subreddit)
        # TODO: Here for now I'll just save the subreddit_data in a Subreddit Model object
        # But I need to enqueue this into a redis queue, send the data to user as fast as possible
        subreddit_obj = SubredditsUtils.create_or_update(subreddit_data)
        # Add the client_org connection to the object
        subreddit_obj.clients.add(client_org)

        return Response(
            {
                'detail': 'Client connected subreddit succesfully.',
                'subreddit': subreddit_data,
            },
            status=status.HTTP_201_CREATED,
        )
Esempio n. 26
0
    def get(self, request, Format=None):
        logger.info('-' * 100)
        logger.info(f'Subreddits subscriptions for client =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)

        if reddit.read_only:
            subreddits = []
        else:
            reddit_user = reddit.user
            subreddits = [
                SubredditsUtils.get_subreddit_data_simple(sub)
                for sub in reddit_user.subreddits()
            ]

        return Response({'subscriptions': subreddits},
                        status=status.HTTP_200_OK)
Esempio n. 27
0
def logIn(username, password):
    session["realname"] = None
    requestid = username + "_" + Utils.getFormattedDateTime()
    session["requestid"] = requestid
    s = requests.session()
    r = s.get(CONST.PORTAL_URL, headers=CONST.headers)
    imgraw = s.get(CONST.CAPTACHA_URL)
    with open(
            DEPLOY_PATH + 'static/temp/captacha/captacha_' + requestid +
            '.jpg', 'wb+') as f:
        f.write(imgraw.content)
    img = Image.open(DEPLOY_PATH + 'static/temp/captacha/captacha_' +
                     requestid + '.jpg')
    code = pytesseract.image_to_string(img)
    print('pytesseract.image_to_string() result:', code)
    postData = {
        'code': code,
        'rsa': RSA.GetRSA(username, password),
        'ul': len(username),
        'pl': len(password),
        'lt': 'LT-211100-OG7kcGcBAxSpyGub3FC9LU6BtINhGg-cas',
        'execution': 'e1s1',
        '_eventId': 'submit'
    }
    r = s.post(CONST.PORTAL_URL, data=postData)
    elements = etree.HTML(r.content)
    errors = elements.xpath('//*[@id="errormsg"]')
    if len(errors) == 0:
        realName = elements.xpath(
            '//a[contains(@title, "查看登录记录")]/font/text()')[0]
        print('Login Success - ', realName, 'Session ID:', requestid)
        # server.sessions[requestid] = s.cookies
        session["usercookie"] = requests.utils.dict_from_cookiejar(s.cookies)
        # session["usercookie"] = s.cookies
        session["uid"] = username
        session["realname"] = realName
        return 0
    elif elements.xpath('//*[@id="errormsg"]/text()')[0] == "验证码有误":
        return -1
    elif elements.xpath('//*[@id="errormsg"]/text()')[0] == "用户名密码错误":
        return -2
    else:
        return -3
    cookie = ""
Esempio n. 28
0
    def get(self, request, name, Format=None):
        logger.info('-' * 100)
        logger.info(f'Subreddit "{name}" submissions =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        subreddit = SubredditsUtils.get_sub_if_available(name, reddit)
        if subreddit is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No subreddit exists with the name: {name}.'
                })

        sort = request.query_params.get('sort', 'hot')
        time_filter = request.query_params.get('time_filter', 'all')
        offset = request.query_params.get('offset', 0)

        offset = self._validate_query_params(sort, time_filter, offset)
        logger.info(f'Sort type: {sort}')
        logger.info(f'Time filter: {time_filter}')
        logger.info(f'offset: {offset}')

        # Get submissions generator according to query_params and with the limit + offset?
        submissions_generator = self._get_submissions(subreddit, sort,
                                                      time_filter, offset + 5)

        submissions = [
            SubmissionsUtils.get_submission_data_simple(sub)
            for index, sub in enumerate(submissions_generator, start=1)
            if index > offset
        ]
        logger.info(f'Total submissions: {len(submissions)}')

        return Response(
            {
                'submissions': submissions,
                'sort_type': sort,
                'time_filter': time_filter,
                'offset': offset,
            },
            status=status.HTTP_200_OK,
        )
Esempio n. 29
0
    def get(self, request, name, Format=None):
        logger.info('-' * 100)
        logger.info(f'Subreddit "{name}" info request =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        subreddit = SubredditsUtils.get_sub_if_available(name, reddit)
        if subreddit is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No subreddit exists with the name: {name}.'
                })

        # Get data I need from subreddit instance
        subreddit_data = SubredditsUtils.get_subreddit_data(subreddit)
        # TODO: Enqueue this in a redis queue job later
        SubredditsUtils.create_or_update(subreddit_data)

        return Response(subreddit_data, status=status.HTTP_200_OK)
Esempio n. 30
0
    def get(self, request, name, Format=None):
        logger.info('-' * 100)
        logger.info(f'Redditor "{name}" info =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, _ = Utils.new_client_request(request.user)
        # Get redditor instance with the name provided
        redditor = RedditorsUtils.get_redditor_if_exists(name, reddit)
        if redditor is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No redditor exists with the name: {name}.'
                })

        # Get data I need from subreddit instance
        redditor_data = RedditorsUtils.get_redditor_data(redditor)
        # Enqueue this in a redis queue job later
        # RedditorsUtils.create_or_update(redditor_data)

        return Response(redditor_data, status=status.HTTP_200_OK)
Esempio n. 31
0
def GetClassCSV(semester, reminder):
	obtainedClass.clear()
	global requestid
	requestid = session.get("requestid")
	setReminder(reminder)
	setFirstWeekDate(CONST.FIRST_WEEK_DATE[semester])
	setClassInfo()
	setClassTime()
	uniteSetting();
	classInfoHandle();
	icsCreateAndSave();
	print('课程表已保存至脚本目录下的 class.ics 中,你现在可以导入了:)')
	result = {
		"link": "/output/class_" + requestid +".ics",
		"obtained_class": obtainedClass,
		"reminder": reminder
	}
	with open (DEPLOY_PATH + 'log/success.log', 'a+', encoding='utf-8') as f:
		f.write(Utils.getCurrentDateTime() + ',' + requestid + ',' + session.get('realname') + ',' + reminder + ',' + str(obtainedClass)+'\n')
		f.close()
	return result
Esempio n. 32
0
def sendFeedback():
    files = request.files.getlist("file")
    message = request.form['message']
    contact = request.form['contact']
    requestid = session.get("requestid")
    if requestid is None:
        requestid = Utils.getFormattedDateTime()
    withFile = False
    if (len(files) > 0):
        withFile = True
        for one in files:
            one.save(
                os.path.join(DEPLOY_PATH + 'static/temp/upload',
                             requestid + '.' + secure_filename(one.filename)))
        filePath = '/temp/upload/' + requestid + '.' + secure_filename(
            one.filename)
        Feedback.SendPhoto(filePath)
    feedbackResult = Feedback.Send(message, contact, withFile)
    if not (feedbackResult["ok"] == True):
        return makeJsonResponse(CODE_ERROR, feedbackResult)
    return makeJsonResponse(CODE_SUCCESS, feedbackResult)
Esempio n. 33
0
def Send(msg, contact, withFile):
    global RECIEVERS
    requestid = session.get("requestid") if session.get(
        "requestid") is not None else "N/A"
    realname = session.get("realname") if session.get(
        "realname") is not None else "N/A"
    if (msg is None):
        msg = ""
    if (contact is None or contact == ''):
        contact = "匿名用户"
    if (withFile):
        contact = contact + " 📎"
    for one in RECIEVERS:
        text = "`<ECNU-class2ics>`\n收到来自 *" + contact + "* 的反馈:\n\n" + msg + "\n\n`requestid: " + requestid + "`"
        postUrl = "https://api.telegram.org/bot" + BOT_TOKEN + "/sendMessage?parse_mode=markdown&chat_id=" + one + "&text=" + text
        result = requests.post(postUrl)
        print(result.content)
    with open(DEPLOY_PATH + 'log/feedback.log', 'a+', encoding='utf-8') as f:
        f.write(Utils.getCurrentDateTime() + ',' + requestid + ',' + realname +
                ',' + contact + ',' + msg + '\n')
        f.close()
    return json.loads(result.content, encoding="unicode")
Esempio n. 34
0
    def PUT(self, environ,start_response):
        self.content = ''
        req = Request(environ)
        self.userName = req.headers.get('X-Auth-User', '')
        self.userKey = req.headers.get('X-Auth-Key', '')
        self.domain = req.headers.get('domain', '')
        containers = req.headers.get('container','')
        self.object = req.headers.get('object', '').encode("UTF-8")
        self.size = req.headers.get('content-length', '')
        
        c_len = len(containers)# the length of the container
        root_id = Utils.getRootContainerId(self.domain)
        parent_id = root_id
        
        if parent_id == '':
            Log().error('can not get the domain ['+self.domain+"] id")
            start_response(HTTPNotFound,[("Content-type", "text/plain"),])
            return ''
        
        if c_len == 0:
            self.container = Utils.getRootContainerStorageName(self.domain)
        resheaders = []
        Log().info("start object PUT operation username:"******",domain:"+self.domain+",containers:"+str(containers)+
                   ",object:"+self.object)        
        for i in xrange(c_len):
            c_name = containers[i].encode("UTF-8")
            kwargs = {'m_name':c_name, 'm_parent_id':parent_id, 'm_content_type':'container'}
            containers_get = DataLogic().get_by_kwargs(**kwargs)
            if len(containers_get) == 0:
                Log().error('Containers not Found, PUT_OBJECT by '+req.headers.get('X-Auth-User')+': '+req.headers['domain']+'/'+str(req.headers['container']))
                start_response(HTTPNotFound, resheaders)
                return self.content  
            else:
                self.container = containers_get[0].m_storage_name
                parent_id = containers_get[0].id
                
        kwargs = {'m_name':self.object, 'm_parent_id':parent_id, 'm_content_type':'object'}
        object_get = DataLogic().get_by_kwargs(**kwargs)
        
        if len(object_get) > 0:
            kws = {'id':object_get[0].id}
            object_get = DataLogic().delete_data_by_id(**kws)
        try:
            Log().info('START PUT_OBJECT by '+self.userName+': '+self.domain+'/'+str(containers)+'/'+self.object)

            token = req.headers['token']
            url = req.headers['auth_url']
            sfile = req.body_file
            #transaction control
            object_name_construct = self.userName+'_'+str(parent_id)+'_'+self.object+'_'+self.domain+'_'+'object_'+"".join(re.split('\W+', str(datetime.datetime.now())))
            object_storagename = hashlib.md5(object_name_construct).hexdigest()  
             
            dic = {"storage_url":url, 'token':token, 'container':self.container,'headers':{}, \
                   'object':object_storagename, 'contents':sfile}
            object_hash = ApiMapping().scloud_put_object(**dic)
            kwargs = {
                            'm_name' : self.object,
                            'm_storage_name' : object_storagename,
                            'm_domain_name' : self.domain,
                            'm_content_type' : 'object',
                            'm_status' : '1',   #'1' means available, '0' means not available
                            'm_uri' : object_storagename,
                            'm_hash' : object_hash ,
                            'm_size' : '2G',
                            'm_parent_id' : parent_id,
                            'created' : str(datetime.datetime.now()),
                }      
            DataLogic().add_data(**kwargs);
            for item in kwargs.items():
                resheaders.append(item)
            start_response(HTTPCreated, resheaders)
            return self.content
        except Exception,e:
            Log().error('PUT_OBJECT by '+req.headers.get('X-Auth-User')+': '+req.headers['domain']+'/'+str(req.headers['container'])+' '+str(e))
            start_response(HTTPInternalServerError, resheaders)
            return ''