Beispiel #1
0
def join_network():
    body = request.get_json(force=True)
    if body is None:
        raise BadRequest('No body is provided.')
    if 'name' not in body or 'address' not in body:
        raise BadRequest(
            'Required fields for joining a network are: name, address '
            'of existing node')

    node = registry.Node(body['name'], body['address'], None)
    try:
        network_nodes = node.client.register(
            {
                'name': current_app.config['ST_OWN_NAME'],
                'address': current_app.config['ST_OWN_ADDRESS']
            },
            force_update=True)

    # this is coming from the client so all possible errors are server errors,
    # no need for fine-tuned exception handling
    except Exception:
        raise BadGateway("The node you provided is unreachable.")
    registry.delete_all()
    [
        registry.add(node['name'], node['address']) for node in network_nodes
        if node['name'] != current_app.config['ST_OWN_NAME']
    ]

    return jsonify('Node successfully joined network.')
Beispiel #2
0
def save_tweet():
    if not request.data:
        raise BadRequest("Data not sent")
    request_data = json.loads(request.data)
    if 'tweet' in request_data:
        Storage.save_tweet(request_data["tweet"])
        return "Tweet saved"
    else:
        raise BadRequest("Missing tweet content")
Beispiel #3
0
def delete_tweet():
    if not request.data:
        raise BadRequest("Data not sent")
    request_data = json.loads(request.data)
    if 'id' in request_data:
        if Storage.delete_tweet((int)(request_data["id"])):
            return "Tweet deleted", 204
        else:
            raise NotFound("Tweet not found")
    else:
        raise BadRequest("Missing tweet content")
Beispiel #4
0
def join_network():
    if not request.data:
        raise BadRequest("Data not sent")
    request_data = json.loads(request.data)
    if request_data['name'] and request_data['url']:
        print("Joining network through node '" + request_data['name'] +
              "' at " + request_data['url'])
        Nodes.register_node(request_data['name'], request_data['url'])
        scan_network()
        return "Joined"
    else:
        raise BadRequest("Missing parameters")
Beispiel #5
0
def register_server():
    body = request.get_json(force=True)
    if body is None:
        raise BadRequest('No body is provided.')
    if 'name' not in body or 'address' not in body:
        raise BadRequest('Required fields for registration are: name, address')
    force_update = ensure_bool(request.args.get('force', None))
    registry.add(body['name'], body['address'], force_update)
    all_nodes = registry.get_all()
    all_nodes.append(
        registry.Node(current_app.config['ST_OWN_NAME'],
                      current_app.config['ST_OWN_ADDRESS'], datetime.now()))
    return jsonify([node.to_dict() for node in all_nodes]), 201
Beispiel #6
0
def register_node():
    if not request.data:
        raise BadRequest("Data not sent")
    request_data = json.loads(request.data)
    if 'name' in request_data and 'url' in request_data:
        if request_data['url'] != self_node_address and request_data[
                'name'] != self_node_name:
            print("New node '" + request_data['name'] + "' at " +
                  request_data['url'])
            Nodes.register_node(request_data['name'], request_data['url'])
            scan_network()
        return jsonify(Nodes.get_all())
    else:
        raise BadRequest("Missing parameters")
Beispiel #7
0
def search():
    # TODO: add created_from, created_to
    if request.args.get('content'):
        if request.args.get('all') and request.args.get('all') == 'true':
            return jsonify(Storage.search(request.args.get('content'), True))
        return jsonify(Storage.search(request.args.get('content')))
    raise BadRequest("Missing params")
Beispiel #8
0
def retweet():
    """
    Creates retweet on this server that references tweet on provided server.
    """
    body = request.get_json(force=True)
    if 'server' not in body or 'id' not in body:
        raise BadRequest('Missing wither "server" or "id" from body.')
    return jsonify(tweet.retweet(body['server'], body['id']).to_dict())
Beispiel #9
0
def check_length(tweet):
    """
    Verifies if provided tweet content is less then 140 characters.

    :param str tweet: Tweet content to check.
    :raises BadRequest: If tweet content is longer then 140 characters.
    """
    if len(tweet) > 140:
        raise BadRequest('Tweet length exceeds 140 characters.')
Beispiel #10
0
def create_tweet():
    """
    Creates new tweet and returns its JSON representation.
    """
    body = request.get_json(force=True)
    if 'tweet' not in body:
        raise BadRequest('Invalid body: no "tweet" key in body.')
    content = body['tweet']
    new_tweet = tweet.create(content)
    return jsonify(new_tweet.to_dict()), 201
Beispiel #11
0
 def register(self, name, address):
     """
     Adds server to servers dict
     :param name: Server name.
     :param address: Server address.
     :return: Dict of registered servers.
     """
     if self.servers.get(name):
         raise BadRequest('Username already exists')
     else:
         self.servers[name] = address
         return json.dumps(self.servers)
Beispiel #12
0
def ensure_dt(val):
    """
    Converts query argument to datetime object.

    If None is provided, it will be returned. Otherwise, conversion to in is
    attempted and that int is treated as unix timestamp, which is converted
    to datetime.datetime.

    :param val: Value to convert to datetime.
    :return: datetime object from provided value.
    :raises BadRequest: If provided value could not be converted to datetime.
    """
    if val is None:
        return None
    try:
        int_val = int(val)
    except ValueError:
        raise BadRequest(f'Expected integer, got: {val}')

    try:
        dt_val = datetime.fromtimestamp(int_val)
        return dt_val
    except Exception:
        raise BadRequest(f'Unable to convert {int_val} to datetime.')
Beispiel #13
0
def modify(tweet_id):
    body = request.get_json(force=True)
    if 'tweet' not in body:
        raise BadRequest('Invalid body: no "tweet" key in body.')
    content = body['tweet']
    return jsonify(tweet.modify(tweet_id, content).to_dict())