Esempio n. 1
0
 def save_event(self):
     """
     This method takes dictionary containing event data. It first checks if
     any event is there with given info (user_id, social_network_id,
     social_network_event_id), then it updates the existing event otherwise
     creates a new event in getTalent database.
     Call this method after successfully publishing event on social network.
     :return event.id: id for event in getTalent database, that was created or updated
     :rtype event.id : int
     """
     data = self.data
     sn_event_id = data['social_network_event_id']
     social_network_id = data['social_network_id']
     event = Event.get_by_user_id_social_network_id_vendor_event_id(
         self.user.id, social_network_id, sn_event_id)
     try:
         # if event exists in database, then update existing one.
         if event:
             del data['id']
             event.update(**data)
         else:
             # event not found in database, create a new one
             event = Event(**data)
             Event.save(event)
     except Exception as error:
         logger.exception(
             'save_event: Event was not updated/saved in Database. '
             'user_id: %s, event_id: %s, social network: %s(id: %s). Error:%s'
             % (self.user.id, event.id, self.social_network.name,
                self.social_network.id, error.message))
         raise EventNotSaveInDb(
             'Error occurred while saving event in database')
     return event.id
Esempio n. 2
0
    def delete_events(self, event_ids):
        """
        :param event_ids: contains all the ids of events to be deleted
            both from social network and database.
        :type event_ids: list
        """
        deleted = []
        not_deleted = []
        if event_ids:
            for event_id in event_ids:
                event_obj = Event.get_by_user_and_event_id(
                    user_id=request.user.id, event_id=event_id)
                title = event_obj.title
                if self.delete_event(event_id):
                    deleted.append(event_id)

                    activity_data = {
                        'username': request.user.name,
                        'event_title': title
                    }
                    add_activity(
                        user_id=request.user.id,
                        activity_type=Activity.MessageIds.EVENT_DELETE,
                        source_table=Event.__tablename__,
                        source_id=event_id,
                        params=activity_data)
                else:
                    not_deleted.append(event_id)
        return deleted, not_deleted
Esempio n. 3
0
 def update_tickets(self, social_network_event_id):
     """
     This method update tickets for specific event on Eventbrite.com.
     This method should be called after updating event contents on
     social_network.
     See "social_network_service.event.Eventbrite.update_event" method for
         further info
     :param social_network_event_id: event id which refers to event on
     eventbrite.com
     :type social_network_event_id: str
     :exception TicketsNotCreated (throws exception if unable to update
         tickets)
     :return: tickets_id (an id which refers to tickets updated on
         eventbrite.com)
     :rtype: str
     """
     tickets_url = get_url(self,
                           Urls.TICKETS).format(social_network_event_id)
     event = Event.get_by_user_and_social_network_event_id(
         self.user.id, social_network_event_id)
     if event.tickets_id:
         tickets_url = tickets_url + str(event.tickets_id) + '/'
     else:
         logger.info('Tickets ID is not available for event with id %s,'
                     ' User:  %s' %
                     (social_network_event_id, self.user.name))
         raise TicketsNotCreated('ApiError: Unable to update event tickets'
                                 ' on Eventbrite as tickets_id was not '
                                 'found for this event')
     return self.manage_event_tickets(tickets_url)
Esempio n. 4
0
 def update_event_associated_with_other_users(self, event_data):
     """
     This method takes an event an update it for all users associated with it.
     :param event_data: Event dict
     """
     # getting all users associated with a specific meetup account
     member_users = UserSocialNetworkCredential.query.filter_by(
         member_id=self.member_id,
         social_network_id=event_data['social_network_id'])
     events_in_db = Event.query.filter_by(
         social_network_id=event_data['social_network_id'],
         social_network_event_id=event_data['social_network_event_id'])
     # making list of 'user_id' of users associated with a specific event
     user_ids = [event.user_id for event in events_in_db]
     member_user_ids = [member.user_id for member in member_users]
     # getting list of users for whom event 'event_data' is not saved in db.
     missing_event_users = set(member_user_ids) - set(user_ids)
     event_data['is_deleted_from_vendor'] = 0
     events_in_db.update(event_data, synchronize_session=False)
     # saving event 'event_data' in db for those users which are connected with same meetup account in
     # other domain but event was not saved for them.
     for member_user_id in missing_event_users:
         event = Event(user_id=member_user_id, **event_data)
         db.session.add(event)
     db.session.commit()
Esempio n. 5
0
 def delete_event(self, event_id, delete_from_vendor=True):
     """
     Here we pass an event id, picks it from db, and try to delete
     it both from social network and database. If successfully deleted
     from both sources, returns True, otherwise returns False.
     :param event_id: is the 'id' of event present in our db
     :type event_id: int or long
     :param delete_from_vendor: is flag to delete event from third party
     :type delete_from_vendor: bool
     :return: True if deletion is successful, False otherwise.
     :rtype: bool
     """
     event = Event.get_by_user_and_event_id(self.user.id, event_id)
     if event:
         try:
             if delete_from_vendor:
                 self.unpublish_event(event.social_network_event_id)
             self.archive_email_campaigns_for_deleted_event(
                 event, delete_from_vendor)
             return True
         except Exception:  # some error while removing event
             logger.exception(
                 'delete_event: user_id: %s, event_id: %s, social network: %s(id: %s)'
                 % (self.user.id, event.id, self.social_network.name,
                    self.social_network.id))
     return False  # event not found in database
Esempio n. 6
0
def assert_event(user_id, social_network_event_id):
    """
    This asserts we get event in database for given user_id and social_network_event_id
    """
    db.session.commit()
    event = Event.get_by_user_and_social_network_event_id(
        user_id=user_id, social_network_event_id=social_network_event_id)
    assert event
Esempio n. 7
0
def test_get_event(token_first, event_in_db):
    """
    Validate that Graphql endpoint is working fine for `event` and `events` queries.
    Also match data for single event.
    """
    response = assert_valid_response('event', Event, token_first,
                                     event_in_db['id'])
    event = response['data']['event']
    match_data(event, event_in_db,
               Event.get_fields(exclude=('organizer_id', 'url')))
Esempio n. 8
0
 def get_events_from_db(self, start_date=None):
     """
     This gets the events from database which starts after the specified start_date
     or in case date is None, return all events
     :param start_date:
     :type start_date: datetime|None
     :return: list of events
     """
     if start_date:
         events = Event.get_by_user_id_vendor_id_start_date(
             self.user.id, self.social_network.id, start_date)
     else:
         events = Event.filter_by_keywords(
             user_id=self.user.id, social_network_id=self.social_network.id)
     if events:
         logger.info(
             'There are %s events of %s(user_id:%s) in database with start_datetime ahead of:%s.'
             % (len(events), self.user.name, self.user.id, start_date))
     else:
         logger.info(
             'No events found of %s(user_id:%s) in database with start_datetime ahead of:%s.'
             % (self.user.name, self.user.id, start_date))
     return events
Esempio n. 9
0
    def get(self, event_id):
        """
        Returns event object with required id
        :param event_id: (Integer) unique id in Event table on GT database.

        :Example:
            headers = {'Authorization': 'Bearer <access_token>'}
            event_id = 1
            response = requests.get(API_URL + '/events/' + str(event_id), headers=headers)

        .. Response::

            {
              "event": {
                          "cost": 0,
                          "currency": "USD",
                          "description": "Test Event Description",
                          "end_datetime": "2015-10-30 16:51:00",
                          "social_network_group_id": "18837246",
                          "group_url_name": "QC-Python-Learning",
                          "id": 1,
                          "max_attendees": 10,
                          "organizer_id": 1,
                          "registration_instruction": "Just Come",
                          "social_network_event_id": "18970807195",
                          "social_network_id": 18,
                          "start_datetime": "2015-10-25 16:50:00",
                          "tickets_id": "39836307",
                          "timezone": "Asia/Karachi",
                          "title": "Test Event",
                          "url": "",
                          "user_id": 1,
                          "venue_id": 2
                        }

            }

        .. Status:: 200 (OK)
                    404 (Event not found)
                    500 (Internal Server Error)
        :param event_id: integer, unique id representing event in GT database
        :return: json for required event
        """
        event = Event.get_by_event_id_and_domain_id(event_id,
                                                    request.user.domain_id)
        if not event:
            raise ResourceNotFound(
                'Event does not exist with id %s in user`s domain.' % event_id)
        event_data = add_organizer_venue_data(event)
        return dict(event=event_data)
Esempio n. 10
0
def _get_event(user_id, social_network_id, social_network_event_id):
    """
    This searches the event in database for given parameters.
    :param positive user_id: If of user
    :param positive social_network_id: Id of Meetup social-network
    :param string social_network_event_id: Id of event on Meetup website
    """
    db.session.commit()
    event = Event.get_by_user_id_social_network_id_vendor_event_id(
        user_id, social_network_id, social_network_event_id)
    if not event:  # TODO: If event is going to happen in future, we should import that event here
        raise EventNotFound(
            'Event is not present in db, social_network_event_id is %s. User Id: %s'
            % (social_network_event_id, user_id))
Esempio n. 11
0
def event_data_tests(method, url, data, token):
    """

    :param method:
    :param url:
    :param data:
    :param token:
    :return:
    """
    event = data.copy()

    # Update with invalid event id
    event['id'] = 231232132133  # We will find a better way to test it
    response = send_request(method, url, token, data=event)
    # response = send_post_request(SocialNetworkApiUrl.EVENT % event['id'],
    #                              event, token)
    logger.info(response.text)
    assert response.status_code == 404, 'Event not found with this id'

    # Update with invalid social network event id
    event = data.copy()
    event['social_network_event_id'] = -1
    response = send_request(method, url, token, data=event)
    logger.info(response.text)
    assert response.status_code == 404, 'Event not found with this social network event id'

    event = data.copy()

    # success case, event should be updated
    datetime_now = datetime.datetime.now()
    event['title'] = 'Test update event'
    event['start_datetime'] = (
        datetime_now +
        datetime.timedelta(days=50)).strftime('%Y-%m-%dT%H:%M:%SZ')
    event['end_datetime'] = (
        datetime_now +
        datetime.timedelta(days=60)).strftime('%Y-%m-%dT%H:%M:%SZ')
    response = send_request(method, url, token, data=event)
    logger.info(response.text)
    assert response.status_code == 200, 'Status should be Ok, Resource Modified (204)'
    event_db = Event.get_by_id(event['id'])
    Event.session.commit(
    )  # needed to refresh session otherwise it will show old objects
    event_db = event_db.to_json()
    assert event['title'] == event_db['title'], 'event_title is modified'
    assert event['start_datetime'] == event_db['start_datetime'].replace(' ', 'T') + 'Z', \
        'start_datetime is modified'
    assert event['end_datetime'] == event_db['end_datetime'].replace(' ', 'T') + 'Z', \
        'end_datetime is modified'
Esempio n. 12
0
    def test_put_with_valid_token(self, token_first, new_event_in_db_second):
        """
        - Get event data from db (using fixture - event_in_db)
        - Using event id, send PUT request to update event data
        - Should get 200 response
        - Check if activity is created or not
        """
        event = copy.deepcopy(new_event_in_db_second)
        # Success case, event should be updated
        datetime_now = datetime.datetime.utcnow()
        datetime_now = datetime_now.replace(microsecond=0)
        event['title'] = 'Test update event'
        event['start_datetime'] = (datetime_now +
                                   datetime.timedelta(days=50)).strftime(
                                       DatetimeUtils.ISO8601_FORMAT)
        event['end_datetime'] = (datetime_now +
                                 datetime.timedelta(days=60)).strftime(
                                     DatetimeUtils.ISO8601_FORMAT)
        response = send_request('put',
                                SocialNetworkApiUrl.EVENT % event['id'],
                                token_first,
                                data=event)
        logger.info(response.text)
        assert response.status_code == codes.OK, '{} {}'.format(
            response.text, event)
        db.db.session.commit()
        event_occurrence_in_db = Event.get_by_id(event['id'])
        Event.session.commit(
        )  # needed to refresh session otherwise it will show old objects
        event_occurrence_in_db = event_occurrence_in_db.to_json()
        assert event['title'] == event_occurrence_in_db[
            'title'], 'event_title is modified'
        assert event['start_datetime'].split('.')[0] + 'Z' == event_occurrence_in_db['start_datetime'] \
                                                                  .replace(' ', 'T') + 'Z', \
            'start_datetime is modified'
        assert (event['end_datetime']).split('.')[0] + 'Z' == event_occurrence_in_db['end_datetime'] \
                                                                  .replace(' ', 'T') + 'Z', \
            'end_datetime is modified'

        # Check activity updated
        CampaignsTestsHelpers.assert_for_activity(
            event_occurrence_in_db['user_id'],
            Activity.MessageIds.EVENT_UPDATE, event['id'])
        activity = Activity.get_by_user_id_type_source_id(
            user_id=event_occurrence_in_db['user_id'],
            source_id=event['id'],
            type_=Activity.MessageIds.EVENT_UPDATE)
        data = json.loads(activity.params)
        assert data['event_title'] == event['title']
Esempio n. 13
0
def import_eventbrite_event(user_id, event_url, action_type):
    """
    This celery task retrieves user event from eventbrite and then saves or
    """
    with app.app_context():
        logger = app.config[TalentConfigKeys.LOGGER]
        logger.info('Going to process Eventbrite Event: %s' % event_url)
        try:
            eventbrite = SocialNetwork.get_by_name('Eventbrite')
            eventbrite_sn = EventbriteSocialNetwork(
                user_id=user_id, social_network_id=eventbrite.id)
            eventbrite_event_base = EventbriteEventBase(
                headers=eventbrite_sn.headers,
                user_credentials=eventbrite_sn.user_credentials,
                social_network=eventbrite_sn.user_credentials.social_network)
            if action_type in [ACTIONS['created'], ACTIONS['published']]:
                logger.info('Event Published on Eventbrite, Event URL: %s' %
                            event_url)
                eventbrite_event_base.get_event(event_url)
            elif action_type == ACTIONS['unpublished']:
                event_id = event_url.split('/')[-2]
                event_id = int(event_id)
                event_in_db = Event.get_by_user_id_social_network_id_vendor_event_id(
                    user_id, eventbrite.id, event_id)
                if event_in_db:
                    if eventbrite_event_base.delete_event(
                            event_in_db.id, delete_from_vendor=False):
                        logger.info(
                            'Event has been marked as is_deleted_from_vendor in gt database: %s'
                            % event_in_db.to_json())
                    else:
                        logger.info(
                            'Event could not be marked as is_deleted_from_vendor in gt database: %s'
                            % event_in_db.to_json())
                else:
                    logger.info(
                        "Event unpublished from Eventbrite but it does not exist, don't worry. Event URL: %s"
                        % event_url)
            elif action_type == ACTIONS['updated']:
                pass  # We are handling update action yet because it causes duplicate entries

        except Exception:
            logger.exception('Failed to save event. URL: %s' % event_url)
Esempio n. 14
0
    def post(self, social_network_id):
        """
        Remove access and refresh token for specified user and social network.
        :param int | long social_network_id: social network id

        :Example:


            headers = {
                        'Authorization': 'Bearer <access_token>',
                       }
            response = requests.get(
                                        API_URL + '/social-networks/13/disconnect',
                                        headers=headers
                                    )

        .. Response::

            {
                "message" : 'Access token and refresh has been removed'
            }

        .. HTTP Status:: 201 (Resource Created)
                         404 (Social network not found)
                         500 (Internal Server Error)
        """
        user_id = request.user.id
        social_network = SocialNetwork.get_by_id(social_network_id)
        if not social_network:
            raise ResourceNotFound("Social Network not found")

        # Get social network specific Social Network class
        social_network_class = get_class(social_network.name, 'social_network')
        social_network_class.disconnect(user_id, social_network)
        events_count = Event.disable_events(user_id, social_network.id)
        logger.info(
            'User (id: %s) has been disconnect from %s and his %s events are marked as hidden'
            % (user_id, social_network.name, events_count))
        return dict(
            messsage=
            'User (id: %s) has been disconnected from social network (name: %s)'
            % (user_id, social_network.name))
Esempio n. 15
0
def test_get_events_pagination(token_first, event_in_db, event_in_db_second):
    """
    Validate that pagination is working fine. There are two events created by test user.
    We will get 2 events in first page and then no events in second page (request)
    """
    assert_valid_response('event', Event, token_first, event_in_db['id'])
    fields = Event.get_fields()
    query = get_query('events', fields, args=dict(page=1, per_page=10))
    response = get_graphql_data(query, token_first)
    assert 'errors' not in response, 'Response: %s\nQuery: %s' % (response,
                                                                  query)
    validate_graphql_response('events',
                              response['data'],
                              fields,
                              is_array=True)

    # Since there were only two events created, now getting events for second page will return no events
    query = get_query('events', fields, args=dict(page=2, per_page=10))
    response = get_graphql_data(query, token_first)
    assert 'errors' not in response, 'Response: %s\nQuery: %s' % (response,
                                                                  query)
    assert response['data']['events'] == []
Esempio n. 16
0
 def save_or_update_event(self, event_data):
     """
     This method takes event dictionary data and save that event in database or update the existing one
     if there is already event there with this data.
     :param event_data: event dict
     :rtype: Event
     """
     event = Event.get_by_user_id_social_network_id_vendor_event_id(
         self.user.id, self.social_network.id,
         event_data['social_network_event_id'])
     event_data['is_deleted_from_vendor'] = 0
     event_data['is_hidden'] = 0
     if event:
         event.update(**event_data)
         logger.info('Event updated successfully : %s' % event.to_json())
     else:
         event = Event(**event_data)
         Event.save(event)
         logger.info('Event imported successfully : %s' % event.to_json())
     return event
Esempio n. 17
0
    def get_attendee_for_rsvp_via_webhook(self, rsvp):
        """
        :param rsvp: rsvp is likely the response of social network API.
        :type rsvp: dict
        :return: attendee
        :rtype: object

        Webhook returns data for RSVP as:

        {
            u'config': {
                            u'action': u'order.placed',
                            u'user_id': u'149011448333',
                            u'endpoint_url': u'https://emails.ngrok.io/webhook/1',
                            u'webhook_id': u'274022'
                        },
            u'api_url': u'https://www.eventbriteapi.com/v3/orders/573384540/'
        }

        we extract order_id from above response and treat it as social_network_rsvp_id.
        So, rsvp object in this method looks like

            {
                'rsvp_id': 573384540
            }

        When we request Eventbrite API with above rsvp_id, we get response as
            {
                u'status': u'placed',
                u'first_name': u'Muhammad',
                u'last_name': u'Aslam',
                u'name': u'Muhammad Aslam',
                u'created': u'2016-11-29T15:52:15Z',
                u'event_id': u'29641929810',
                u'changed': u'2016-11-29T15:52:16Z',
                u'email': u'*****@*****.**',
                u'costs':
                        {
                            u'payment_fee': {u'currency': u'USD', u'display': u'$0.00',
                                             u'value': 0, u'major_value': u'0.00'
                                             },
                            u'gross': { u'currency': u'USD', u'display': u'$0.00', u'value': 0,
                                        u'major_value': u'0.00'},
                            u'eventbrite_fee': {u'currency': u'USD', u'display': u'$0.00', u'value': 0,
                                                u'major_value': u'0.00'},
                            u'tax': {u'currency': u'USD', u'display': u'$0.00', u'value': 0, u'major_value': u'0.00'},
                            u'base_price': {u'currency': u'USD', u'display': u'$0.00', u'value': 0,
                                            u'major_value': u'0.00'}
                        },
                u'time_remaining': None,
                u'id': u'575508020',
                u'resource_uri': u'https://www.eventbriteapi.com/v3/orders/575508020/'
            }

        - This function is used to get the data of candidate related to given rsvp. It attaches all the information
            in attendee object. `attendees` is a utility object we share in calls that contains
          pertinent data.

        - This method is called from get_attendee() defined in this file.

        :Example:
            attendee = self.get_attendee_for_rsvp_via_webhook(rsvp)

        **See Also**
            .. seealso:: get_attendee() method in this class.
        """
        order_url = get_url(self, Urls.ORDER).format(rsvp['rsvp_id'])
        order_response = http_request('GET',
                                      order_url,
                                      headers=self.headers,
                                      user_id=self.user.id)
        if order_response.ok:
            data = order_response.json()
            # get event_id
            social_network_event_id = data['event_id']
            event = Event.get_by_user_id_social_network_id_vendor_event_id(
                self.user.id, self.social_network.id, social_network_event_id)
            if not event:
                raise EventNotFound(
                    'Event is not present in db, social_network_event_id is %s. User Id: %s'
                    % (social_network_event_id, self.user.id))
            created_datetime = datetime.strptime(data['created'][:19],
                                                 "%Y-%m-%dT%H:%M:%S")
            attendee = Attendee()
            attendee.event = event
            attendee.first_name = data['first_name']
            attendee.full_name = data['name']
            attendee.last_name = data['last_name']
            attendee.added_time = created_datetime
            attendee.rsvp_status = 'yes' if data[
                'status'] == 'placed' else data['status']
            attendee.email = data['email']
            attendee.vendor_rsvp_id = rsvp['rsvp_id']
            attendee.gt_user_id = self.user.id
            attendee.social_network_id = self.social_network.id
            # TODO: This won't work now, need to figure out a way
            attendee.vendor_img_link = \
                "<img class='pull-right'" \
                " style='width:60px;height:30px' " \
                "src='/web/static/images/activities/eventbrite_logo.png'/>"
            # GET attendees of event
            rsvps_url = get_url(self, Urls.RSVPS).format(
                event.social_network_event_id)
            response_attendees = http_request('GET',
                                              rsvps_url,
                                              headers=self.headers)
            event_attendees = response_attendees.json()['attendees']
            for event_attendee in event_attendees:
                # Get profile url of candidate to save
                if event_attendee['created'] == order_response.json(
                )['created']:
                    # In case of Eventbrite, we have a Attendee object created
                    # on Eventbrite website. We save that link as profile url.
                    attendee.social_profile_url = event_attendee[
                        'resource_uri']
                    break
            return attendee
Esempio n. 18
0
    def put(self, event_id):
        """
        Updates event in getTalent's database and on corresponding social network.
        :param event_id: id of event on getTalent database

        :Example:

            event_data = {
                    "organizer_id": 1,
                    "venue_id": 2,
                    "title": "Test Event",
                    "description": "Test Event Description",
                    "registration_instruction": "Just Come",
                    "end_datetime": "30 Oct, 2015 04:51 pm",
                    "group_url_name": "QC-Python-Learning",
                    "social_network_id": 18,
                    "timezone": "Asia/Karachi",
                    "cost": 0,
                    "start_datetime": "25 Oct, 2015 04:50 pm",
                    "currency": "USD",
                    "social_network_group_id": 18837246,
                    "max_attendees": 10
            }

            headers = {
                        'Authorization': 'Bearer <access_token>',
                        'Content-Type': 'application/json'
                       }
            data = json.dumps(event_data)
            event_id = event_data['id']
            response = requests.post(
                                        API_URL + '/events/' + str(event_id)',
                                        data=data,
                                        headers=headers,
                                    )

        .. Response::

            No Content

        .. Status:: 200 (Resource Modified)
                    500 (Internal Server Error)
                    401 (Unauthorized to access getTalent)
                    403 (Forbidden: Can not update specified event)

        .. Error codes (returned in response's body):
                    In case of internal server error, response contains error code which can be

                    4052 (Unable to determine Social Network)
                    4053 (Some Required event fields are missing)
                    4055 (Event not created)
                    4056 (Event not Published on Social Network)
                    4058 (Event venue not created on Social Network)
                    4059 (Tickets for event not created)
                    4060 (Event was not save in getTalent database)
                    4061 (User credentials of user for Social Network not found)
                    4062 (No implementation for specified Social Network)
                    4064 (Invalid datetime for event)
                    4065 (Specified Venue not found in database)
                    4066 (Access token for Social Network has expired)

        """
        event_data = get_valid_json_data(request)
        # check whether given event_id exists for this user
        event = Event.get_by_user_id_event_id_social_network_event_id(
            request.user.id, event_id, event_data['social_network_event_id'])

        if not event:
            raise ResourceNotFound('Event not found')

        process_event(event_data, request.user.id, method='Update')
        return dict(message='Event updated successfully')
Esempio n. 19
0
    def test_eventbrite_rsvp_importer_endpoint(self, token_first, user_first,
                                               talent_pool_session_scope,
                                               user_same_domain,
                                               token_same_domain):
        """
        Test eventbrite rsvps importer.
        A pre-existing rsvp is on eventbrite.
        - Run rsvp importer for eventbrite.
        - Then check if already created rsvp is imported correctly or not
        - Then again run rsvp importer and assert there should be only 1 rsvp
        - Remove user talent pool and run tests and rsvp should not be imported
        """

        rsvp_id = '672393772'
        social_network_event_id = '26557579435'
        user_id = user_first['id']
        headers = dict(Authorization='Bearer %s' % token_first)
        headers['Content-Type'] = 'application/json'

        eventbrite_obj = SocialNetwork.get_by_name('Eventbrite')

        usercredentials = UserSocialNetworkCredential.get_all_credentials(
            eventbrite_obj.id)
        for usercredential in usercredentials:
            usercredential.update(updated_datetime=None)

        rsvps = RSVP.filter_by_keywords(
            **{
                'social_network_rsvp_id': rsvp_id,
                'social_network_id': eventbrite_obj.id
            })

        for rsvp in rsvps:
            RSVP.delete(rsvp.id)
        """---------------------------Get or Import event for eventbrite-------------------------------"""

        event = Event.get_by_user_and_social_network_event_id(
            user_id=user_id, social_network_event_id=social_network_event_id)
        # If event is not imported then run event importer and import events first
        if not event:
            # Import events first then import RSVPs
            response = requests.post(url=SocialNetworkApiUrl.IMPORTER %
                                     ('event', 'eventbrite'),
                                     headers=headers)
            assert response.status_code == codes.OK
            retry(assert_event,
                  args=(user_id, social_network_event_id),
                  sleeptime=15,
                  attempts=15,
                  sleepscale=1,
                  retry_exceptions=(AssertionError, ))

        eventbrite_event = Event.get_by_user_and_social_network_event_id(
            user_id, social_network_event_id)
        assert eventbrite_event
        """------------------------------------------------------------------------------------------------
        -----------------------------SECTION: Import RSVPs for User 1--------------------------------------
        """

        response = requests.post(url=SocialNetworkApiUrl.IMPORTER %
                                 ('rsvp', 'eventbrite'),
                                 data=json.dumps({}),
                                 headers=headers)
        assert response.status_code == codes.OK

        # Check if rsvp is imported for user 1
        def f(_rsvp_id, _eventbrite_id, event_id, count=1):
            db.db.session.commit()
            _rsvp = RSVP.filter_by_keywords(
                **{
                    'social_network_rsvp_id': _rsvp_id,
                    'social_network_id': _eventbrite_id,
                    'event_id': event_id
                })
            assert len(_rsvp) == count

        retry(f,
              sleeptime=15,
              attempts=15,
              sleepscale=1,
              retry_exceptions=(AssertionError, ),
              args=(rsvp_id, eventbrite_obj.id, eventbrite_event.id))
        """------------------------------------------------------------------------------------------------
                    Get RSVP for user id 2, which shouldn't be imported due to talent pool attached
        """
        db.db.session.commit()
        eventbrite_event_user_second = Event.get_by_user_and_social_network_event_id(
            user_same_domain['id'], social_network_event_id)
        assert eventbrite_event_user_second

        retry(f,
              sleeptime=15,
              attempts=15,
              sleepscale=1,
              retry_exceptions=(AssertionError, ),
              args=(rsvp_id, eventbrite_obj.id,
                    eventbrite_event_user_second.id, 0))
        """------------------------------------------------------------------------------------------------
        ----------------SECTION: Import RSVPs again and rsvps shouldn't be redundant------------------------
        """

        # Run rsvp importer again and data should not be redundant.
        response = requests.post(url=SocialNetworkApiUrl.IMPORTER %
                                 ('rsvp', 'eventbrite'),
                                 data=json.dumps({}),
                                 headers=headers)

        assert response.status_code == codes.OK

        retry(f,
              sleeptime=15,
              attempts=15,
              sleepscale=1,
              retry_exceptions=(AssertionError, ),
              args=(rsvp_id, eventbrite_obj.id, eventbrite_event.id))

        rsvp = RSVP.get_by_social_network_rsvp_id_and_social_network_id(
            rsvp_id, eventbrite_obj.id)
        RSVP.delete(rsvp.id)
Esempio n. 20
0
 def resolve_event(self, args, request, info):
     """
     Resolves an event owned by current user.
     """
     event_id = args.get('id')
     return Event.get_by_user_and_event_id(request.user.id, event_id)
Esempio n. 21
0
    def post(self, social_network_id):
        """
        Adds credentials for user for given social network.
        Gets data from POST request which contains 'code' and 'social_credentials'
        :param args:
        :param kwargs:
        :return:

        :Example:
            data = {
                    'code': '32432ffd2s8fd23e8saq123ds6a3da21221
                    }


            headers = {
                        'Authorization': 'Bearer <access_token>',
                        'Content-Type': 'application/json'
                       }
            data = json.dumps(data)
            response = requests.post(
                                        API_URL + '/social-networks/13/user/credentials',
                                        data=data,
                                        headers=headers,
                                    )

        .. Response::

            {
                "message" : 'User credentials for social network were added successfully'
            }

        .. HTTP Status:: 201 (Resource Updated)
                         404 (Social Network not found)
                         500 (Internal Server Error)

        """
        user_id = request.user.id
        # Get json request data
        req_data = get_valid_json_data(request)
        code = req_data['code']
        social_network = SocialNetwork.get_by_id(social_network_id)
        # if social network does not exists, send failure message
        if social_network:
            # Get social network specific Social Network class
            social_network_class = get_class(social_network.name,
                                             'social_network')
            credentials = social_network_class(
                user_id, social_network.id,
                validate_credentials=False).connect(code)
            logger.info(
                'User(id:%s) has been connected successfully with %s. We are going to import events now.'
                % (user_id, social_network.name))
            events_count = Event.enable_events(user_id, social_network.id)
            logger.info(
                'User (id: %s) has been connected to %s and his %s events have been enabled'
                % (user_id, social_network.name, events_count))
            sync_events.delay(credentials)
            return dict(
                message='User credentials added successfully'), codes.CREATED
        else:
            raise ResourceNotFound('Social Network not found')
Esempio n. 22
0
def process_meetup_event(event):
    """
    This celery task is for an individual event to be processed. When `rsvp_events_importer` task finds that some
    event belongs to getTalent user, it passes this event to this task for further processing.

    In this task, we create meetup objects for social network and event and the finally save this event by mapping
    meetup event fields to gt event fields. If event already exists in database, it is updated.

    If an event contains venue information, is is save in `venue` table or updated an existing venue.
    :param dict event: event dictionary from meetup
    """
    with app.app_context():
        logger = app.config[TalentConfigKeys.LOGGER]

        # if same event is received multiple times, accept first and reject remaining
        meetup_event_lock_key = json.dumps(event)
        if not redis_store.get(meetup_event_lock_key):
            # set lock for 5 minutes
            redis_store.set(meetup_event_lock_key, True, 5 * 60)
        else:
            logger.info('Already received this Meetup Event: %s.' % event)
            return 'Done'

        logger.info('Going to process Meetup Event: %s' % event)
        try:
            time.sleep(
                5
            )  # wait for event creation api to save event in database otherwise there can be duplicate
            # event created in database (one by api and other by importer)
            groups = MeetupGroup.get_all_records_by_group_id(
                event['group']['id'])
            meetup = SocialNetwork.get_by_name('Meetup')
            # have to change in try catch as well
            try:
                meetup_sn = MeetupSocialNetwork(user_id=groups[0].user.id,
                                                social_network_id=meetup.id)
            except HitLimitReached:
                meetup_sn = MeetupSocialNetwork(user_id=groups[0].user.id,
                                                social_network_id=meetup.id,
                                                validate_token=False)
            meetup_event_base = Meetup(
                user_credentials=meetup_sn.user_credentials,
                social_network=meetup,
                headers=meetup_sn.headers)
            if event['status'] in [
                    MEETUP_EVENT_STATUS['upcoming'],
                    MEETUP_EVENT_STATUS['suggested'],
                    MEETUP_EVENT_STATUS['proposed']
            ]:
                event_data = meetup_event_base.fetch_event(event['id'])
                gt_event_data, gt_venue_data = meetup_event_base.event_sn_to_gt_mapping(
                    event_data)
                for group_user in groups:
                    try:
                        group_user_credentials = UserSocialNetworkCredential.get_by_user_and_social_network_id\
                            (group_user.user.id, meetup.id)
                        meetup_event_obj = Meetup(
                            user_credentials=group_user_credentials,
                            social_network=meetup,
                            headers=meetup_sn.headers)
                        if gt_venue_data:
                            gt_venue_data['user_id'] = group_user.user_id
                            venue_in_db = meetup_event_obj.save_or_update_venue(
                                gt_venue_data)
                            gt_event_data['venue_id'] = venue_in_db.id
                        gt_event_data['user_id'] = group_user.user_id
                        meetup_event_obj.save_or_update_event(gt_event_data)
                    except Exception as e:
                        logger.error(
                            "An error occured while saving event, error: %s" %
                            e)

            elif event['status'] in [
                    'canceled', MEETUP_EVENT_STATUS['deleted']
            ]:
                social_network_event_id = event['id']
                for group_user in groups:
                    try:
                        event_in_db = Event.get_by_user_id_social_network_id_vendor_event_id(
                            group_user.user_id, meetup.id,
                            social_network_event_id)
                        if event_in_db:
                            meetup_event_base.user = group_user.user
                            if meetup_event_base.delete_event(
                                    event_in_db.id, delete_from_vendor=False):
                                logger.info(
                                    'Meetup event has been marked as is_deleted_from_vendor in gt database: %s'
                                    % event_in_db.to_json())
                            else:
                                logger.info(
                                    'Event could not be marked as is_deleted_from_vendor in gt database: %s'
                                    % event_in_db.to_json())
                        else:
                            logger.info(
                                "Meetup event not found in database. event:`%s`."
                                % event)
                    except Exception as e:
                        logger.error(
                            "An error occured while marking event deleted, error: %s"
                            % e)

        except Exception:
            logger.exception('Failed to save event: %s' % event)
            rollback()
Esempio n. 23
0
    def get(self):
        """
        This action returns a list of user events and their count
        :return events_data: a dictionary containing list of events and their count
        :rtype json

        :Example:
            headers = {'Authorization': 'Bearer <access_token>'}
            response = requests.get(API_URL + '/events/', headers=headers)

        .. Response::

            {
              "events": [
                {
                  "cost": 0,
                  "currency": "USD",
                  "description": "Test Event Description",
                  "end_datetime": "2015-10-30 16:51:00",
                  "social_network_group_id": "18837246",
                  "group_url_name": "QC-Python-Learning",
                  "id": 189,
                  "max_attendees": 10,
                  "organizer_id": 1,
                  "registration_instruction": "Just Come",
                  "social_network_event_id": "18970807195",
                  "social_network_id": 18,
                  "start_datetime": "2015-10-25 16:50:00",
                  "tickets_id": "39836307",
                  "timezone": "Asia/Karachi",
                  "title": "Test Event",
                  "url": "",
                  "user_id": 1,
                  "is_deleted_from_vendor": 0,
                  "venue_id": 2
                }
              ]
            }

        .. Status:: 200 (OK)
                    500 (Internal Server Error)

        """
        page, per_page = get_pagination_params(request)
        search = request.args.get('search')
        sort_by = request.args.get('sort_by', 'start_datetime')
        sort_type = request.args.get('sort_type', 'desc')
        user_id = request.args.get('user_id')
        is_deleted_from_vendor = request.args.get('is_deleted_from_vendor', 0)

        if user_id:
            if user_id.isdigit():
                user_id = long(user_id)
            else:
                raise InvalidUsage('user_id is not a valid number, Given: %s' %
                                   user_id)

        social_network_id = request.args.get('social_network_id')
        if social_network_id:
            if social_network_id.isdigit():
                social_network_id = long(social_network_id)
            else:
                raise InvalidUsage(
                    'social_network_id is not a valid number, Given: %s' %
                    social_network_id)
        query = Event.get_events_query(
            request.user,
            search=search,
            sort_type=sort_type,
            sort_by=sort_by,
            user_id=user_id,
            social_network_id=social_network_id,
            is_deleted_from_vendor=is_deleted_from_vendor)
        results = query.paginate(per_page=per_page, page=page)
        events = map(add_organizer_venue_data, results.items)
        headers = generate_pagination_headers(results.total, per_page, page)
        if events:
            return ApiResponse(response=dict(events=events), headers=headers)
        else:
            return ApiResponse(headers=headers, response=dict(events=[]))
Esempio n. 24
0
    def get_attendee(self, rsvp):
        """
        :param dict rsvp: is likely the response from social network API.
        :return: attendee
        :rtype: Attendee

        rsvp object looks like
            {
                u'profile':
                    {
                        u'first_name': u'Muhammad', u'last_name': u'Basit',
                        u'addresses': {
                                        u'home': {}, u'ship': {}, u'work': {}, u'bill': {}
                                       },
                        u'email': u'*****@*****.**', u'name': u'Muhammad Basit'
                    },
                u'status': u'Attending',
                u'checked_in': False,
                u'created': u'2016-11-23T12:03:40Z',
                u'event_id': u'29640427316',
                u'refunded': False,
                u'changed': u'2016-11-23T12:03:40Z',
                u'ticket_class_name': u'Early Bird',
                u'answers': [],
                u'cancelled': False,
                u'costs': {
                            u'payment_fee': {
                                            u'currency': u'USD', u'display': u'$0.00', u'value': 0,
                                            u'major_value': u'0.00'
                                        },
                            u'gross':   {
                                        u'currency': u'USD', u'display': u'$0.00', u'value': 0, u'major_value':
                                        u'0.00'
                                        },
                            u'eventbrite_fee': {
                                            u'currency': u'USD', u'display': u'$0.00', u'value': 0,
                                            u'major_value': u'0.00'
                                            },
                            u'tax': {
                                    u'currency': u'USD', u'display': u'$0.00', u'value': 0, u'major_value':
                                    u'0.00'
                                    },
                            u'base_price': {
                                            u'currency': u'USD', u'display': u'$0.00', u'value': 0,
                                            u'major_value': u'0.00'
                                            }
                            },
                u'affiliate': None,
                u'team': None,
                u'barcodes':
                            [
                                {
                                    u'status': u'unused', u'barcode': u'574038679721387572001',
                                    u'checkin_type': 0, u'changed': u'2016-11-23T12:03:40Z',
                                    u'created': u'2016-11-23T12:03:40Z'
                                }
                            ],
                u'ticket_class_id': u'58034349',
                u'quantity': 1,
                u'order_id': u'574038679',
                u'id': u'721387572',
                u'resource_uri': u'https://www.eventbriteapi.com/v3/events/29640427316/attendees/721387572/'
            }

        - This function is used to get the data of candidate related to given rsvp. It attaches all the information
          in attendee object. attendees is a utility object we share in calls that contains pertinent data.

        - This method is called from process_rsvps() defined in RSVPBase class.

        :Example:

            attendee = self.get_attendee(rsvp)

        **See Also**
            .. seealso:: process_rsvps() method in RSVPBase class inside social_network_service/rsvp/base.py
        """
        if not self.rsvp_via_importer:
            return self.get_attendee_for_rsvp_via_webhook(rsvp)
        # get event_id
        social_network_event_id = rsvp['event_id']
        event = Event.get_by_user_id_social_network_id_vendor_event_id(
            self.user.id, self.social_network.id, social_network_event_id)
        if not event:
            logger.info(
                'Event is not present in db, social_network_event_id is %s. User Id: %s'
                % (social_network_event_id, self.user.id))
            return None

        created_datetime = datetime.strptime(rsvp['created'][:19],
                                             "%Y-%m-%dT%H:%M:%S")
        attendee = Attendee()
        attendee.first_name = rsvp['profile']['first_name']
        attendee.full_name = rsvp['profile']['name']
        attendee.last_name = rsvp['profile']['last_name']
        attendee.added_time = created_datetime
        attendee.rsvp_status = 'yes' if rsvp['status'].lower(
        ) == 'attending' else rsvp['status']
        attendee.email = rsvp['profile']['email']
        attendee.vendor_rsvp_id = rsvp['id']
        attendee.gt_user_id = self.user.id
        attendee.social_network_id = self.social_network.id
        attendee.vendor_img_link = \
            "<img class='pull-right'" \
            " style='width:60px;height:30px' " \
            "src='/web/static/images/activities/eventbrite_logo.png'/>"
        # Save profile url of candidate to save
        attendee.social_profile_url = rsvp['resource_uri']
        attendee.event = event
        return attendee
Esempio n. 25
0
    def get_attendee(self, rsvp):
        """
        :param rsvp: rsvp is likely the response of social network API.
        :type rsvp: dict
        :return: attendee
        :rtype: object

        - This function is used to get the data of candidate related
          to given rsvp. It attaches all the information in attendee object.
          attendees is a utility object we share in calls that contains
          pertinent data.

        - This method is called from process_rsvps() defined in RSVPBase class.

        :Example:

            attendee = self.get_attendee(rsvp)

        - RSVP data return from Meetup looks like

        In case of RSVPs importer:

        {
            'group': {
                        'group_lat': 24.860000610351562,
                        'created': 1439953915212,
                        'join_mode': 'open',
                        'group_lon': 67.01000213623047,
                        'urlname': 'Meteor-Karachi',
                        'id': 17900002
                    },
            'created': 1438040123000,
            'rsvp_id': 1562651661,
            'mtime': 1438040194000,
            'event': {
                        'name': 'Welcome to Karachi - Meteor',
                        'id': '223588917'
                        'event_url': 'http://www.meetup.com/Meteor-Karachi/events/223588917/',
                        'time': 1440252000000,
                    },
            'member': {
                        'name': 'kamran',
                        'member_id': 190405794
                    },
            'guests': 1,
            'member_photo':
                    {
                        'thumb_link': 'http://photos3.meetupstatic.com/photos/member/c/b/1/0/thumb_248211984.jpeg',
                        'photo_id': 248211984,
                        'highres_link': 'http://photos3.meetupstatic.com/photos/member/c/b/1/0/highres_248211984.jpeg',
                        'photo_link': 'http://photos3.meetupstatic.com/photos/member/c/b/1/0/member_248211984.jpeg'
                    },
            'response': 'yes'
            }

        From streaming API:

        {
            u'group': {
                    u'group_city': u'Denver',
                    u'group_lat': 39.68,
                    u'group_urlname': u'denver-metro-chadd-support',
                    u'group_name': u'Denver-Metro CHADD (Children and Adults with ADHD) Meetup',
                    u'group_lon': -104.92,
                    u'group_topics': [
                                        {u'topic_name': u'ADHD', u'urlkey': u'adhd'},
                                        {u'topic_name': u'ADHD Support', u'urlkey': u'adhd-support'},
                                        {u'topic_name': u'Adults with ADD', u'urlkey': u'adults-with-add'},
                                        {u'topic_name': u'Families of Children who have ADD/ADHD',
                                            u'urlkey': u'families-of-children-who-have-add-adhd'},
                                        {u'topic_name': u'ADHD, ADD', u'urlkey': u'adhd-add'},
                                        {u'topic_name': u'ADHD Parents with ADHD Children',
                                            u'urlkey': u'adhd-parents-with-adhd-children'},
                                        {u'topic_name': u'Resources for ADHD', u'urlkey': u'resources-for-adhd'},
                                        {u'topic_name': u'Parents of Children with ADHD',
                                            u'urlkey': u'parents-of-children-with-adhd'},
                                        {u'topic_name': u'Support Groups for Parents with ADHD Children',
                                            u'urlkey': u'support-groups-for-parents-with-adhd-children'},
                                        {u'topic_name': u'Educators Training on AD/HD',
                                            u'urlkey': u'educators-training-on-ad-hd'},
                                        {u'topic_name': u'Adults with ADHD', u'urlkey': u'adults-with-adhd'}
                                    ],
                    u'group_state': u'CO', u'group_id': 1632579, u'group_country': u'us'
                },
        u'rsvp_id': 1639776896,
        u'venue': {u'lat': 39.674759, u'venue_id': 3407262, u'lon': -104.936317,
                   u'venue_name': u'Denver Academy-Richardson Hall'},
        u'visibility': u'public',
        u'event': {
                        u'event_name': u'Manage the Impact of Technology on Your Child and Family with Lana Gollyhorn',
                        u'event_id': u'235574682',
                        u'event_url': u'https://www.meetup.com/denver-metro-chadd-support/events/235574682/',
                        u'time': 1479778200000
                   },
        u'member': {
                    u'member_name': u'Valerie Brown',
                    u'member_id': 195674019
                    },
        u'guests': 0,
        u'mtime': 1479312043215,
        u'response': u'yes'
        }


        In both cases, we get info of attendee from Meetup API and response looks like

        {
            u'status': u'active',
            u'city': u'Horsham',
            u'name': u'Katalin Nimmerfroh',
            u'other_services': {},
            u'country': u'gb',
            u'topics': [
                        {u'name': u'Musicians', u'urlkey': u'musicians', u'id': 173},
                        {u'name': u'Acting', u'urlkey': u'acting', u'id': 226}
                    ],
            u'lon': -0.33,
            u'joined': 1456995423000,
            u'id': 200820968,
            u'state': u'P6',
            u'link': u'http://www.meetup.com/members/200820968',
            u'photo': {
                    u'thumb_link': u'http://photos2.meetupstatic.com/photos/member/4/f/f/9/thumb_254420473.jpeg',
                    u'photo_id': 254420473,
                    u'highres_link': u'http://photos2.meetupstatic.com/photos/member/4/f/f/9/highres_254420473.jpeg',
                    u'base_url': u'http://photos2.meetupstatic.com',
                    u'type': u'member',
                    u'photo_link': u'http://photos4.meetupstatic.com/photos/member/4/f/f/9/member_254420473.jpeg'
                    },
            u'lat': 51.07,
            u'visited': 1472805623000,
            u'self': {u'common': {}}}


        - So we will get the member data and issue a member call to get more info about member so we can later save
            him as a candidate.

        **See Also**
            .. seealso:: process_rsvps() method in RSVPBase class inside social_network_service/rsvp/base.py
            for more insight.
        """
        if self.rsvp_via_importer:
            social_network_event_id = rsvp['event']['id']
        else:
            social_network_event_id = rsvp['event']['event_id']
        event = Event.get_by_user_id_social_network_id_vendor_event_id(self.user.id, self.social_network.id,
                                                                       social_network_event_id)
        if not event:
            raise EventNotFound('Event is not present in db, social_network_event_id is %s. '
                                'User Id: %s' % (social_network_event_id, self.user.id))

        member_url = self.api_url + '/member/' + str(rsvp['member']['member_id'])
        # Sleep for 10 / 30 seconds to avoid throttling
        time.sleep(0.34)
        response = http_request('GET', member_url, headers=self.headers, user_id=self.user.id)
        if response.ok:
            data = response.json()
            attendee = Attendee()
            attendee.first_name = data['name'].split(" ")[0]
            if len(data['name'].split(" ")) > 1:
                attendee.last_name = data['name'].split(" ")[1]
            else:
                attendee.last_name = ' '
            attendee.full_name = data['name']
            attendee.city = data['city']
            attendee.email = ''  # Meetup API does not expose this
            attendee.country = data['country']
            attendee.social_profile_url = data['link']
            # attendee.picture_url = data['photo']['photo_link']
            attendee.gt_user_id = self.user.id
            attendee.social_network_id = self.social_network.id
            attendee.rsvp_status = rsvp['response']
            attendee.vendor_rsvp_id = rsvp['rsvp_id']
            # TODO: This won't work now, need to figure out a way
            attendee.vendor_img_link = "<img class='pull-right' " \
                                       "style='width:60px;height:30px'" \
                                       " src='/web/static/images" \
                                       "/activities/meetup_logo.png'/>"
            # get event from database
            epoch_time = rsvp['mtime']
            dt = milliseconds_since_epoch_to_dt(epoch_time)
            attendee.added_time = dt
            attendee.event = event
            return attendee
Esempio n. 26
0
    def get_attendee(self, rsvp):
        """
        :param rsvp: rsvp is likely the response of social network API.
        :type rsvp: dict
        :return: attendee
        :rtype: object

        - This function is used to get the data of candidate related
          to given rsvp. It attaches all the information in attendee object.
          attendees is a utility object we share in calls that contains
          pertinent data.

        - This method is called from process_rsvps() defined in
          RSVPBase class.

        :Example:

            attendee = self.get_attendee(rsvp)

        **See Also**
            .. seealso:: process_rsvps() method in RSVPBase class inside
            social_network_service/rsvp/base.py for more insight.
        """
        try:
            data = self.graph.get_object('v2.4/' + rsvp['id'],
                                         fields='first_name, last_name, name, '
                                         'email, location, address, '
                                         'link, picture')
        except facebook.GraphAPIError:
            logger.exception(
                "get_attendee: Couldn't get Facebook's attendee info. "
                "user_id: %s, social_network_rsvp_id: %s" %
                (self.user.id, rsvp['id']))
            raise
        if 'location' in data:
            try:
                location = self.graph.get_object('v2.4/' +
                                                 data['location']['id'],
                                                 fields='location')
            except facebook.GraphAPIError:
                logger.exception(
                    "get_attendee: Couldn't get location info (Facebook). "
                    "user_id: %s, social_network_rsvp_id: %s" %
                    (self.user.id, rsvp['id']))
                raise
            if 'location' in location:
                location = location['location']
        else:
            location = {}
        if data:
            try:
                attendee = Attendee()
                attendee.first_name = data.get('first_name', '')
                attendee.last_name = data.get('last_name', '')
                attendee.full_name = data.get('name', '')
                attendee.email = data.get('email', '')
                attendee.city = location.get('city', '')
                attendee.country = location.get('country', '')
                attendee.latitude = location.get('latitude')
                attendee.longitude = location.get('longitude')
                attendee.zip = location.get('zip')
                attendee.social_profile_url = data.get('link', '')
                attendee.picture_url = data['picture']['data']['url'] \
                    if 'picture' in data and 'data' in data['picture']\
                       and 'url' in data['picture']['data'] else ''
                attendee.gt_user_id = self.user.id
                attendee.social_network_id = self.social_network.id
                # we are using profile_id here as we don't have any
                # rsvp_id for this vendor.
                attendee.vendor_rsvp_id = rsvp['id']
                # We do not have 'time' of rsvp from Facebook API response.
                # We cannot use datetime.now() here because every time we run
                # importer, we will have duplicate candidates as their added
                # time will not be same as the added time of previous record.
                # So for now, we are saving it as blank.
                attendee.added_time = ' '
                attendee.vendor_img_link = \
                    "<img class='pull-right' " \
                    "style='width:60px;height:30px' " \
                    "src='/web/static/images/activities/facebook_logo.png'/>"
                social_network_event_id = rsvp['vendor_event_id']
                if rsvp['rsvp_status'].strip() == 'attending' \
                        or rsvp['rsvp_status'].strip() == 'maybe':
                    attendee.rsvp_status = 'yes'
                else:
                    attendee.rsvp_status = 'no'
                event = Event.get_by_user_id_social_network_id_vendor_event_id(
                    self.user.id, self.social_network.id,
                    social_network_event_id)
                if event:
                    attendee.event = event
                    return attendee
                else:
                    raise EventNotFound(
                        'Event is not present in db, '
                        'social_network_event_id is '
                        '%s. User Id: %s' %
                        (social_network_event_id, self.user.id))
            except Exception:
                raise
Esempio n. 27
0
def delete_events(user_id, event_ids):
    """
    This utility function takes a list of event ids and id of user who owns the events.
    This function first create a mappings dictionary for which looks like this

            social_networks = {
                    # keys are Ids, and values are corresponding Social Network object and event ids
                    "13" : {
                              "event_obj": Meetup obj,
                              "event_ids" : [1,2,4]
                            },
                    "18" : {
                              "event_obj": Eventbrite obj,
                              "event_ids" : [33,45]
                            }

                }
    We then iterate this dictionary and call delete_events() method on respective social
     network objects.

    :param user_id:
    :param event_ids:
    :return: deleted(events that have been deleted), not_deleted (events that weren't deleted)
    :rtype: tuple (list, list)
    """
    assert len(event_ids) > 0, 'event_ids should contain at least one event id'
    # dictionary for mappings
    social_networks = {}
    # list for event id that are deleted successfully and that were not delete due to any reason
    deleted, not_deleted = [], []
    # iterate through all event ids
    for event_id in event_ids:
        # get event from database for this user and event id
        event = Event.get_by_user_and_event_id(user_id, event_id)
        # if event was not found then it means that, either this event does not exists at all
        # or this user does not create that event, so he is not allowed to get that so push this
        # event id in not_delete list.
        if event and not event.is_deleted_from_vendor:
            # get social network from event
            social_network = event.social_network
            # social network id is already in mapping dictionary then just add this event id in
            # its specific event ids list otherwise create a new dictionary with
            #  social_network id as key
            # and set social network object and ids list for events
            if social_network.id not in social_networks:
                # get social network and event management class for this social network
                social_network_class = get_class(social_network.name.lower(),
                                                 'social_network')
                event_class = get_class(social_network.name.lower(), 'event')
                sn = social_network_class(user_id=user_id,
                                          social_network_id=social_network.id)
                event_obj = event_class(user=sn.user,
                                        social_network=social_network,
                                        headers=sn.headers)
                social_networks[social_network.id] = dict(event_obj=event_obj,
                                                          event_ids=[event_id])
            else:
                social_networks[social_network.id]['event_ids'].append(
                    event_id)
        else:
            # if event was not found, put this id in not_deleted list
            not_deleted.append(event_id)

    for social_network_id, social_network in social_networks.items():
        # get event object from mapping dictionary and invoke delete_events on this to
        #  unpublish / remove
        # social network specific actions
        event_obj = social_network['event_obj']
        successful, unsuccessful = event_obj.delete_events(
            social_network['event_ids'])
        deleted.extend(successful)
        not_deleted.extend(unsuccessful)

    return deleted, not_deleted
Esempio n. 28
0
def process_event(data, user_id, method='Create'):
    """
    This functions is called from restful POST service (which gets data from
    Event Create Form submission).
    It creates event on vendor as well as saves in database.
    Data in the arguments is the Data coming from Event creation form submission
    user_id is the id of current logged in user (which we get from session).
    :return: id of event
    :rtype: int
    """
    if data:
        social_network_id = data.get('social_network_id', 0)
        social_network = SocialNetwork.get(social_network_id)
        if social_network:
            # creating class object for respective social network
            social_network_class = get_class(social_network.name.lower(),
                                             'social_network')
            event_class = get_class(social_network.name.lower(), 'event')
            sn = social_network_class(user_id=user_id)
            event_obj = event_class(user=sn.user,
                                    headers=sn.headers,
                                    social_network=social_network)
        else:
            raise SocialNetworkError('Unable to find social network')
        data['user_id'] = user_id
        if social_network.name.lower() == MEETUP and data.get('organizer_id'):
            raise InvalidUsage(
                'organizer_id is not a valid field in case of meetup')
        event_obj.event_gt_to_sn_mapping(data)

        activity_data = {'username': request.user.name}

        if method == 'Create':
            event_id = event_obj.create_event()

            # Create activity of event object creation
            event_obj = Event.get_by_user_and_event_id(user_id=user_id,
                                                       event_id=event_id)
            activity_data.update({'event_title': event_obj.title})
            add_activity(user_id=user_id,
                         activity_type=Activity.MessageIds.EVENT_CREATE,
                         source_id=event_id,
                         source_table=Event.__tablename__,
                         params=activity_data)
            return event_id
        else:
            event_id = event_obj.update_event()

            # Create activity of event object creation
            event_obj = Event.get_by_user_and_event_id(user_id=user_id,
                                                       event_id=event_id)

            activity_data.update({'event_title': event_obj.title})

            add_activity(user_id=user_id,
                         activity_type=Activity.MessageIds.EVENT_UPDATE,
                         source_id=event_id,
                         source_table=Event.__tablename__,
                         params=activity_data)

            return event_id
    else:
        error_message = 'Data not received from Event Creation/Edit FORM'
        log_error({'user_id': user_id, 'error': error_message})
Esempio n. 29
0
    def event_sn_to_gt_mapping(self, event):
        """
        We take event's data from social network's API and map its fields to
        getTalent database fields. Finally we return Event's object to
        save/update record in getTalent database.
        We also issue some calls to get updated venue and organizer information.
        :param event: data from Facebook API.
        :type event: dictionary
        :exception Exception: It raises exception if there is an error getting
            data from API.
        :return: event: Event object
        :rtype event: common.models.event.Event
        """
        venue = None
        location = None
        venue_id = None
        organizer = None
        organizer_id = None
        assert event is not None
        owner = event.get('owner')
        if event.get('place'):
            venue = event.get('place')
            location = venue['location']
            try:
                organizer = self.graph.get_object('v2.4/' + owner['id'])
                organizer = organizer.get('data')
            except facebook.GraphAPIError:
                logger.exception(
                    'event_sn_to_gt_mapping: Getting data of organizer. '
                    'user_id: %s, social_network_event_id: %s' %
                    (self.user.id, event['id']))
                raise
        if owner or organizer:
            organizer_data = dict(
                user_id=self.user.id,
                name=owner['name'] if owner and owner.has_key('name') else '',
                email=organizer['email']
                if organizer and organizer.has_key('email') else '',
                about='')
            organizer_in_db = EventOrganizer.get_by_user_id_and_name(
                self.user.id,
                owner['name'] if owner and owner.has_key('name') else '')

            if organizer_in_db:
                organizer_in_db.update(**organizer_data)
                organizer_id = organizer_in_db.id
            else:
                organizer_instance = EventOrganizer(**organizer_data)
                EventOrganizer.save(organizer_instance)
                organizer_id = organizer_instance.id

        if venue:
            venue_data = dict(
                social_network_venue_id=venue['id'],
                user_id=self.user.id,
                address_line_1=location['street']
                if location.has_key('street') else '',
                address_line_2='',
                city=location['city'].title()
                if location.has_key('city') else '',
                state='',
                zip_code=location['zip'] if location.has_key('zip') else None,
                country=location['country'].title()
                if location.has_key('country') else '',
                longitude=float(location['longitude'])
                if location.has_key('longitude') else 0,
                latitude=float(location['latitude'])
                if location.has_key('latitude') else 0,
            )
            venue_in_db = Venue.get_by_user_id_and_social_network_venue_id(
                self.user.id, venue['id'])
            if venue_in_db:
                venue_in_db.update(**venue_data)
                venue_id = venue_in_db.id
            else:
                venue = Venue(**venue_data)
                Venue.save(venue)
                venue_id = venue.id
        try:
            event = Event(social_network_event_id=event['id'],
                          title=event['name'],
                          description=event.get('description', ''),
                          social_network_id=self.social_network.id,
                          user_id=self.user.id,
                          organizer_id=organizer_id,
                          venue_id=venue_id,
                          social_network_group_id=0,
                          start_datetime=event.get('start_time'),
                          end_datetime=event.get('end_time'),
                          timezone=event.get('timezone'),
                          registration_instruction='',
                          cost=0,
                          currency='',
                          max_attendees=event['attending_count'] +
                          event['maybe_count'] + event['noreply_count'] if
                          (event and event.has_key('attending_count')
                           and event.has_key('maybe_count')
                           and event.has_key('noreply_count')) else '')
        except:
            logger.exception('event_sn_to_gt_mapping: user_id: %s, '
                             'social_network_event_id: %s' %
                             (self.user.id, event['id']))
        else:
            return event