← Back to team overview

cairo-dock-team team mailing list archive

[Merge] lp:~eduardo-mucelli/cairo-dock-plug-ins-extras/Twitter into lp:cairo-dock-plug-ins-extras

 

Eduardo Mucelli Rezende Oliveira has proposed merging lp:~eduardo-mucelli/cairo-dock-plug-ins-extras/Twitter into lp:cairo-dock-plug-ins-extras.

Requested reviews:
  Cairo-Dock Team (cairo-dock-team)

For more details, see:
https://code.launchpad.net/~eduardo-mucelli/cairo-dock-plug-ins-extras/Twitter/+merge/95911

Finally, after long work, compatible with Twitter Stream, and using it to show the tweets that just arrived. Changed the "received" icon for direct messages, and added the "new" for new tweets.
-- 
https://code.launchpad.net/~eduardo-mucelli/cairo-dock-plug-ins-extras/Twitter/+merge/95911
Your team Cairo-Dock Team is requested to review the proposed merge of lp:~eduardo-mucelli/cairo-dock-plug-ins-extras/Twitter into lp:cairo-dock-plug-ins-extras.
=== modified file 'Twitter/ChangeLog'
--- Twitter/ChangeLog	2012-01-29 18:20:33 +0000
+++ Twitter/ChangeLog	2012-03-05 14:58:31 +0000
@@ -1,3 +1,4 @@
+0.1: (March/5/2012): Finally, after long work, compatible with Twitter Stream, and using it to show the tweets that just arrived. Changed the "received" icon for direct messages, and added the "new" for new tweets, both are from the icon pack Basic made by Pixel Maker, http://pixel-mixer.com
 0.0.3: (January/14/2012): Possible to see user's info. Translation directives were added on the strings.
 0.0.2: (January/8/2012): Possible to see the received direct messages.
 0.0.1: (December/16/2011): Possible to send a tweety, and see the home timeline.

=== modified file 'Twitter/Twitter'
--- Twitter/Twitter	2012-01-29 18:20:33 +0000
+++ Twitter/Twitter	2012-03-05 14:58:31 +0000
@@ -26,9 +26,9 @@
 # To see the received direct messages right-click on the icon -> Twitter -> Received direct messages
 # To see some user's info right-click on the icon -> Twitter -> Info
 
-import urlparse, os, webbrowser, simplejson
+import urlparse, os, webbrowser, simplejson, threading, Queue, time, urllib2, simplejson
 from oauth import oauth
-from http import post, get
+from http import post, get #, stream
 from util import *
 from CDApplet import CDApplet, _
 # TODO import ConfigParser later conver files to config syntax
@@ -75,45 +75,59 @@
     self.access_token = oauth.OAuthToken.from_string(response)
     access_token_data = dict((x, y) for x, y in urlparse.parse_qsl(response))                 # tuple to dict
     return access_token_data['oauth_token'], access_token_data['oauth_token_secret']
+    
+# TODO: Separate things starting with this, check also the possible inheritance with TwitterOauth
+#class API():
+#  def __init__(self, access_key, access_secret):
+#    self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
+#    consumer_key, consumer_secret = read_consumer_key_and_secret()
+#    self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
+#    self.access_token = oauth.OAuthToken(access_key, access_secret)
 
-#class TwitterAPI(threading.Thread):
-class TwitterAPI():
+#class TwitterAPI(API):
+class TwitterAPI:
   def __init__(self, access_key, access_secret):
+    #API.__init__(self, access_key, access_secret)
     self.update_url             = 'http://twitter.com/statuses/update.json'
     self.home_timeline_url      = 'http://twitter.com/statuses/home_timeline.json'
     self.direct_messages_url    = 'https://api.twitter.com/1/direct_messages.json'
     self.verify_credentials_url = 'https://api.twitter.com/1/account/verify_credentials.json'
+    self.user_stream_url        = "https://userstream.twitter.com/2/user.json";
 
     self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     consumer_key, consumer_secret = read_consumer_key_and_secret()
     self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self.access_token = oauth.OAuthToken(access_key, access_secret)
-
-#    self.current_home_timeline = self.home_timeline()
-#    self.current_last_status_time = time.strptime(self.current_home_timeline[0]['created_at'], "%a %b %d %H:%M:%S +0000 %Y")
-#    print "==== initial last time ========="
-#    print self.current_home_timeline[0]['text']
-#    print self.current_last_status_time
-#    print "============="
-#    t = Thread(target=self.check_home_timeline())
-#    t.start()
-#    t.join()
-#    self.check_home_timeline()
-    #threading.Thread.__init__(self)
-
-#  def run(self):
-#    self.check_home_timeline()
-
-#  def tweety_streaming(self):
-#    oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
-#                                                               token = self.access_token,
-#                                                               http_url = self.tweety_streaming_url,
-#                                                               parameters = {'track':'recipe', 'delimited':'length'},
-#                                                               http_method = "GET")
-#    oauth_request.sign_request(self.signature_method, self.consumer, self.access_token)
-#    url = oauth_request.to_url()
-#    response = get(url)
-#    return simplejson.loads(response)
+    
+    thread = threading.Thread(target=self.tweety_streaming)
+    thread.start()
+    self.stream_content = Queue.Queue()
+    
+  def tweety_streaming(self):
+    oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
+                                                               token = self.access_token,
+                                                               http_url = self.user_stream_url)
+    oauth_request.sign_request(self.signature_method, self.consumer, self.access_token)
+    #stream(oauth_request.to_url())
+    url = oauth_request.to_url()
+    req = urllib2.urlopen(url)
+    buffer = ''
+    while True:
+      chunk = req.read(1)
+      if not chunk:
+        print buffer
+        break
+
+      buffer += chunk
+      tweets = buffer.split("\n",1)
+      if len(tweets) > 1:
+        content = tweets[0]
+        if "text" in content:
+          content = simplejson.loads(content)
+          self.stream_content.put(content)
+          self.stream_content.task_done()
+          print content
+        buffer = tweets[1]
 
   def tweety(self, message):                                                                  # popularly "send a tweety"
     oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
@@ -125,36 +139,6 @@
     post_data = oauth_request.to_postdata()
     return post(self.update_url, post_data)
 
-#  def check_home_timeline(self):
-#    i = 0
-#    while i < 5:
-#      new_home_timeline = self.home_timeline()
-#      new_tweetys = []
-#      if self.current_home_timeline:
-#        for status in new_home_timeline:
-#          #if status['created_at'] > self.current_last_status_time:
-#          if time.strptime(status['created_at'], "%a %b %d %H:%M:%S +0000 %Y") > self.current_last_status_time:
-#            print "==== found greater last time ========="
-#            print status['text']
-#            print status['created_at']
-#            print "============="
-#            new_tweetys.append(status)
-#        logp("Thread - Changed home timeline")
-#        self.current_home_timeline = new_home_timeline
-#        message = "".join (["[%s] %s\n" % (status['user']['name'], status['text']) for status in new_tweetys])
-#        logp(message)
-#        #self.show_popup_message(message)
-#        self.current_last_status_time = time.strptime(self.current_home_timeline[0]['created_at'], "%a %b %d %H:%M:%S +0000 %Y")
-#        print "==== novo greater last time ========="
-#        print status['text']
-#        print status['created_at']
-#        print "============="
-#        #self.current_last_status_time = self.current_home_timeline[0]['created_at']
-#      else:
-#        logp("Thread - Fetching home timeline")
-#        self.current_home_timeline = new_home_timeline
-#      time.sleep(20)
-#      i+=1
 
   def home_timeline(self):
     oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
@@ -202,6 +186,27 @@
     self.icon.SetQuickInfo("")
 
   # Twitter methods
+  
+  # TODO: Encapsulate this method inside the StreamAPI class
+  # TODO: Make available a "Animation" option upon a new tweet arrival
+  def check_twitter_user_stream(self):
+    while True:
+      time.sleep(30)                                              # TODO: variable for this!
+      logp("Checking Stream ...")
+      if not self.api.stream_content.empty():
+        self.tweets_on_the_user_stream_queue = self.api.stream_content.qsize()
+        logp("There are new %d items on the Stream Queue" % self.tweets_on_the_user_stream_queue)
+        self.icon.SetQuickInfo(str(self.tweets_on_the_user_stream_queue))
+
+  def show_new_tweets(self):
+    self.inform_start_of_waiting_process()
+    message = ''
+    while not self.api.stream_content.empty():
+      tweet = self.api.stream_content.get()
+      message += "[<b>%s</b>] %s\n" % (tweet['user']['name'], tweet['text'])
+    dialog = {'use-markup':True}
+    self.inform_end_of_waiting_process()
+    self.show_popup_message(message, dialog)
 
   def show_home_timeline(self):
     self.inform_start_of_waiting_process()
@@ -328,6 +333,17 @@
         'icon'  : os.path.abspath("./data/credentials.png")
     })
     self.icon.AddMenuItems(credentials_menu)
+    
+  # TODO: As soon as clean up the API code, the label will be: "New tweets (%d)" % self.tweets_on_the_user_stream_queue
+  def build_user_stream_menu(self):
+    user_stream_menu = []
+    user_stream_menu.append ({
+        'type'  : CDApplet.MENU_ENTRY,
+        'label' : _("New tweets"),
+        'id'    : self.user_stream_menu_id,
+        'icon'  : os.path.abspath("./data/new.png")
+    })
+    self.icon.AddMenuItems(user_stream_menu)
 
   def __init__(self):
     self.user = User()
@@ -340,6 +356,10 @@
 
     self.direct_messages_menu_id = 1000
     self.credentials_menu_id = 2000
+    self.user_stream_menu_id = 3000
+    
+    self.tweets_on_the_user_stream_queue = 0
+    # TODO: Array with the two threads here
 
     CDApplet.__init__(self)                                                           # call CDApplet interface init
 
@@ -352,7 +372,12 @@
     else:                                                                             # user not found
       logp("User '%s' found" % self.user.screen_name)
       self.api = TwitterAPI(self.user.access_key, self.user.access_secret)            # getting control over the api
-
+      thread = threading.Thread(target=self.check_twitter_user_stream)
+      thread.start()
+  
+  #def end(self):
+    # TODO: Iterate over the array of threads and join them here
+  
   # TODO: Fix it!
   def reload(self):
     self.read_user_data()
@@ -392,12 +417,16 @@
   def on_build_menu(self):
     self.build_direct_messages_menu()
     self.build_credentials_menu()
+    if self.tweets_on_the_user_stream_queue > 0:
+      self.build_user_stream_menu()
 
   def on_menu_select(self, selected_menu):
     if selected_menu == self.direct_messages_menu_id:
       self.show_direct_messages()
     elif selected_menu == self.credentials_menu_id:
       self.show_credentials()
+    elif selected_menu == self.user_stream_menu_id:
+      self.show_new_tweets()
 
 if __name__ == '__main__':
   Applet().run()

=== modified file 'Twitter/Twitter.conf'
--- Twitter/Twitter.conf	2012-01-29 18:20:33 +0000
+++ Twitter/Twitter.conf	2012-03-05 14:58:31 +0000
@@ -1,4 +1,4 @@
-#!en;0.0.3
+#!en;0.1
 
 #[gtk-about]
 [Icon]
@@ -8,7 +8,7 @@
 #d Name of the dock it belongs to:
 dock name = 
 
-#s Name of the icon as it will appear in its caption in the dock:
+#s Name of the icon as it will appear in its caption in the dock:
 name = Twitter
 
 #F[Display]

=== modified file 'Twitter/auto-load.conf'
--- Twitter/auto-load.conf	2012-01-29 18:20:33 +0000
+++ Twitter/auto-load.conf	2012-03-05 14:58:31 +0000
@@ -4,13 +4,13 @@
 author = Eduardo Mucelli Rezende Oliveira
 
 # A short description of the applet and how to use it.
-description = You can send tweets, see your timeline, and the received directed messages.\nOn the first time, the applet is going to ask your nickname and authorization to connect with Twitter.\nThe applet is going to open your browser with the authorization page\nAs soon as you authorize it, a PIN number will be shown on the page, copy this number\nPaste this number on the next dialog box will be shown.\nThe plugin is going to inform that you are successfully connected.\nTo see the received direct messages right-click on the icon -> Twitter -> Received direct messages.\nTo see some user's info right-click on the icon -> Twitter -> Info.
+description = You can send tweets, see your timeline, the received directed messages, and new tweets.\nOn the first time, the applet is going to ask your nickname and authorization to connect with Twitter.\nThe applet is going to open your browser with the authorization page\nAs soon as you authorize it, a PIN number will be shown on the page, copy this number\nPaste this number on the next dialog box will be shown.\nThe plugin is going to inform that you are successfully connected.\nTo see the received direct messages right-click on the icon -> Twitter -> Received direct messages.\nTo see some user's info right-click on the icon -> Twitter -> Info.\nTo see the received tweets right-click on the icon -> Twitter -> New tweets.
 
 # Category of the applet : 2 = files, 3 = internet, 4 = Desktop, 5 = accessory, 6 = system, 7 = fun
 category = 3
 
 # Version of the applet; change it everytime you change something in the config file. Don't forget to update the version both in this file and in the config file.
-version = 0.0.3
+version = 0.1
 
 # Whether the applet can be instanciated several times or not.
 multi-instance = true

=== added file 'Twitter/data/new.png'
Binary files Twitter/data/new.png	1970-01-01 00:00:00 +0000 and Twitter/data/new.png	2012-03-05 14:58:31 +0000 differ
=== modified file 'Twitter/data/received.png'
Binary files Twitter/data/received.png	2012-01-08 05:09:48 +0000 and Twitter/data/received.png	2012-03-05 14:58:31 +0000 differ
=== modified file 'Twitter/http.py'
--- Twitter/http.py	2011-12-17 03:28:23 +0000
+++ Twitter/http.py	2012-03-05 14:58:31 +0000
@@ -5,7 +5,7 @@
 # Author: Eduardo Mucelli Rezende Oliveira
 # E-mail: edumucelli@xxxxxxxxx or eduardom@xxxxxxxxxxx
 
-import urllib2
+import urllib2, json
 from util import logp, logm
 
 # HTTP GET
@@ -19,7 +19,7 @@
 		except urllib2.HTTPError:
 			tries += 1
 			if tries > 3:
-				raise			
+				raise
 
 # HTTP POST
 def post(url, post_data, tries = 0):
@@ -30,3 +30,22 @@
 			tries += 1
 			if tries > 3:
 				raise
+				
+#def stream(url):
+#  req = urllib2.urlopen(url)
+#  buffer = ''
+#  while True:
+#    chunk = req.read(1)
+#    if not chunk:
+#      print buffer
+#      break
+#    
+#    chunk = unicode(chunk)
+#    buffer += chunk
+#    
+#    tweets = buffer.split("\n",1)
+#    if len(tweets) > 1:
+#      print tweets[0]
+#      #return json.loads(tweets[0])
+#      buffer = tweets[1]
+#      #return tweety


Follow ups