Esempio n. 1
0
def create_facebook_event(event,
                          request,
                          facebook_owner_id,
                          facebook_owner_type='user'):
    graph = get_persistent_graph(request)

    if not graph:
        raise Exception('Error: facebook authentication is required')

    parser = HTMLParser()
    description = strip_tags(parser.unescape(event.description))

    googlemap_link = 'http://maps.google.com/?ie=UTF8&hq=&q=%s,%s&ll=%s,%s&z=13' % (
        event.location.y, event.location.x, event.location.y, event.location.x)
    description = '%s\r\n\nLocation: %s\r\n\nPrice: %s' % (
        description, googlemap_link, event.price)

    if facebook_owner_type == 'user' and event.tickets:
        description = '%s\r\n\nTickets: %s' % (description, event.tickets)

    location = event.venue.name
    if event.venue.street:
        location += ', %s' % event.venue.street

    location += ', %s' % event.venue.city.name_std
    dates = Event.events.annotate(start_time=Min('single_events__start_time'))\
                 .annotate(end_time=Max('single_events__end_time')).get(pk=event.id)

    if dates.start_time >= dates.end_time:
        dates.end_time += datetime.timedelta(days=1)

    common_params = {
        'name': shorten_string(event.name, 72),  # max length is 75 (with ...)
        'description': unicode(description).encode('utf-8'),
        'location': location
    }

    if facebook_owner_type == 'page' and event.tickets:
        validate = URLValidator()
        try:
            validate(event.tickets)
            common_params['ticket_uri'] = event.tickets
        except ValidationError:
            pass

    if event.is_multiday():
        single_events = list(SingleEvent.homepage_events.filter(event=event))
    else:
        single_events = list(SingleEvent.future_events.filter(event=event))

    event_url = '%s/events' % facebook_owner_id
    event_images = list(event.sorted_images)
    have_images = False
    if len(event_images) > 0:
        event_image = os.path.abspath(
            os.path.join(settings.MEDIA_ROOT, event_images[0].picture.path))
        have_images = True

    event_groups, event_group = [], []
    index = 0
    for single_event in single_events:
        event_group.append(single_event)
        index += 1
        if index == 10:
            event_groups.append(event_group)
            index, event_group = 0, []

    if index != 0:
        event_groups.append(event_group)

    facebook_event_ids, posted_single_events = [], []
    for event_group in event_groups:
        batch, attached_images = [], {}
        for single_event in event_group:
            if not single_event.facebook_event:
                posted_single_events.append(single_event)
                params = common_params.copy()
                params.update({
                    'start_time':
                    single_event.start_time.strftime('%Y-%m-%dT%H:%M:%S-0600'),
                    'end_time':
                    single_event.end_time.strftime('%Y-%m-%dT%H:%M:%S-0600'),
                })

                operation_name = 'create-event-%s' % single_event.id

                batch.append({
                    'method': 'POST',
                    'relative_url': event_url,
                    'body': urllib.urlencode(params),
                    'name': operation_name,
                    'omit_response_on_success': False
                })

                if have_images:
                    picture_url = '{result=%s:$.id}/picture' % operation_name
                    image_name = 'source%s' % single_event.id

                    batch.append({
                        'method': 'POST',
                        'relative_url': picture_url,
                        'attached_files': image_name
                    })

                    attached_images[image_name] = open(event_image)

        if posted_single_events:
            values = {
                'access_token': graph.access_token,
                'batch': json.dumps(batch)
            }

            if have_images:
                values.update(attached_images)

            response = _send_multipart_data(graph.api_url, values)
            for item in response:
                data = json.loads(item['body'])
                if type(data) == dict and 'id' in data:
                    facebook_event_ids.append(data['id'])

    if not posted_single_events:
        raise Exception('Error: no events for posting')

    result = {}
    for i in range(0, len(posted_single_events)):
        attach_facebook_event(int(facebook_event_ids[i]),
                              posted_single_events[i])
        result[posted_single_events[i].id] = facebook_event_ids[i]

    if event.is_multiday():
        single_event = SingleEvent.objects.filter(event=event,
                                                  is_occurrence=False)[0]
        single_event.facebook_event = posted_single_events[0].facebook_event
        single_event.save()

    return result
Esempio n. 2
0
def create_facebook_event(event, request, facebook_owner_id, facebook_owner_type='user'):
    graph = get_persistent_graph(request)

    if not graph:
        raise Exception('Error: facebook authentication is required')

    parser = HTMLParser()
    description = strip_tags(parser.unescape(event.description))

    googlemap_link = 'http://maps.google.com/?ie=UTF8&hq=&q=%s,%s&ll=%s,%s&z=13' % (event.location.y, event.location.x,
                                                                                    event.location.y, event.location.x)
    description = '%s\r\n\nLocation: %s\r\n\nPrice: %s' % (description, googlemap_link, event.price)

    if facebook_owner_type == 'user' and event.tickets:
        description = '%s\r\n\nTickets: %s' % (description, event.tickets)

    location = event.venue.name
    if event.venue.street:
        location += ', %s' % event.venue.street

    location += ', %s' % event.venue.city.name_std
    dates = Event.events.annotate(start_time=Min('single_events__start_time'))\
                 .annotate(end_time=Max('single_events__end_time')).get(pk=event.id)

    if dates.start_time >= dates.end_time:
        dates.end_time += datetime.timedelta(days=1)

    common_params = {
        'name': shorten_string(event.name, 72), # max length is 75 (with ...)
        'description': unicode(description).encode('utf-8'),
        'location': location
    }

    if facebook_owner_type == 'page' and event.tickets:
        validate = URLValidator()
        try:
            validate(event.tickets)
            common_params['ticket_uri'] = event.tickets
        except ValidationError:
            pass

    if event.is_multiday():
        single_events = list(SingleEvent.homepage_events.filter(event=event))
    else:
        single_events = list(SingleEvent.future_events.filter(event=event))

    event_url = '%s/events' % facebook_owner_id
    event_images = list(event.sorted_images)
    have_images = False
    if len(event_images) > 0:
        event_image = os.path.abspath(os.path.join(settings.MEDIA_ROOT, event_images[0].picture.path))
        have_images = True

    event_groups, event_group = [], []
    index = 0
    for single_event in single_events:
        event_group.append(single_event)
        index += 1
        if index == 10:
            event_groups.append(event_group)
            index, event_group = 0, []

    if index != 0:
        event_groups.append(event_group)

    facebook_event_ids, posted_single_events = [], []
    for event_group in event_groups:
        batch, attached_images = [], {}
        for single_event in event_group:
            if not single_event.facebook_event:
                posted_single_events.append(single_event)
                params = common_params.copy()
                params.update({
                    'start_time': single_event.start_time.strftime('%Y-%m-%dT%H:%M:%S-0600'),
                    'end_time': single_event.end_time.strftime('%Y-%m-%dT%H:%M:%S-0600'),
                })

                operation_name = 'create-event-%s' % single_event.id

                batch.append({
                    'method': 'POST',
                    'relative_url': event_url,
                    'body': urllib.urlencode(params),
                    'name': operation_name,
                    'omit_response_on_success': False
                })

                if have_images:
                    picture_url = '{result=%s:$.id}/picture' % operation_name
                    image_name = 'source%s' % single_event.id

                    batch.append({
                        'method': 'POST',
                        'relative_url': picture_url,
                        'attached_files': image_name
                    })

                    attached_images[image_name] = open(event_image)

        if posted_single_events:
            values = {
                'access_token': graph.access_token,
                'batch': json.dumps(batch)
            }

            if have_images:
                values.update(attached_images)

            response = _send_multipart_data(graph.api_url, values)
            for item in response:
                data = json.loads(item['body'])
                if type(data) == dict and 'id' in data:
                    facebook_event_ids.append(data['id'])

    if not posted_single_events:
        raise Exception('Error: no events for posting')

    result = {}
    for i in range(0, len(posted_single_events)):
        attach_facebook_event(int(facebook_event_ids[i]), posted_single_events[i])
        result[posted_single_events[i].id] = facebook_event_ids[i]

    if event.is_multiday():
        single_event = SingleEvent.objects.filter(event=event, is_occurrence=False)[0]
        single_event.facebook_event = posted_single_events[0].facebook_event
        single_event.save()

    return result
Esempio n. 3
0
 def item_description(self, item):
     mpa = dict.fromkeys(range(32))
     prepared_description = item.event_description().translate(
         mpa)  # removing control characters
     return shorten_string(strip_tags(prepared_description), 500)
Esempio n. 4
0
 def item_description(self, item):
     mpa = dict.fromkeys(range(32))
     prepared_description = item.event_description().translate(mpa) # removing control characters
     return shorten_string(strip_tags(prepared_description), 500)