Beispiel #1
0
def add():
    """ The form for user-submission """
    if request.method == 'GET':
        tags = get_most_popular_tags()[:10]
        return render_template('edit_entry.html',
                               entry=post_from_request(),
                               popular_tags=tags,
                               type="add")

    elif request.method == 'POST':  # if we're adding a new post

        if not session.get('logged_in'):
            abort(401)

        if "Submit" in request.form:
            thread = threading.Thread(
                target=add_entry,
                args=(request))  # we spin off a thread to create
            # album processing can take time: we want to spin it off to avoid worker timeouts.
            thread.start()
            location = '/'
            location = add_entry(request)

        if "Save" in request.form:  # if we're simply saving the post as a draft

            data = post_from_request(request)
            location = create_json_entry(data, g=g, draft=True)

        return redirect(location)  # send the user to the newly created post
Beispiel #2
0
def bridgy_facebook(location):
    """send a facebook mention to brid.gy"""
    # send the mention
    r = send_mention(
        'http://' + DOMAIN_NAME + location,
        'https://brid.gy/publish/facebook',
        endpoint='https://brid.gy/publish/webmention'
    )
    # get the response from the send
    syndication = r.json()
    data = file_parser_json('data/' + location.split('/e/')[1]+".json", md=False)
    app.logger.info(syndication)
    if data['syndication']:
        data['syndication'].append(syndication['url'])
    else:
        data['syndication'] = [syndication['url']]
    data['facebook'] = {'url': syndication['url']}
    create_json_entry(data, g=None,update=True)
Beispiel #3
0
def add():
    """ The form for user-submission """
    if request.method == 'GET':
        return render_template('add.html')

    elif request.method == 'POST':                  # if we're adding a new post
        if not session.get('logged_in'):
            abort(401)
        app.logger.info(request.form)

        data = post_from_request(request)

        if "Submit" in request.form:                    # we're publishing it now; give it the present time
            data['published'] = datetime.now()

            if data['location'] is not None and data['location'].startswith("geo:"):
                if data['location'].startswith("geo:"):
                    app.logger.info(data['location'])
                    (place_name, geo_id) = resolve_placename(data['location'])
                    data['location_name'] = place_name
                    data['location_id'] = geo_id

            location = create_json_entry(data, g=g)

            if data['in_reply_to']:
                send_mention('http://' + DOMAIN_NAME +location, data['in_reply_to'])

            app.logger.info("posted at {0}".format(location))
            if request.form.get('twitter'):
                t = Timer(30, bridgy_twitter, [location])
                t.start()

            if request.form.get('facebook'):
                t = Timer(30, bridgy_facebook, [location])
                t.start()

        if "Save" in request.form:              # if we're simply saving the post as a draft
            location = create_json_entry(data, g=g, draft=True)

        return redirect(location)
    else:
        return redirect('/404'), 404
Beispiel #4
0
def bridgy_twitter(location):
    """send a twitter mention to brid.gy"""
    location = 'http://' + DOMAIN_NAME + location
    app.logger.info("bridgy sent to {0}".format(location))
    r = send_mention(
        location,
        'https://brid.gy/publish/twitter',
        endpoint='https://brid.gy/publish/webmention'
    )
    syndication = r.json()
    app.logger.info(syndication)
    app.logger.info("recieved {0} {1}".format(syndication['url'], syndication['id']))
    data = file_parser_json('data/' + location.split('/e/')[1]+".json", md=False)
    if data['syndication']:
        data['syndication'].append(syndication['url'])
    else:
        data['syndication'] = [syndication['url']]
    data['twitter'] = {'url': syndication['url'],
                       'id': syndication['id']}
    create_json_entry(data, g=None, update=True)
Beispiel #5
0
def add_entry(creation_request, draft=False):

    data = post_from_request(creation_request)
    if data['published'] is None:  # we're publishing it now; give it the present time
        data['published'] = datetime.now()
    data['content'] = run(
        data['content'],
        date=data['published'])  # find all images in albums and move them

    if data['location'] is not None and data['location'].startswith(
            "geo:"):  # if we were given a geotag
        (place_name,
         geo_id) = resolve_placename(data['location'])  # get the placename
        data['location_name'] = place_name
        data['location_id'] = geo_id
        # todo: you'll be left with a rogue 'location' in the dict... should clean that...

    location = create_json_entry(data, g=g)  # create the entry
    syndicate_from_form(creation_request, location, data['in_reply_to'])
    return location
Beispiel #6
0
def show_draft(name):
    if request.method == 'GET':
        draft_location = 'drafts/' + name + ".json"
        entry = file_parser_json(draft_location, md=False)
        if entry['category']:
            entry['category'] = ', '.join(entry['category'])
        return render_template('edit_draft.html', entry=entry)

    if request.method == 'POST':
        if not session.get('logged_in'):
            abort(401)
        data = post_from_request(request)

        if "Save" in request.form:                          # if we're updating a draft
            file_name = "drafts/{0}".format(name)
            entry = file_parser_json(file_name+".json")
            location = update_json_entry(data, entry, g=g, draft=True)
            return redirect("/drafts")

        if "Submit" in request.form:                        # if we're publishing it now
            data['published'] = datetime.now()

            location = create_json_entry(data, g=g)
            if data['in_reply_to']:
                send_mention('http://' + DOMAIN_NAME +location, data['in_reply_to'])

            if request.form.get('twitter'):
                t = Timer(30, bridgy_twitter, [location])
                t.start()

            if request.form.get('facebook'):
                t = Timer(30, bridgy_facebook, [location])
                t.start()

            if os.path.isfile("drafts/"+name+".json"):           # this won't always be the slug generated
                os.remove("drafts/"+name+".json")

            return redirect(location)
Beispiel #7
0
def handle_micropub():
    app.logger.info('handleMicroPub [%s]' % request.method)
    if request.method == 'POST':                                                    # if post, authorise and create
        access_token = request.headers.get('Authorization')                         # get the token and report it
        app.logger.info('token [%s]' % access_token)
        if access_token:                                                            # if the token is not none...
            access_token = access_token.replace('Bearer ', '')
            app.logger.info('acccess [%s]' % request)
            if checkAccessToken(access_token, request.form.get("client_id.data")):  # if the token is valid ...
                app.logger.info('authed')
                data = {}

                for key in (
                        'h', 'name', 'summary', 'content', 'published', 'updated', 'category',
                        'slug', 'location', 'in_reply_to', 'repost-of', 'syndication', 'syndicate-to[]'):
                    data[key] = request.form.get(key)

                if data['syndication']:
                    data['syndication'] += ","                  #TODO: add twitter keywords

                if not data['published']:                       # if we don't have a timestamp, make one now
                    data['published'] = datetime.today()
                else:
                    data['published'] = parse(data['published'])

                for key, name in [('photo','image'),('audio','audio'),('video','video')]:
                    try:
                        if request.files.get(key):
                            img = request.files.get(key).read()
                            data[key] = img
                            data['category'] += ','+name                # we've added an image, so append it
                    except KeyError:
                        pass

                try:
                    if data['location']:
                        app.logger.info(data['location'])
                        (place_name, geo_id) = resolve_placename(data['location'])
                        data['location_name'] = place_name
                        data['location_id'] = geo_id
                except KeyError:
                    pass
                location = create_json_entry(data, g=g)
                
                # regardless of whether or not syndication is called for, if there's a photo, send it to FB and twitter
                try:
                    if request.form.get('twitter') or data['photo']:
                        t = Timer(30, bridgy_twitter, [location])
                        t.start()
                except KeyError:
                    pass
                try:
                    if request.form.get('facebook') or data['photo']:
                        t = Timer(30, bridgy_facebook, [location])
                        t.start()
                except KeyError:
                    pass

                resp = Response(status="created", headers={'Location': 'http://' + DOMAIN_NAME + location})
                resp.status_code = 201
                return resp
            else:
                return 'unauthorized', 403
        else:
            return 'unauthorized', 401

    elif request.method == 'GET':
        qs = request.query_string
        if request.args.get('q') == 'syndicate-to':
            syndicate_to = [
                'twitter.com/',
                'tumblr.com/',
                'facebook.com/'
            ]

            r = ''
            while len(syndicate_to) > 1:
                r += 'syndicate-to[]=' + syndicate_to.pop() + '&'
            r += 'syndicate-to[]=' + syndicate_to.pop()
            resp = Response(content_type='application/x-www-form-urlencoded', response=r)
            return resp
        return 'not implemented', 501
Beispiel #8
0
def handle_micropub():
    app.logger.info('handleMicroPub [%s]' % request.method)
    if request.method == 'POST':  # if post, authorise and create
        access_token = request.headers.get(
            'Authorization')  # get the token and report it
        app.logger.info('token [%s]' % access_token)
        if access_token:  # if the token is not none...
            access_token = access_token.replace('Bearer ', '')
            app.logger.info('acccess [%s]' % request)
            if checkAccessToken(access_token, request.form.get(
                    "client_id.data")):  # if the token is valid ...
                app.logger.info('authed')
                app.logger.info(request.data)
                app.logger.info(request.form.keys())
                app.logger.info(request.files)
                data = {
                    'h': None,
                    'title': None,
                    'summary': None,
                    'content': None,
                    'published': None,
                    'updated': None,
                    'category': None,
                    'slug': None,
                    'location': None,
                    'location_name': None,
                    'location_id': None,
                    'in_reply_to': None,
                    'repost-of': None,
                    'syndication': None,
                    'photo': None
                }

                for key in ('name', 'summary', 'content', 'published',
                            'updated', 'category', 'slug', 'location',
                            'place_name', 'in_reply_to', 'repost-of',
                            'syndication', 'syndicate-to[]'):
                    try:
                        data[key] = request.form.get(key)
                    except KeyError:
                        pass

                cat = request.form.get('category[]')
                if cat:
                    app.logger.info(request.form.get('category[]'))
                    data['category'] = cat

                if type(data['category']) is unicode:
                    data['category'] = [
                        i.strip() for i in data['category'].lower().split(",")
                    ]
                elif type(data['category']) is list:
                    data['category'] = data['category']
                elif data['category'] is None:
                    data['category'] = []

                if not data[
                        'published']:  # if we don't have a timestamp, make one now
                    data['published'] = datetime.today()
                else:
                    data['published'] = parse(data['published'])

                for key, name in [('photo', 'image'), ('audio', 'audio'),
                                  ('video', 'video')]:
                    try:
                        if request.files.get(key):
                            img = request.files.get(key)
                            data[key] = img
                            data['category'].append(
                                name)  # we've added an image, so append it
                    except KeyError:
                        pass

                if data['location'] is not None and data[
                        'location'].startswith("geo:"):
                    if data['place_name']:
                        data['location_name'] = data['place_name']
                    elif data['location'].startswith("geo:"):
                        (place_name,
                         geo_id) = resolve_placename(data['location'])
                        data['location_name'] = place_name
                        data['location_id'] = geo_id

                location = create_json_entry(data, g=g)

                if data['in_reply_to']:
                    send_mention('https://' + DOMAIN_NAME + '/e/' + location,
                                 data['in_reply_to'])

                # regardless of whether or not syndication is called for, if there's a photo, send it to FB and twitter
                try:
                    if request.form.get('twitter') or data['photo']:
                        t = Timer(30, bridgy_twitter, [location])
                        t.start()
                except KeyError:
                    pass

                resp = Response(
                    status="created",
                    headers={'Location': 'http://' + DOMAIN_NAME + location})
                resp.status_code = 201
                return resp
            else:
                resp = Response(status='unauthorized')
                resp.status_code = 401
                return resp
        else:
            resp = Response(status='unauthorized')
            resp.status_code = 401

    elif request.method == 'GET':
        qs = request.query_string
        if request.args.get('q') == 'syndicate-to':
            syndicate_to = ['twitter.com/', 'tumblr.com/', 'facebook.com/']

            r = ''
            while len(syndicate_to) > 1:
                r += 'syndicate-to[]=' + syndicate_to.pop() + '&'
            r += 'syndicate-to[]=' + syndicate_to.pop()
            resp = Response(content_type='application/x-www-form-urlencoded',
                            response=r)
            return resp
        resp = Response(status='not implemented')
        resp.status_code = 501
        return resp