Пример #1
0
    def import_event(self,fbevent_id,use_cache=True,import_owners=True):
        '''
        Inserts Event for an fbevent_ids from Facebook. Returns an
        EventImportReport objects.

        Will skip over creating an Events already tracked by a 
        FacebookEventRecord instance and return a result with a 
        EventInstanceExists set as the error.

        If importing a batch of events, it's recommended to cache the 
        event infos with either of the pull_event_info calls.

        If import_owners is True, a new Organization will be created for 
        the event owner if it not yet linked to the relevant fbid.
        '''
        info = self.pull_event_info([fbevent_id],use_cache=use_cache)[0]
        try:
            pic = facebook_client.graph_api_picture_request(fbevent_id)
        except IOError as e:
            outsourcing_log.error('Error retreiving picture for event %s: %s' % (unicode(fbevent_id),unicode(e)))
            pic = ''
        
        if not isinstance(info,Exception):
            return self._store_event(info,pic,import_owners=import_owners)
        else:
            return EventImportReport(fbevent_id,None,[info])
Пример #2
0
    def import_event(self, fbevent_id, use_cache=True, import_owners=True):
        '''
        Inserts Event for an fbevent_ids from Facebook. Returns an
        EventImportReport objects.

        Will skip over creating an Events already tracked by a 
        FacebookEventRecord instance and return a result with a 
        EventInstanceExists set as the error.

        If importing a batch of events, it's recommended to cache the 
        event infos with either of the pull_event_info calls.

        If import_owners is True, a new Organization will be created for 
        the event owner if it not yet linked to the relevant fbid.
        '''
        info = self.pull_event_info([fbevent_id], use_cache=use_cache)[0]
        try:
            pic = facebook_client.graph_api_picture_request(fbevent_id)
        except IOError as e:
            outsourcing_log.error('Error retreiving picture for event %s: %s' %
                                  (unicode(fbevent_id), unicode(e)))
            pic = ''

        if not isinstance(info, Exception):
            return self._store_event(info, pic, import_owners=import_owners)
        else:
            return EventImportReport(fbevent_id, None, [info])
Пример #3
0
    def import_events_from_page(self,
                                page_id,
                                start_filter=None,
                                use_cache=True,
                                import_owners=True):
        '''
        Inserts Events for a batch of events belonging to a Facebook page
        id. Returns a list of EventImportReport objects, one per attached
        event.

        If start_filter is provided, events occuring before the given 
        datetime will not be imported.
        
        If querying of page fails, no error will be procuded, just an 
        empty list.

        See import_event for notes about options.
        '''
        page_fbevents_map = self.pull_event_info_from_pages(
            [page_id], start_filter=start_filter, use_cache=use_cache)
        fbevents = page_fbevents_map[page_id]
        page_reports_map = {}

        venue_cache = VenueResolveCache(
        )  # used to prevent redundant resolve calls for a
        # series of events at the same location
        reports = []
        for fbevent in fbevents:
            # TODO: don't like fbevent being a possible exception. revisit.
            if isinstance(fbevent, Exception):
                reports.append(EventImportReport(None, None, [fbevent]))
            else:
                eid = fbevent['id']
                try:
                    pic = facebook_client.graph_api_picture_request(eid)
                except IOError as e:
                    outsourcing_log.error(
                        'Error retreiving picture for event %s: %s' %
                        (unicode(eid), unicode(e)))
                    pic = ''
                reports.append(
                    self._store_event(fbevent,
                                      pic,
                                      import_owners=import_owners,
                                      resolve_cache=venue_cache))
        return reports
Пример #4
0
    def import_events_from_page(self,page_id,start_filter=None,use_cache=True,import_owners=True):
        '''
        Inserts Events for a batch of events belonging to a Facebook page
        id. Returns a list of EventImportReport objects, one per attached
        event.

        If start_filter is provided, events occuring before the given 
        datetime will not be imported.
        
        If querying of page fails, no error will be procuded, just an 
        empty list.

        See import_event for notes about options.
        '''
        page_fbevents_map = self.pull_event_info_from_pages([page_id],
                                                            start_filter=start_filter,
                                                            use_cache=use_cache)
        fbevents = page_fbevents_map[page_id]
        page_reports_map = {}

        venue_cache = VenueResolveCache()   # used to prevent redundant resolve calls for a 
                                            # series of events at the same location
        reports = []
        for fbevent in fbevents:
            # TODO: don't like fbevent being a possible exception. revisit.
            if isinstance(fbevent,Exception):
                reports.append( EventImportReport(None,None,[fbevent]) )
            else:
                eid = fbevent['id']
                try:
                    pic = facebook_client.graph_api_picture_request(eid)
                except IOError as e:
                    outsourcing_log.error('Error retreiving picture for event %s: %s' % (unicode(eid),unicode(e)))
                    pic = ''
                reports.append( self._store_event( fbevent,
                                                    pic,
                                                    import_owners=import_owners,
                                                    resolve_cache=venue_cache))
        return reports
Пример #5
0
def store_fbevent(event_info,event_image=None,
                    create_owners=True,
                    resolve_cache=None):
    '''
    Takes a dict of properties retreived from a Facebook Graph API call for
    a page and stores a Place from the information. The following 
    fields in the dict are used:
    - id          (required)
    - type        (required with value 'event' or a TypeError will be thrown)
    - name        (required)
    - start_time  (required. assumed to be in EST at the moment)
    - end_time    (required. assumed to be in EST at the moment)
    - description
    - venue       (dict with location values)
    - location    (simple string place name)
    - owner       (dict with stub info about organizer)

    No new Event will be returned if either an identical one already
    exists in the db, or a FacebookEventEntry already exists for the given 
    Facebook id. An INFO message is logged to note the attempt to store an 
    existing page as a Place.

    event_image is a URL to an image to use for this event. The Facebook 
    event object doesn't store it's picture directly, instead it stores it 
    as a connection to the event. If this argument is not provided, the 
    live service will be queried to retreive it.

    If create_owners is True, a Facebook-linked model instance will be
    created for the owner.

    The resolve_cache is an optional instance of a VenueResolveCache
    objects. See docs for it for details.
    '''
    fbid = event_info.get('id')
    if fbid is None:
        raise TypeError("Cannot store object without 'event' type.")

    # look to see if event already exists. return with it if so.
    try:
        event = FacebookEventRecord.objects.get(fb_id=fbid).event
        outsourcing_log.info('Existing fb event found for fbid %s'%unicode(fbid))
        return event
    except FacebookEventRecord.DoesNotExist:
        pass
    
    # ensure this is actually an event
    if event_info.get('type') != 'event':
        raise TypeError("Cannot store object without 'event' type.")

    ename = event_info.get('name').strip()
    # need to log events that don't have names
    if not ename:
        outsourcing_log.warning('No name for event with fbid %s' % fbid)

    event = Event(name=event_info['name'],
                    description=unicode(event_info.get('description','')),
                    url='http://www.facebook.com/%s' % fbid)

    # process times
    try:
        dtstart_est = EST.localize(dtparser.parse(event_info.get('start_time')))
        dtend_est = EST.localize(dtparser.parse(event_info.get('end_time')))
    except ValueError as e:
        raise ValueError('Bad start/end time for event fbid %s: %s' % (unicode(fbid),unicode(e)))
        
    event.dtstart = localtoutc(dtstart_est,return_naive=True)
    event.dtend = localtoutc(dtend_est,return_naive=True)

    # process image
    if event_image is None:
        try:
            event.image_url = facebook_client.graph_api_picture_request(fbid)
        except IOError as e:
            outsourcing_log.error('Error retreiving picture for event %s: %s' % (unicode(eid),unicode(e)))
    else:
        event.image_url = event_image
        
    # process place
    if resolve_cache:
        event.place = _process_place_cache_support(event_info,
                                                    resolve_cache=resolve_cache)
    else:
        event.place = _process_place(event_info)
    
    if event.place and event.place.pk is None:
        if event.place.location and event.place.location.pk is None:
            event.place.location.save()
        event.place.save()

    event.save()

    # get the update time from the fbevent
    dtupdate_str = event_info.get('updated_time')
    if dtupdate_str:
        dtupdated = dtparser.parse(event_info.get('updated_time'))
        if dtupdated.tzinfo:    # if a tz was part of the time string, convert to UTC (otherwise just assume UTC)
            dtupdated = localtoutc(dtupdated,return_naive=True)
        event.dtmodified = dtupdated
    else:
        dtupdated = event.dtmodified

    # create a FB record
    FacebookEventRecord.objects.create(fb_id=fbid,event=event,last_updated=dtupdated)

    # add event categories as EventMeta objects
    categorize.add_event_oldtypes(event)
    
    # now set the event owner
    fbowner_id = event_info.get('owner',{}).get('id')
    if fbowner_id:
        owner = _get_owner(fbowner_id,create_new=create_owners)
        if owner:
            role = Role.objects.create(role_type='host',
                                        organization=owner,
                                        event=event)
        
    return event
Пример #6
0
def store_fbevent(event_info,
                  event_image=None,
                  create_owners=True,
                  resolve_cache=None):
    '''
    Takes a dict of properties retreived from a Facebook Graph API call for
    a page and stores a Place from the information. The following 
    fields in the dict are used:
    - id          (required)
    - type        (required with value 'event' or a TypeError will be thrown)
    - name        (required)
    - start_time  (required. assumed to be in EST at the moment)
    - end_time    (required. assumed to be in EST at the moment)
    - description
    - venue       (dict with location values)
    - location    (simple string place name)
    - owner       (dict with stub info about organizer)

    No new Event will be returned if either an identical one already
    exists in the db, or a FacebookEventEntry already exists for the given 
    Facebook id. An INFO message is logged to note the attempt to store an 
    existing page as a Place.

    event_image is a URL to an image to use for this event. The Facebook 
    event object doesn't store it's picture directly, instead it stores it 
    as a connection to the event. If this argument is not provided, the 
    live service will be queried to retreive it.

    If create_owners is True, a Facebook-linked model instance will be
    created for the owner.

    The resolve_cache is an optional instance of a VenueResolveCache
    objects. See docs for it for details.
    '''
    fbid = event_info.get('id')
    if fbid is None:
        raise TypeError("Cannot store object without 'event' type.")

    # look to see if event already exists. return with it if so.
    try:
        event = FacebookEventRecord.objects.get(fb_id=fbid).event
        outsourcing_log.info('Existing fb event found for fbid %s' %
                             unicode(fbid))
        return event
    except FacebookEventRecord.DoesNotExist:
        pass

    # ensure this is actually an event
    if event_info.get('type') != 'event':
        raise TypeError("Cannot store object without 'event' type.")

    ename = event_info.get('name').strip()
    # need to log events that don't have names
    if not ename:
        outsourcing_log.warning('No name for event with fbid %s' % fbid)

    event = Event(name=event_info['name'],
                  description=unicode(event_info.get('description', '')),
                  url='http://www.facebook.com/%s' % fbid)

    # process times
    try:
        dtstart_est = EST.localize(dtparser.parse(
            event_info.get('start_time')))
        dtend_est = EST.localize(dtparser.parse(event_info.get('end_time')))
    except ValueError as e:
        raise ValueError('Bad start/end time for event fbid %s: %s' %
                         (unicode(fbid), unicode(e)))

    event.dtstart = localtoutc(dtstart_est, return_naive=True)
    event.dtend = localtoutc(dtend_est, return_naive=True)

    # process image
    if event_image is None:
        try:
            event.image_url = facebook_client.graph_api_picture_request(fbid)
        except IOError as e:
            outsourcing_log.error('Error retreiving picture for event %s: %s' %
                                  (unicode(eid), unicode(e)))
    else:
        event.image_url = event_image

    # process place
    if resolve_cache:
        event.place = _process_place_cache_support(event_info,
                                                   resolve_cache=resolve_cache)
    else:
        event.place = _process_place(event_info)

    if event.place and event.place.pk is None:
        if event.place.location and event.place.location.pk is None:
            event.place.location.save()
        event.place.save()

    event.save()

    # get the update time from the fbevent
    dtupdate_str = event_info.get('updated_time')
    if dtupdate_str:
        dtupdated = dtparser.parse(event_info.get('updated_time'))
        if dtupdated.tzinfo:  # if a tz was part of the time string, convert to UTC (otherwise just assume UTC)
            dtupdated = localtoutc(dtupdated, return_naive=True)
        event.dtmodified = dtupdated
    else:
        dtupdated = event.dtmodified

    # create a FB record
    FacebookEventRecord.objects.create(fb_id=fbid,
                                       event=event,
                                       last_updated=dtupdated)

    # add event categories as EventMeta objects
    categorize.add_event_oldtypes(event)

    # now set the event owner
    fbowner_id = event_info.get('owner', {}).get('id')
    if fbowner_id:
        owner = _get_owner(fbowner_id, create_new=create_owners)
        if owner:
            role = Role.objects.create(role_type='host',
                                       organization=owner,
                                       event=event)

    return event