Esempio n. 1
0
def create_follow():
    """Create follower-followee relation"""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400

    follower_id = post_data.get('follower_id')
    followee_id = post_data.get('followee_id')
    if follower_id is None or followee_id is None:
        return jsonify(response_object), 400

    if int(follower_id) == int(followee_id):
        response_object['message'] = 'You cannot follow yourself'
        return jsonify(response_object), 400

    try:
        # Send notification to followee
        try:
            response_obj = send_request('get',
                                        'users',
                                        f'users/{follower_id}',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_object['users'] = response_obj.json

            username = f'User {follower_id}'
            try:
                username = response_obj.json['data']['username']
            except:
                pass

            response_obj = send_request('post',
                                        'notification',
                                        'notifications',
                                        timeout=3,
                                        json={
                                            'content':
                                            f'{username} has followed you',
                                            'recipients': [followee_id]
                                        },
                                        auth=(g.user_id_or_token, g.password))
            response_object['notification'] = response_obj.json
        except:
            response_object['warning'] = 'failed creating a notification'

        db.session.add(
            Follower(follower_id=follower_id, followee_id=followee_id))
        db.session.commit()
        response_object['status'] = 'success'
        response_object['message'] = 'follower was successfully created'

        return jsonify(response_object), 201
    except Exception as e:
        db.session.rollback()
        # response_object["what"] = str(e)
        return jsonify(response_object), 400
Esempio n. 2
0
 def report_format_generate(self, report, format, chapters=None, filters=[], url_params={}):
   if self.token:
     token = self.token
     params = self.params
   for filter in filters:
     util.merge_params(params, filter)
   url = "%s/report/format/generate" % (self.connection_string)  
   if chapters:
     return util.send_request(url, params, {'token':token,'report':report,'format':format,'chapters':chapters})    
   else:
     return util.send_request(url, params, {'token':token,'report':report,'format':format})    
Esempio n. 3
0
def create_like():
    """Create a new like on a post"""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400

    post_id = post_data.get('post_id')
    user_id = post_data.get('user_id')

    try:
        # Send notification to creator of post
        try:
            response_obj = send_request('get',
                                        'post',
                                        f'posts/{post_id}',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_object['post'] = response_obj.json
            creator = response_obj.json['data']['creator']

            response_obj = send_request('get',
                                        'users',
                                        f'users/{user_id}',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_object['users'] = response_obj.json
            username = response_obj.json['data']['username']

            send_request('post',
                         'notification',
                         'notifications',
                         timeout=3,
                         json={
                             'content': f'{username} has liked your post',
                             'recipients': [creator]
                         },
                         auth=(g.user_id_or_token, g.password))
            response_object['notification'] = response_obj.json
        except:
            pass

        db.session.add(Like(post_id=post_id, user_id=user_id))
        db.session.commit()
        response_object['status'] = 'success'
        response_object['message'] = 'like was successfully created'
        return jsonify(response_object), 201

    except:
        db.session.rollback()
        return jsonify(response_object), 400
Esempio n. 4
0
def create_tags():
    """Create new tags on a post"""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400

    post_id = post_data.get('post_id')
    user_ids = post_data.get('user_ids')

    try:
        # Send notification to the tagged person
        try:
            response_obj = send_request('get',
                                        'post',
                                        f'posts/{post_id}',
                                        timeout=3)
            response_object['post'] = response_obj.json
            creator = response_obj.json['data']['creator']

            response_obj = send_request('get',
                                        'users',
                                        f'users/{creator}',
                                        timeout=3)
            response_object['users'] = response_obj.json
            username = response_obj.json['data']['username']

            send_request('post',
                         'notification',
                         'notifications',
                         timeout=3,
                         json={
                             'content':
                             f'{username} has tagged you in their post',
                             'recipients': user_ids
                         })
            response_object['notification'] = response_obj.json
        except:
            pass

        for user_id in user_ids:
            db.session.add(Tag(post_id=post_id, user_id=user_id))
        db.session.commit()
        response_object['status'] = 'success'
        response_object['message'] = 'tags were successfully created'
        return jsonify(response_object), 201

    except:
        db.session.rollback()
        return jsonify(response_object), 400
Esempio n. 5
0
def get_newsfeed(user_id):
    """Get the newsfeed of a user (most recent posts of the followers)"""
    response_object = {
        'status': 'fail',
        'message': 'User does not exist or has not followed anyone yet'
    }
    try:
        posts = []

        # Get all users the user follows
        response_obj = send_request('get',
                                    'follow',
                                    f'follow/followees/{user_id}',
                                    timeout=3,
                                    auth=(g.user_id_or_token, g.password))
        response_object['follow'] = response_obj.json
        if response_obj.status_code == 503:
            raise RequestException()
        elif response_obj.status_code != 200:
            raise RequestException()

        data = response_obj.json

        # Get posts of followed users + include own posts
        for followedUser in data['followees'] + [user_id]:
            response_obj = send_request('get',
                                        'post',
                                        f'posts/user/{followedUser}',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_object['post'] = response_obj.json
            if response_obj.status_code == 503:
                raise RequestException()
            elif response_obj.status_code != 200:
                raise RequestException()

            data = response_obj.json
            posts += data['data']['posts']

        # Sort posts (newest first)
        posts.sort(
            reverse=True,
            key=lambda x: time.mktime(
                time.strptime(x['created_date'], '%a, %d %b %Y %H:%M:%S %Z')))

        response_object = {'status': 'success', 'data': {'posts': posts}}
        return jsonify(response_object), 200
    except:
        return jsonify(response_object), 404
Esempio n. 6
0
def send_notification_to_all(message):
    """Send notification to all users that a service is temporary down"""

    response_obj = send_request('get', 'users', 'users', timeout=3)
    all_users = [user['id'] for user in response_obj.json['data']['users']]

    send_request('post',
                 'notification',
                 'notifications',
                 timeout=3,
                 json={
                     'content': message,
                     'recipients': all_users
                 },
                 auth=('2', 'admin'))
Esempio n. 7
0
 def login(self, connection_string, username, password, url_params={}):
   self.connection_string = connection_string
   params = util.merge_params(self.params, url_params)
   url = "%s/login" % (connection_string)
   response = util.send_request(url, params, {'login':username, 'password':password})
   self.token = response['token']
   return response
Esempio n. 8
0
def poll_services():
    """Poll each service by pinging them"""

    for service, path in SERVICES:
        try:
            response_object = send_request('get',
                                           service,
                                           f'{path}',
                                           timeout=3)
            if response_object.json['status'] == "fail":
                if not service_status[service]:
                    service_status[service] = True  # status = down
                    send_notification_to_all(
                        f'{service} service is temporary down. Please wait while we\'ll try to fix this.'
                    )
            else:
                if service_status[service]:
                    service_status[service] = False  # status = up
                    send_notification_to_all(
                        f'{service} service is back up. Thank you for your patience.'
                    )
        except:
            if not service_status[service]:
                service_status[service] = True  # status = down
                send_notification_to_all(
                    f'{service} service is temporary down. Please wait while we\'ll try to fix this.'
                )
Esempio n. 9
0
    def __init__(self, endpoint):

        self.endpoint = endpoint
        self.file_path = RAW_DATA_PATH + self.endpoint + ".json"
        self.raw_subtree = {key: [] for key in RAW_CATEGORIES}

        self.exists = False
        if not file_exists(self.file_path):
            self.html = send_request(BASE_URL + self.endpoint, HEADERS)
            self.subtree = {}
        else:
            print(self.endpoint, "exists")
            self.exists = True
            self.subtree = read_json(self.file_path)
Esempio n. 10
0
def login():
    """Given email & pw, get token"""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'User does not exist'}
    response_code = 400
    if not post_data:
        return jsonify(response_object), 400
    email = post_data.get('email')
    password = post_data.get('password')
    if not email or not password:
        return jsonify(response_object), 400
    try:
        response_code = 404
        user = User.query.filter_by(email=email).first()
        if not user:
            # response_object["sdfqsdf"] = "qsdfqsdf"
            return jsonify(response_object), 404
        else:
            if not user.active:
                response_object['message'] = 'You are blocked.'
                response_code = 401
                raise RequestException()
            response_obj = send_request('get',
                                        'authentication',
                                        'token',
                                        timeout=3,
                                        auth=(user.id, password))
            response_code = response_obj.status_code
            if response_obj.status_code == 503:
                response_object = response_obj.json
                raise RequestException()
            elif response_obj.status_code == 401:
                response_object['message'] = "Wrong credentials."
                raise RequestException()
            elif response_obj.status_code != 200:
                raise RequestException()

            response_object = response_obj.json

            try:
                response_object["is_admin"] = is_admin(user.id)
            except:
                response_object["is_admin"] = False

            response_object["user_id"] = user.id
            return jsonify(response_object), 200
    except (ValueError, RequestException) as e:
        db.session.rollback()
        return jsonify(response_object), response_code
Esempio n. 11
0
def add_user():
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    response_code = 400
    if not post_data:
        return jsonify(response_object), 400
    username = post_data.get('username')
    password = post_data.get('password')
    email = post_data.get('email')
    try:
        user = User.query.filter_by(email=email).first()
        if not user:
            user = User(username=username, email=email)
            db.session.add(user)
            db.session.flush()
            db.session.refresh(user)

            response_obj = send_request('post',
                                        'authentication',
                                        'passwords',
                                        timeout=3,
                                        json={
                                            'user_id': user.id,
                                            'password': password
                                        })
            response_code = response_obj.status_code
            if response_obj.status_code == 503:
                response_object = response_obj.json
                raise RequestException()
            elif response_obj.status_code != 201:
                raise RequestException()

            db.session.commit()
            response_object['status'] = 'success'
            response_object['message'] = f'{email} was added!'
            response_object['user_id'] = user.id
            return jsonify(response_object), 201
        else:
            response_object['message'] = 'Sorry. That email already exists.'
            return jsonify(response_object), 400
    except (exc.IntegrityError, RequestException) as e:
        db.session.rollback()
        return jsonify(response_object), response_code
Esempio n. 12
0
def unblock_user(user_id):
    """Blocks a user"""
    response_object = {'status': 'fail', 'message': 'User does not exist'}
    response_code = 404
    try:
        if not is_admin(g.user_id):
            response_object['message'] = 'User is not admin.'
            return jsonify(response_object), 401
    except KeyError:
        response_object[
            'message'] = 'Could not reach authentication service to check if user is admin.'
        return jsonify(response_object), 401

    try:
        user = User.query.filter_by(id=int(user_id)).first()

        if not user:
            return jsonify(response_object), 404
        else:
            response_obj = send_request('PUT',
                                        'authentication',
                                        f'passwords/{user_id}/block',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_code = response_obj.status_code
            if response_obj.status_code == 503:
                response_object = response_obj.json
                raise RequestException()
            elif response_obj.status_code != 200:
                raise RequestException()

            user.active = True
            db.session.commit()
            response_object['status'] = 'success'
            response_object['message'] = 'user was successfully unblocked'
            return jsonify(response_object), 200

    except ValueError:
        return jsonify(response_object), 404
    except RequestException as e:
        return jsonify(response_object), response_code
Esempio n. 13
0
#!/usr/bin/env python
import json
import util

peers = util.get_peers()
results = util.send_request(peers, 'blockchain.estimatefee', [2])
print(json.dumps(results, indent=4))
Esempio n. 14
0
def ping3():
    response_obj = send_request('get', 'authentication', 'ping', timeout=3)
    return jsonify(response_obj.json), response_obj.status_code
Esempio n. 15
0
 def launch_adhoc_scan(self, policy, plugin_id=None, url_params={}):
   if self.token:
     token = self.token
   params = util.merge_params(self.params, url_params)
   url = "%s/scan/new" % (self.connection_string)
   return util.send_request(url, params, {'scan_name':'adhoc_'+random.randint(1,65535),'token':token,'template':template}) 
Esempio n. 16
0
 def report_details(self, report, host, url_params={}):
   if self.token:
     token = self.token
   params = util.merge_params(self.params, url_params)
   url = "%s/report/details" % (self.connection_string)
   return util.send_request(url, params, {'token':token,'report':report,'host':host})    
Esempio n. 17
0
 def report_format_status(self, file, url_params={}):
   if self.token:
     token = self.token
   params =  util.merge_params(self.params, url_params)
   url = "%s/report/format/status" % (self.connection_string)      
   return util.send_request(url, params, {'token':token,'file':file})    
Esempio n. 18
0
#!/usr/bin/env python3

import util

from electrumsv.network import filter_protocol
from electrumsv.blockchain import hash_header

peers = util.get_peers()
peers = filter_protocol(peers, 's')

results = util.send_request(peers, 'blockchain.headers.subscribe', [])

for n, v in sorted(results.items(), key=lambda x: x[1].get('block_height')):
    print("%60s" % n, v.get('block_height'), hash_header(v))
Esempio n. 19
0
 def policy_list(self, url_params={}):
   if self.token:
     token = self.token
   params = util.merge_params(self.params, url_params)
   url = "%s/policy/list/policies" % (self.connection_string)
   return util.send_request(url, params, {'token':token}) 
Esempio n. 20
0
 def launch_scan_template(self, template,url_params={}):
   if self.token:
     token = self.token
   params = util.merge_params(self.params, url_params)
   url = "%s/scan/template/launch" % (self.connection_string)
   return util.send_request(url, params, {'token':token,'template':template}) 
Esempio n. 21
0
 def scan_list(self, url_params={}):
   if self.token:
     token = self.token
   params = util.merge_params(self.params, url_params)
   url = "%s/scan/list2" % (self.connection_string)
   return util.send_request(url, params, {'token':token}) 
Esempio n. 22
0
    def __init__(self, endpoint, file_name):

        self.html = send_request(BASE_URL + endpoint, HEADERS)
        self.file_name = file_name
        self.genre_list = set()
Esempio n. 23
0
def create_post():
    """Create a new post"""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400

    creator = post_data.get('creator')
    content = post_data.get('content')
    tags = post_data.get('tags')

    try:
        # Check for bad words
        response_obj = send_request('post',
                                    'anti-cyberbullying',
                                    'anti_cyberbullying/contains_bad_word',
                                    timeout=3,
                                    json={'sentence': str(content)},
                                    auth=(g.user_id_or_token, g.password))
        response_object['anti-cyberbullying'] = response_obj.json
        if response_obj.status_code == 201:
            result = response_obj.json
            if result['status'] == "success" and result[
                    'result']:  # contains bad word
                response_object[
                    'message'] = f'Post contains bad word: {result["bad_word"]}'
                return jsonify(response_object), 201

        # Update user categories (for ads)
        response_obj = send_request('post',
                                    'ad',
                                    f'ads/user/{creator}',
                                    timeout=3,
                                    json={'sentence': str(content)},
                                    auth=(g.user_id_or_token, g.password))
        response_object['ad'] = response_obj.json

        # Create post
        post = Post(creator=creator, content=content)
        db.session.add(post)
        db.session.commit()

        if tags:
            # Get user id's by username
            user_tags_ids = []
            for tag in tags:
                response_obj = send_request('get',
                                            'users',
                                            f'users/name/{tag}',
                                            timeout=3,
                                            auth=(g.user_id_or_token,
                                                  g.password))
                if response_obj.status_code != 200:
                    continue
                result = response_obj.json
                if result['status'] == "success":
                    user_tags_ids.append(result['data']['id'])

            # Add user tags
            data = {'post_id': post.id, 'user_ids': user_tags_ids}
            response_obj = send_request('post',
                                        'tag',
                                        'tags',
                                        timeout=3,
                                        json=data,
                                        auth=(g.user_id_or_token, g.password))
            response_object['tag'] = response_obj.json

        response_object['status'] = 'success'
        response_object['message'] = 'Post was successfully created'
        return jsonify(response_object), 201

    except:
        db.session.rollback()
        return jsonify(response_object), 400
Esempio n. 24
0
#!/usr/bin/env python3
import util, sys
try:
    tx = sys.argv[1]
except IndexError:
    print("usage: txradar txid")
    sys.exit(1)

peers = util.get_peers()
results = util.send_request(peers, 'blockchain.transaction.get', [tx])

r1 = []
r2 = []

for k, v in results.items():
    (r1 if v else r2).append(k)

print("Received %d answers" % len(results))
print("Propagation rate: %.1f percent" % (len(r1) * 100. /
                                          (len(r1) + len(r2))))
Esempio n. 25
0
def create_comment():
    """Create a new comment on a post"""
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400

    post_id = post_data.get('post_id')
    user_id = post_data.get('user_id')
    content = post_data.get('content')

    try:
        # Check for bad words
        response_obj = send_request('post',
                                    'anti-cyberbullying',
                                    'anti_cyberbullying/contains_bad_word',
                                    timeout=3,
                                    json={'sentence': str(content)},
                                    auth=(g.user_id_or_token, g.password))
        response_object['anti-cyberbullying'] = response_obj.json
        if response_obj.status_code == 201:
            result = response_obj.json
            if result['status'] == "success" and result[
                    'result']:  # contains bad word
                response_object[
                    'message'] = f'Comment contains bad word: {result["bad_word"]}'
                return jsonify(response_object), 201

        # Update user categories (for ads)
        response_obj = send_request('post',
                                    'ad',
                                    f'ads/user/{user_id}',
                                    timeout=3,
                                    json={'sentence': str(content)},
                                    auth=(g.user_id_or_token, g.password))
        response_object['ad'] = response_obj.json

        # Send notification to creator of post
        try:
            response_obj = send_request('get',
                                        'post',
                                        f'posts/{post_id}',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_object['post'] = response_obj.json
            creator = response_obj.json['data']['creator']

            response_obj = send_request('get',
                                        'users',
                                        f'users/{user_id}',
                                        timeout=3,
                                        auth=(g.user_id_or_token, g.password))
            response_object['users'] = response_obj.json
            username = response_obj.json['data']['username']

            send_request('post',
                         'notification',
                         'notifications',
                         timeout=3,
                         json={
                             'content':
                             f'{username} has commented on your post',
                             'recipients': [creator]
                         },
                         auth=(g.user_id_or_token, g.password))
            response_object['notification'] = response_obj.json
        except:
            pass

        db.session.add(
            Comment(post_id=post_id, creator=user_id, content=content))
        db.session.commit()
        response_object['status'] = 'success'
        response_object['message'] = 'comment was successfully created'
        return jsonify(response_object), 201

    except:
        db.session.rollback()
        return jsonify(response_object), 400