예제 #1
0
 def publish_event(self, social_network_event_id):
     """
     This function publishes the Event on Eventbrite.
     This event is public.
     :param social_network_event_id: id for event on eventbrite.com
     :type social_network_event_id: int
     :exception EventNotPublished: raises this exception when unable to
         publish event on Eventbrite.com
     """
     # create url to publish event
     url = get_url(self,
                   Urls.PUBLISH_EVENT).format(str(social_network_event_id))
     # params are None. Access token is present in self.headers
     response = http_request('POST',
                             url,
                             headers=self.headers,
                             user_id=self.user.id)
     if response.ok:
         logger.info('|  Event has been published  |')
     else:
         error_message = "Event was not Published. There are some " \
                         "errors: Details: %s  |" % response.text
         log_error({
             'user_id': self.user.id,
             'error': error_message,
         })
         raise EventNotPublished('ApiError: Unable to publish event '
                                 'on Eventbrite')
예제 #2
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)
예제 #3
0
    def add_venue_to_sn(self, venue_data):
        """
        This function sends a POST request to Meetup api to create a venue for event.
        :param dict venue_data: a dictionary containing data required to create a venue
        """
        if not venue_data.get('group_url_name'):
            raise InvalidUsage("Mandatory Input Missing: group_url_name",
                               error_code=custom_codes.MISSING_REQUIRED_FIELDS)
        url = get_url(self, SocialNetworkUrls.VENUES,
                      custom_url=MEETUP_VENUE).format(
                          venue_data['group_url_name'])
        payload = {
            'address_1': venue_data['address_line_1'],
            'address_2': venue_data.get('address_line_2'),
            'city': venue_data['city'],
            'country': venue_data['country'],
            'state': venue_data['state'],
            'name': venue_data['address_line_1']
        }
        # Sleep for 10 / 30 seconds to avoid throttling
        time.sleep(0.34)
        response = http_request('POST',
                                url,
                                params=payload,
                                headers=self.headers,
                                user_id=self.user.id)
        json_resp = response.json()
        if response.ok:
            venue_id = json_resp['id']
            logger.info('Venue has been Added. Venue Id: %s', venue_id)
        elif response.status_code == codes.CONFLICT:
            # 409 is returned when our venue is matching existing
            # venue/venues.
            try:
                match_id = json_resp['errors'][0]['potential_matches'][0]['id']
            except:
                raise InternalServerError('Invalid response from Meetup',
                                          error_code=INVALID_MEETUP_RESPONSE)
            venue = Venue.get_by_user_id_and_social_network_venue_id(
                self.user.id, match_id)
            if venue:
                raise InvalidUsage(
                    'Venue already exists in getTalent database',
                    additional_error_info=dict(id=venue.id),
                    error_code=VENUE_EXISTS_IN_GT_DATABASE)
            venue_id = json_resp['errors'][0]['potential_matches'][0]['id']
        else:
            raise InternalServerError(
                'ApiError: Unable to create venue for Meetup',
                additional_error_info=dict(venue_error=json_resp))

        venue_data['user_id'] = self.user.id
        venue_data['social_network_venue_id'] = venue_id
        return SocialNetworkBase.save_venue(venue_data)
예제 #4
0
    def manage_event_tickets(self, tickets_url):
        """
        Here tickets are created for event on Eventbrite.
        This method sends a POST request to Eventbrite.com API to create or
        update tickets. Call this method from create_tickets or update_tickets
        with respective tickets_url. It returns tickets id if successful
        otherwise raises "TicketsNotCreated" exception

        :param tickets_url  (API url to create or update event tickets)
        :type tickets_url: str
        :exception TicketsNotCreated (throws exception if unable to create or
            update tickets)
        :return: tickets_id (an id which refers to tickets for event on
            eventbrite.com)
        :rtype: str
        """
        # send POST request to create or update tickets for event
        response = http_request('POST',
                                tickets_url,
                                params=self.ticket_payload,
                                headers=self.headers,
                                user_id=self.user.id)
        if response.ok:
            logger.info(
                '|  %s Ticket(s) have been created  |' %
                str(self.ticket_payload['ticket_class.quantity_total']))
            tickets_id = response.json().get('id')
            return tickets_id
        else:
            error_message = 'Event tickets were not created successfully'
            log_error({
                'user_id': self.user.id,
                'error': error_message,
            })
            raise TicketsNotCreated('ApiError: Unable to create event tickets '
                                    'on Eventbrite')
예제 #5
0
    def refresh_access_token(self):
        """
        - When user authorizes Meetup account, we get a refresh token
            and access token. Access token expires in one hour.
            Here we refresh the access_token using refresh_token without user
            involvement and save in user_credentials db table.


        - This function is called from validate_and_refresh_access_token()
            defined in SocialNetworkBase class inside
            social_network_service/base.py

        :Example:
                from social_network_service.meetup import Meetup
                sn = Meetup(user_id=1)
                sn.refresh_access_token()

        **See Also**
        .. seealso:: validate_and_refresh_token() function defined in
            SocialNetworkBase class inside social_network_service/base.py.

        :return True if token has been refreshed successfully and False
                otherwise.
        :rtype: bool
        """
        status = False
        user_refresh_token = self.user_credentials.refresh_token

        auth_url = get_url(self, SocialNetworkUrls.REFRESH_TOKEN, is_auth=True)
        client_id = self.social_network.client_key
        client_secret = self.social_network.secret_key

        payload_data = {
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': u'refresh_token',
            'refresh_token': user_refresh_token
        }
        # Sleep for 10 / 30 seconds to avoid throttling
        time.sleep(0.34)
        response = http_request('POST',
                                url=auth_url,
                                data=payload_data,
                                user_id=self.user.id,
                                app=app)
        if response.ok:
            try:
                # access token has been refreshed successfully, need to update
                # self.access_token and self.headers
                response = response.json()
                self.access_token = response.get('access_token')
                self.headers.update(
                    {'Authorization': 'Bearer ' + self.access_token})
                refresh_token = response.get('refresh_token')
                UserSocialNetworkCredential.query.filter_by(social_network_id=self.social_network.id,
                                                            member_id=self.user_credentials.member_id).\
                    update({'access_token': self.access_token, 'refresh_token': refresh_token})
                db.session.commit()
                logger.info("Access token has been refreshed.")
                status = True
            except Exception:
                logger.exception('refresh_access_token: user_id: %s' %
                                 self.user.id)
        else:
            # Error has been logged inside http_request()
            pass
        return status
예제 #6
0
    def add_location(self):
        """
        This generates a venue object for the event and returns the
        id of venue.
        :exception EventLocationNotCreated: throws exception if unable to
            create or update venue on Eventbrite
        :exception VenueNotFound: raises exception if venue does not exist
            in database
        :return venue_id: id for venue created on eventbrite.com
        :rtype venue_id: int

            :Example:

                This method is used to create venue or location for event
                on Eventbrite. It requires a venue already created in getTalent
                database otherwise it will raise VenueNotFound exception.

                Given venue id it first gets venue from database and uses its
                data to create Eventbrite object

                >> eventbrite = Eventbrite(user=gt_user,
                                           headers=authentication_headers)

                Then we call add location from create event
                To get a better understanding see *create_event()* method.


        """
        # get venue from db which will be created on Eventbrite
        venue = Venue.get_by_user_id_social_network_id_venue_id(
            self.user.id, self.social_network.id, self.venue_id)
        if venue:
            if venue.social_network_venue_id:
                # there is already a venue on Eventbrite with this info.
                return venue.social_network_venue_id
            # This dict is used to create venue
            payload = {
                'venue.name': venue.address_line_1,
                'venue.address.address_1': venue.address_line_1,
                'venue.address.address_2': venue.address_line_2,
                'venue.address.region': venue.state,
                'venue.address.city': venue.city,
                # 'venue.address.country': venue.country,
                'venue.address.postal_code': venue.zip_code,
                'venue.address.latitude': venue.latitude,
                'venue.address.longitude': venue.longitude,
            }
            # create url to send post request to create venue
            url = get_url(self, Urls.VENUES)
            response = http_request('POST',
                                    url,
                                    params=payload,
                                    headers=self.headers,
                                    user_id=self.user.id)
            if response.ok:
                logger.info('|  Venue has been created  |')
                venue_id = response.json().get('id')
                venue.update(social_network_venue_id=venue_id)
                return venue_id
            else:
                error_message = "Venue was not Created. There are some " \
                                "errors: Details: %s " % response
                message = '\nErrors from the Social Network:\n'
                message += \
                    ''.join(response.json().get('error') + ','
                            + response.json().get('error_description'))
                error_message += message
                log_error({'error': error_message, 'user_id': self.user.id})
                raise EventLocationNotCreated(
                    'ApiError: Unable to create venue for event\n %s' %
                    message)
        else:
            error_message = 'Venue with ID = %s does not exist in db.' \
                            % self.venue_id
            log_error({
                'user_id': self.user.id,
                'error': error_message,
            })
            raise VenueNotFound('Venue not found in database. Kindly create'
                                ' venue first.')
예제 #7
0
    def update_event(self):
        """
        This function is used to update an event on Eventbrite.com
        It uses update_tickets() method to update number of tickets for this
         event

        :exception EventNotCreated: throws exception if unable to update event
         on Eventbrite.com)
        :return: id of event
        :rtype: int

            :Example:

                In order to updates event first create EventBrite object and it
                takes user and authentication headers e.g.

                >> eventbrite = Eventbrite(user=gt_user,
                                           headers=authentication_headers)

                Then call event_gt_to_sn_mapping() method on this object and
                pass it event dictionary.
                >> eventbrite.event_gt_to_sn_mapping(event_data)

                It will create event payload which is required to post event on
                Eventbrite.com.
                Now call update_event to update event on Eventbrite.com and in
                getTalent database.

                >> eventbrite.update_event()

                This method returns id of updated getTalent event.
        """
        # create url to update event
        url = get_url(
            self, Urls.EVENT).format(str(self.social_network_event_id) + '/')
        venue_id = self.add_location()  # adding venue for the event
        self.event_payload['event.venue_id'] = venue_id
        response = http_request('POST',
                                url,
                                params=self.event_payload,
                                headers=self.headers,
                                user_id=self.user.id)
        if response.ok:  # event has been updated on Eventbrite.com
            event_id = response.json()['id']
            # Ticket are going to be created/updated
            ticket_id = self.update_tickets(event_id)
            logger.info('|  Event %s updated Successfully  |' %
                        self.event_payload['event.name.html'])
            self.data['social_network_event_id'] = event_id
            self.data['tickets_id'] = ticket_id
            return self.save_event()
        else:
            error_message = 'Event was not updated Successfully'
            response = response.json()
            error_detail = response.get('error', '') + ': ' \
                           + response.get('error_description', '')
            if error_detail != ': ':
                error_message += '\n%s' % error_detail
            log_error({
                'user_id': self.user.id,
                'error': error_detail,
            })
            raise EventNotCreated(error_message)
예제 #8
0
    def create_event(self):
        """
        This function is used to post/create event on Eventbrite.com
        It uses create_tickets() method to allow user subscriptions and
        publish_event() to make it public
        :exception EventNotCreated: throws exception if unable to create
            event on Eventbrite.com
        :return: event_id, tickets_id: a tuple containing event_id on
            Eventbrite and tickets_id for this event

            :Example:

                In order to create event first create EventBrite object and it
                takes user and authentication headers e.g.

                >> eventbrite = Eventbrite(user=gt_user,
                                           headers=authentication_headers)

                Then call event_gt_to_sn_mapping() method on this object and
                 pass it event dictionary.
                >> eventbrite.event_gt_to_sn_mapping(event_data)

                It will create event payload which is required to post event on
                Eventbrite.com
                Now call create event to create event on Eventbrite.com

                >> eventbrite.create_event()

                This method returns id of getTalent event that was created on
                 Eventbrite.com as well.

        """
        # create url to post/create event on eventbrite.com
        url = get_url(self, Urls.EVENTS)
        # adding venue for the event or reuse if already created on
        # eventbrite.com
        venue_id = self.add_location()
        # add venue_id in event payload so it can be associated with this event
        # on eventbrite
        self.event_payload['event.venue_id'] = venue_id
        # create event on eventbrite by sending POST request
        response = http_request('POST',
                                url,
                                params=self.event_payload,
                                headers=self.headers,
                                user_id=self.user.id)
        if response.ok:
            # Event has been created on vendor and saved in draft there.
            # Now we need to create tickets for it and then publish it.
            event = response.json()
            event_id = event['id']
            # Ticket are going to be created/updated
            ticket_id = self.create_tickets(event_id)
            # Ticket(s) have been created for newly created Event
            if app.config[TalentConfigKeys.ENV_KEY] not in [
                    TalentEnvs.JENKINS
            ]:
                self.publish_event(event_id)
            logger.info('|  Event %s created Successfully  |' %
                        self.event_payload['event.name.html'])
            self.data['social_network_event_id'] = event_id
            self.data['tickets_id'] = ticket_id
            self.data['url'] = event['url']
            return self.save_event()
        else:
            error_message = 'Event was not created Successfully as draft'
            response = response.json()
            error_detail = response.get('error', '') + ': ' \
                           + response.get('error_description', '')
            if error_detail != ': ':
                error_message += '\n%s' % error_detail
            log_error({
                'user_id': self.user.id,
                'error': error_detail,
            })
            raise EventNotCreated(error_message)