Ejemplo n.º 1
0
    def __init__(self):
        self.REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
        self.ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
        self.AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
        self.SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'

        self.config = BarkConfig(None)
Ejemplo n.º 2
0
 def __init__(self, api):
     self.api = api
     self.renderer = Render()
     self.config = BarkConfig(None)
     self.logger = BarkLogger(__file__)
     self.tweets = []
     self.printed_lines = 0
     self.progress = None
Ejemplo n.º 3
0
    def main(self):
        bark_consumer = BarkConsumer()
        pin_auth = PinAuthentication()
        bark_config = BarkConfig(None)
        if bark_consumer.CONSUMER_KEY == None:
            CONSUMER_KEY = bark_config.get_value('API', 'consumer_key')
        else:
            CONSUMER_KEY = bark_consumer.CONSUMER_KEY

        if bark_consumer.CONSUMER_SECRET == None:
            CONSUMER_SECRET = bark_config.get_value('API', 'consumer_secret')
        else:
            CONSUMER_SECRET = bark_consumer.CONSUMER_SECRET

        if bark_config.get_value('API', 'access_token') == None:
            #TODO: Request access tokens with pin based auth
            pin_auth.get_access_token(CONSUMER_KEY, CONSUMER_SECRET)
            ACCESS_TOKEN = bark_config.get_value('API', 'access_token')
            ACCESS_TOKEN_SECRET = bark_config.get_value(
                'API', 'access_token_secret')
        else:
            ACCESS_TOKEN = bark_config.get_value('API', 'access_token')
            ACCESS_TOKEN_SECRET = bark_config.get_value(
                'API', 'access_token_secret')

        api = twitter.Api(consumer_key=CONSUMER_KEY,
                          consumer_secret=CONSUMER_SECRET,
                          access_token_key=ACCESS_TOKEN,
                          access_token_secret=ACCESS_TOKEN_SECRET)
        bark = BarkCurses(api)
        curses.wrapper(bark.main)
Ejemplo n.º 4
0
class PinAuthentication:
    def __init__(self):
        self.REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
        self.ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
        self.AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
        self.SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'

        self.config = BarkConfig(None)

    def get_access_token(self, consumer_key, consumer_secret):
        oauth_client = OAuth1Session(consumer_key,
                                     client_secret=consumer_secret,
                                     callback_uri='oob')

        print('\nRequesting temp token from Twitter...\n')

        resp = oauth_client.fetch_request_token(self.REQUEST_TOKEN_URL)

        url = oauth_client.authorization_url(self.AUTHORIZATION_URL)

        print(
            'I will try to start a browser to visit the following Twitter page '
            'if a browser will not start, copy the URL to your browser '
            'and retrieve the pincode to be used '
            'in the next step to obtaining an Authentication Token: \n'
            '\n\t{0}'.format(url))

        webbrowser.open(url)
        pincode = input('\nEnter your pincode? ')

        print('\nGenerating and signing request for an access token...\n')

        oauth_client = OAuth1Session(
            consumer_key,
            client_secret=consumer_secret,
            resource_owner_key=resp.get('oauth_token'),
            resource_owner_secret=resp.get('oauth_token_secret'),
            verifier=pincode)
        try:
            resp = oauth_client.fetch_access_token(self.ACCESS_TOKEN_URL)
        except ValueError as e:
            raise 'Invalid response from Twitter requesting temp token: {0}'.format(
                e)

        self.config.set_value('API', 'access_token', resp.get('oauth_token'))
        self.config.set_value('API', 'access_token_secret',
                              resp.get('oauth_token_secret'))
        print('''Your tokens/keys are as follows:
            access_token_key     = {atk}
            access_token_secret  = {ats}'''.format(
            atk=resp.get('oauth_token'), ats=resp.get('oauth_token_secret')))
Ejemplo n.º 5
0
    def __init__(self, filename):
        config = BarkConfig(None)
        self.logger = logging.getLogger(filename)

        #Allow overriding the log file- Mainly used for testing
        if config.get_value('LOGGING', 'logfile') != None:
            hdlr = logging.FileHandler(config.get_value('LOGGING', 'logfile'))
        else:
            hdlr = logging.FileHandler('bark.log')

        formatter = logging.Formatter('%(asctime)s ' +
                                      os.path.basename(filename) +
                                      ' %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        if config.get_value('LOGGING', 'loglevel') == 'debug':
            self.logger.setLevel(logging.DEBUG)
        elif config.get_value('LOGGING', 'loglevel') == 'error':
            self.logger.setLevel(logging.ERROR)
        else:
            self.logger.setLevel(logging.INFO)
Ejemplo n.º 6
0
class BarkCurses:
    def __init__(self, api):
        self.api = api
        self.renderer = Render()
        self.config = BarkConfig(None)
        self.logger = BarkLogger(__file__)
        self.tweets = []
        self.printed_lines = 0
        self.progress = None

    def main(self, stdscr):
        terminal_size = shutil.get_terminal_size()
        self.terminal_width = terminal_size[0]
        self.terminal_height = terminal_size[1]

        # Clear screen
        stdscr.clear()

        #Create the timeline window
        self.timeline_win = self.create_timeline_win()

        #Create the Prompt
        credentials = self.api.VerifyCredentials()
        prompt_win, prompt_width = self.create_prompt_win(
            credentials.screen_name)
        prompt_win.refresh()

        #Create Input window
        edit_line_win = self.create_edit_line_win(prompt_width)
        box = Textbox(edit_line_win, self)
        box.stripspaces = 1

        #Refresh tweets and start loop
        self.do_refresh()
        while True:
            message = box.edit(validate=self.validate_input)
            edit_line_win.clear()
            self.handle_command(message)

    def create_timeline_win(self):
        return curses.newpad(2000, self.terminal_width)

    def create_prompt_win(self, username):
        prompt_width = len(username) + 4
        prompt_win = curses.newwin(1, prompt_width, self.terminal_height - 1,
                                   0)
        prompt_win.addstr('[@' + username + ']')
        return prompt_win, prompt_width

    def create_edit_line_win(self, prompt_width):
        win = curses.newwin(1, self.terminal_width, self.terminal_height - 1,
                            prompt_width)
        return win

    def validate_input(self, char):
        if char == 338:
            self.do_page_down()
        elif char == 339:
            self.do_page_up()
        return char

    def handle_command(self, message):
        if len(message) > 0:
            command_words = message.split()
            command = command_words[0].lower()
            self.logger.debug('Got Command: %s' % command)
            if command == "/refresh":
                self.do_refresh()
            elif command == "/tweet":
                self.do_tweet(command_words[1:])
            elif command == "/exit":
                sys.exit()
            else:
                self.logger.debug('unknown command')
        else:
            self.logger.debug('Empty command')

    def do_page_up(self):
        self.logger.debug('Doing Page Up %d' % self.scroll_current)
        scroll_new = self.scroll_current - (self.terminal_height)
        if scroll_new < 0:
            scroll_new = 0
        self.scroll_to(scroll_new)

    def do_page_down(self):
        scroll_max = self.printed_lines - (self.terminal_height) + 1
        self.logger.debug('Doing Page Down %d' % self.scroll_current)
        scroll_new = self.scroll_current + (self.terminal_height)
        if scroll_new > scroll_max:
            scroll_new = scroll_max
        self.scroll_to(scroll_new)

    def do_tweet(self, words):
        tweet_message = ''
        for word in words:
            tweet_message = tweet_message + word + ' '

        if self.config.get_value('CONFIGURATION',
                                 'simulate_tweeting') == 'false':
            self.api.PostUpdate(tweet_message.strip())
        else:
            self.logger.info('Would have tweeted: |%s|' %
                             tweet_message.strip())

    def do_refresh(self):
        self.logger.debug('REFRESH: progress = %s' % self.progress)
        time_line_statuses = self.api.GetHomeTimeline(count=100,
                                                      since_id=self.progress)

        #Set the column width of the Time Column
        time_column_width = 9

        #Set the column width of the Username Column
        if time_line_statuses is not None:
            usernames = []
            for tweet in self.tweets:
                usernames.append(tweet['username'])
            for status in time_line_statuses:
                usernames.append(status.user.screen_name)

            username_column_width = self.renderer.get_longest_username(
                usernames)

        #Set the column width of the Text Column
        text_column_width = self.terminal_width - username_column_width - 12

        #Build the rendered tweet objects
        for status in reversed(time_line_statuses):
            tweet = self.renderer.render_tweet(status, text_column_width)
            self.tweets.append(tweet)
            self.progress = tweet['id']

        self.timeline_win.clear()
        self.printed_lines = self.print_tweets(time_column_width,
                                               username_column_width,
                                               self.tweets)
        self.scroll_to(self.printed_lines - (self.terminal_height) + 1)

    def scroll_to(self, row):
        self.scroll_current = row
        pminrow = self.scroll_current
        pmincol = 0
        sminrow = 0
        smincol = 0
        smaxrow = self.terminal_height - 2
        smaxcol = self.terminal_width
        self.logger.debug(
            'PAD REFRESH: pminrow = %d, pmincol = %d, sminrow = %d, smincol = %d, smaxrow = %d, smaxcol = %d'
            % (pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol))
        self.logger.debug('printed = %d' % self.printed_lines)
        if pminrow >= 0 and pminrow < self.printed_lines:
            self.timeline_win.refresh(pminrow, pmincol, sminrow, smincol,
                                      smaxrow, smaxcol)

    def print_tweets(self, time_column_width, username_column_width, tweets):
        first_column_width = time_column_width + username_column_width + 2
        printed_lines = 0
        for tweet in tweets:
            self.timeline_win.addstr(
                '%s %s | %s\n' %
                (tweet['time'], tweet['username'].rjust(username_column_width),
                 tweet['tweet_lines'][0]))
            printed_lines = printed_lines + 1
            for line in tweet['tweet_lines'][1:]:
                self.timeline_win.addstr('%s %s\n' %
                                         ('|'.rjust(first_column_width), line))
                printed_lines = printed_lines + 1
        return printed_lines
Ejemplo n.º 7
0
 def test_set_and_get(self):
     config = BarkConfig('test.conf')
     config.set_value('TEST', 'test', 'testvalue')
     assert config.get_value('TEST', 'test') == 'testvalue'
Ejemplo n.º 8
0
 def test_init(self):
     config = BarkConfig('test.conf')
     assert self.check_exists('test.conf') == True
     assert config.get_value('LOGGING', 'logfile') == 'bark.log'
     assert config.get_value('LOGGING', 'loglevel') == 'info'