コード例 #1
0
ファイル: views.py プロジェクト: rickeyski/causal
def verify_auth(request):
    """Handle the redirect from foursquare as part of the oauth process.
    """

    service = get_model_instance(request.user, PACKAGE)
    code = request.GET.get('code')

    url = "https://foursquare.com/oauth2/access_token?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s" % (service.app.auth_settings['consumer_key'], service.app.auth_settings['consumer_secret'], service.app.auth_settings['return_url'], code)

    access_token = get_url(url)

    if access_token.has_key('error'):
        messages.error(request, 'Unable to validate your with Foursquare, please wait a few minutes and retry.')
    else:
        at = AccessToken.objects.create(
            oauth_token = access_token["access_token"],
            oauth_token_secret = '',
            oauth_verify = ''
        )

        service.auth.access_token = at
        service.auth.save()

        service.setup = True
        service.public = True
        service.save()


    return redirect(settings_redirect(request))
コード例 #2
0
ファイル: views.py プロジェクト: causality/causal
def auth(request):
    """We dont need a full oauth setup just a username."""

    service = get_model_instance(request.user, PACKAGE_NAME)
    if service and request.method == 'POST':
        username = request.POST['username']

        if username:
            user_feed = get_url('http://feeds.delicious.com/v2/json/%s' % (username,))

            if username:
                # check the username is valid
                if user_feed[0]['d'] == '404 Not Found':
                    messages.error(request, 'Unable to find username "%s", please try again' % (username,))
                else:
                    if not service.auth:
                        auth_handler = Auth()
                    else:
                        auth_handler = service.auth
                    auth_handler.username = username
                    auth_handler.save()
                    if not service.auth:
                        service.auth = auth_handler
    
                    service.setup = True
                    service.public = True
                    service.save()
        else:
            messages.error(request, 'Please enter a Delicious username')

    return redirect(settings_redirect(request))
コード例 #3
0
ファイル: service.py プロジェクト: causality/causal
 def _convert_likes_feed(self, likes, since):
     """fetch using a cheeky url grab"""
     
     items = []
     
     # get info about the like:
     # https://graph.facebook.com/271847211041
     
     for like in likes['data']:
         
         if like.has_key('created_time'):
             created = self._convert_time_stamp(like['created_time'])
             
             if created.date() >= since:
                 
                 info_on_like = get_url('https://graph.facebook.com/%s' % (like['id']))
                 
                 item = ServiceItem()
                 item.created = created
                 
                 if like.has_key('name'):
                     item.title = like['name']
                     
                 if like.has_key('category'):    
                     item.body = like['category']
                     
                 item.link_back = info_on_like['link']
                 item.service = self.service
                 items.append(item)
         else:
             pass
     return items
コード例 #4
0
ファイル: service.py プロジェクト: causality/causal
    def get_items(self, since):
        """Get data too display for main page."""
        url = 'http://feeds.delicious.com/v2/json/%s?count=100' % (
            self.service.auth.username,
        )

        user_feed = get_url(url)
        if user_feed:
            return self._convert_feed(user_feed, since)
コード例 #5
0
ファイル: service.py プロジェクト: causality/causal
    def get_artists(self, since):
        """Get a users top artists.
        """

        fav_artists = get_url('http://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user=%s&api_key=%s&period=7day&format=json' % (
                self.service.auth.username,
                self.service.app.auth_settings['api_key']
            ))

        return self._convert_top_artists_json(fav_artists)
コード例 #6
0
ファイル: service.py プロジェクト: rickeyski/causal
    def get_items(self, since):
        """Fetch the history of checkins for the current user.
        """

        try:
            url = "https://api.foursquare.com/v2/users/self/checkins?oauth_token=%s" % (self.service.auth.access_token.oauth_token)
            checkins = get_url(url)
        except Exception, e:
            messages.error(request, "Unable to to contact Foursquare's servers, please wait a few minutes and retry or check http://status.foursquare.com.")
            raise LoggedServiceError(original_exception=e)
コード例 #7
0
ファイル: service.py プロジェクト: causality/causal
    def _set_title_body(self, entry, item):
        """Set the title and body based on the event type."""

        item.body = ''
        
        try:
            if entry['type'] == 'CreateEvent':
                if entry['payload'].has_key('object_name'):
                    item.title = "Created branch %s from %s" % (entry['payload']['object_name'], entry['payload']['name'])
                else:
                    if entry.has_key('repository'):
                        item.title = "Created branch %s from %s" % (entry['payload']['master_branch'], entry['repository']['name'])  
                    else:
                        item.title = "Created branch %s from %s" % (entry['payload']['master_branch'], entry['payload']['ref'])
            elif entry['type'] == 'GistEvent':
                item.title = "Created gist %s" % (entry['payload']['desc'])
            elif entry['type'] == 'IssuesEvent':
                url = 'https://github.com/%s/%s/issues/%s' % (
                    entry['repository']['owner'], 
                    entry['repository']['name'],
                    str(entry['payload']['number']))
                item.title = 'Issue <a href="%s">#%s</a> was %s.' % (url, str(entry['payload']['number']), entry['payload']['action'])
            elif entry['type'] == 'ForkEvent':
                item.title = "Repo %s forked." % (entry['repository']['name'])
            elif entry['type'] == 'PushEvent':
                if entry.has_key('repository'):
                    item.title = "Pushed to repo %s with comment \"%s\"." % (entry['repository']['name'], entry['payload']['shas'][0][2])
                else:
                    item.title = entry['url'].split('/')[4]
            elif entry['type'] == 'CreateEvent':
                item.title = "Branch %s for %s." % (entry['payload']['object_name'], entry['payload']['name'])
            elif entry['type'] == 'WatchEvent':
                item.title = "Started watching %s." % (entry['repository']['name'])
            elif entry['type'] == 'FollowEvent':
                item.title = "Started following %s." % (entry['payload']['target']['login'])
            elif entry['type'] == 'GistEvent':
                item.title = "Snippet: %s" % (entry['payload']['snippet'])
            elif entry['type'] == 'DeleteEvent':
                item.title = "Deleted: %s called %s" % (entry['payload']['ref_type'], entry['payload']['ref'])
            elif entry['type'] == 'GollumEvent':
                pass
            elif entry['type'] == 'IssueCommentEvent':
                comments = get_url('https://api.github.com/repos/%s/%s/issues/comments/%s' % (
                    entry['repository']['owner'], 
                    entry['repository']['name'],
                    entry['payload']['comment_id']
                ))
                item.title = '<b>Commented</b> "%s" on issue <a href="%s">%s</a>' % (comments['body'], entry['url'], entry['url'].split('#')[0].rsplit('/', 1)[1])
            elif entry['type'] == 'PullRequestEvent':
                item.title = "Created pull for %s" % (entry['repository']['name'])
            else:
                item.title = "Unknown Event!"
                
        except:
            item.title = "Unknown Event!"
コード例 #8
0
ファイル: service.py プロジェクト: causality/causal
 def _get_repos(self, since):
     """Fetch the repo list for a user."""
     
     repos_url = "https://api.github.com/user/repos?access_token=%s" % (self.service.auth.access_token.oauth_token)
     repos = get_url(repos_url)
     
     updated_repos = []
     for repo in repos:
         pushed = datetime.strptime(repo['pushed_at'], '%Y-%m-%dT%H:%M:%SZ')
         if pushed.date() > since:
             updated_repos.append(repo)
             
     return updated_repos
コード例 #9
0
ファイル: views.py プロジェクト: causality/causal
def auth(request):
    """We dont need a full oauth setup just a username.
    """
    service = get_model_instance(request.user, PACKAGE_NAME)
    if service and request.method == 'POST':
        username = request.POST['username']

        if username:
            user_feed = get_url('http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=%s&api_key=%s&format=json' % (
                                      username, service.app.auth_settings['api_key']))
            #user_feed = get_data(
                #service,
                #'http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=%s&api_key=%s&format=json'  % (
                    #username,
                    #service.app.auth_settings['api_key']
                #),
                #disable_oauth=True
            #)

            # check we have a valid username
            if user_feed.has_key('error'):
                messages.error(
                    request,
                    'Unable to validate your username "%s" with Last.fm, please check your username and retry.' % (
                    username,
                    )
                )
                return redirect(settings_redirect(request))
            
            if not service.auth:
                auth_handler = Auth()
            else:
                auth_handler = service.auth
            auth_handler.username = username
            auth_handler.save()
            if not service.auth:
                service.auth = auth_handler

            service.setup = True
            service.public = True
            service.save()

        else:
            messages.error(request, 'Please enter a Last.fm username')

    return redirect(settings_redirect(request))
コード例 #10
0
ファイル: views.py プロジェクト: causality/causal
def auth(request):
    """We dont need a full oauth setup just a username.
    """
    service = get_model_instance(request.user, PACKAGE_NAME)
    if service and request.method == 'POST':
        username = request.POST['username']

        if username:
            # Fetch the page and try to find the reader id
            url = "http://www.google.com/reader/shared/%s" % (username,)
            links = SoupStrainer('link')
            content = get_url(url, json=False)
            parsed_links = [tag for tag in soup(str(content), parseOnlyThese=links)]

            if parsed_links:
                try:
                    user_id = parsed_links[2].attrs[2][1].split('%2F')[1]

                    if not service.auth:
                        auth_handler = Auth()
                    else:
                        auth_handler = service.auth
                    auth_handler.username = username
                    auth_handler.secret = user_id
                    auth_handler.save()
                    if not service.auth:
                        service.auth = auth_handler

                    service.setup = True
                    service.public = True
                    service.save()
                except:
                    messages.error(
                        request,
                        'Unable to find Google Reader account with username "%s"' % (username,)
                    )
            else:
                messages.error(
                    request,
                    'Unable to find Google Reader account with username "%s"' % (username,)
                )
        else:
            messages.error(request, "Please enter a Google Reader username")

    return redirect(settings_redirect(request))
コード例 #11
0
ファイル: service.py プロジェクト: causality/causal
    def get_items(self, since):
        """Fetch and filter the updates from Last.fm.
        """

        tracks_listing = None

        try:
            t = datetime.now()
            url = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json&from=%s&to=%s&limit=%s' % (
                    self.service.auth.username,
                    self.service.app.auth_settings['api_key'],
                    str(int(mktime(since.timetuple()))),
                    str(int(mktime(t.timetuple()))),
                    MAX_RESULTS)
            tracks_listing = get_url(url)
            
        except Exception, exception:
            raise LoggedServiceError(original_exception = exception)
コード例 #12
0
ファイル: views.py プロジェクト: causality/causal
def verify_auth(request):
    """Handle reply from github"""
    """Take incoming request and validate it to create a valid AccessToken."""

    try:
        service = get_model_instance(request.user, PACKAGE)
        code = request.GET.get('code')
    
        if code:
            # swap our newly aquired code for a everlasting signed "token"
            reply = get_url('https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s' % (
                service.app.auth_settings['api_key'], 
                service.app.auth_settings['api_secret'], 
                code), json=False, method="POST", disable_ssl=True)
        
            if  not reply.startswith('access_token'):
                raise Exception('Token Failure')
            
            access, perm_type = reply.split('&')
            
            service.auth.access_token = AccessToken.objects.create(
                oauth_token = access.split('=')[1],
                oauth_token_secret = access.split('=')[1],
            )
            
            service.auth.save()
            
            # Mark as setup completed
            service.setup = True    
            service.save()

    except:
        messages.error(
            request,
            'Unable to validate your account with GitHub, please grant permission for gargoyle.me to access your account.'
        )

    return redirect(settings_redirect(request))
コード例 #13
0
ファイル: service.py プロジェクト: causality/causal
    def get_upcoming_gigs(self, since, artist=None):
        """Return a list of up coming gigs for the user.
        """

        items = []
        return 
        gigs = get_url(
            'http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist=%s&api_key=%s&format=json' % (
                artist.replace(' ', '+'),
                self.service.app.auth_settings['api_key']
            ))

        items = []

        if gigs and gigs.has_key('events') and gigs['events'].has_key('event') :
            for gig in gigs['events']['event']:
                item = ServiceItem()
                item.location = {}
                try:
                    if gig.has_key('venue') and \
                       gig['venue'].has_key('name') and \
                       gig.has_key('startDate'):
                        item.venue_name = gig['venue']['name']
                        item.event_url = gig['url']
                        item.date = datetime.strptime(gig['startDate'], '%a, %d %b %Y %H:%M:%S')

                        if gig['venue'].has_key('location') and \
                           gig['venue']['location'].has_key('geo:point'):
                            item.location['long'] = \
                                gig['venue']['location']['geo:point']['geo:long']
                            item.location['lat'] = \
                                gig['venue']['location']['geo:point']['geo:lat']

                        items.append(item)
                except:
                    pass
        return items