public
Description: A PyObjC based Twitter client
Homepage:
Clone URL: git://github.com/lethain/kappa.git
lethain (author)
Thu Sep 04 05:24:37 -0700 2008
commit  3cdc6eaa445f7ed0dd5e309d7c704c9520715a92
tree    4444d0c22e5d6b8a9533ee66ae6f0348b1721109
parent  c0ea74b3a0199ee81bf430a9615aa0294831440b
kappa / KappaAppDelegate.py
100644 369 lines (295 sloc) 12.869 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#
# KappaAppDelegate.py
# Kappa
#
# Created by Will Larson on 9/1/08.
# Copyright Will Larson 2008. All rights reserved.
#
 
import twitter
import os, objc, pickle, datetime, urllib2, re
from Foundation import *
from AppKit import *
 
"""
From python-twitter documentation:
 
>>> api.PostDirectMessage(user, text)
>>> api.GetUser(user)
>>> api.GetReplies()
>>> api.GetUserTimeline(user)
>>> api.GetStatus(id)
>>> api.DestroyStatus(id)
>>> api.GetFriendsTimeline(user)
>>> api.GetFriends(user)
>>> api.GetFollowers()
>>> api.GetFeatured()
>>> api.GetDirectMessages()
>>> api.PostDirectMessage(user, text)
>>> api.DestroyDirectMessage(id)
>>> api.DestroyFriendship(user)
>>> api.CreateFriendship(user)
 
"""
 
USER_PREFS_FILE = 'user.prefs'
 
class KappaAppDelegate(NSObject):
    mainWindow = objc.IBOutlet()
    prefsWindow = objc.IBOutlet()
    timeProgressIndicator = objc.IBOutlet()
    inputTextField = objc.IBOutlet()
    twitDictsController = objc.IBOutlet()
    searchField = objc.IBOutlet()
    publicTimelineMenu = objc.IBOutlet()
    friendsTimelineMenu = objc.IBOutlet()
    atRepliesMenu = objc.IBOutlet()
    tableView = objc.IBOutlet()
    
    prefs = None # initialized in restorePreferences
    
    progressIndicatorTimer = None
    lastRetrieval = None
    nextRetrieval = None
    twits = []
    twitDicts = []
    api = None
    retrievedOwnTimeline = False
    
    ''' IBActions for picking feeds. '''
    def toggleMenuItem(self,menuItem):
        if menuItem.state() == 0:
            menuItem.setState_(1)
        else:
            menuItem.setState_(0)
    
    @objc.IBAction
    def togglePublicTimeline_(self,sender):
        self.toggleMenuItem(self.publicTimelineMenu)
        self.prefs['fetch_public_timeline'] = 1 if self.prefs['fetch_public_timeline'] == 0 else 0
        
        
    @objc.IBAction
    def toggleFriendsTimeline_(self,sender):
        self.toggleMenuItem(self.friendsTimelineMenu)
        self.prefs['fetch_friends_timeline'] = 1 if self.prefs['fetch_friends_timeline'] == 0 else 0
        
    @objc.IBAction
    def toggleAtReplies_(self,sender):
        self.toggleMenuItem(self.atRepliesMenu)
        self.prefs['fetch_at_replies'] = 1 if self.prefs['fetch_at_replies'] == 0 else 0
    
    ''' Serialization '''
    
    def restorePreferences(self):
        try:
            fin = open(self.pathForFile(USER_PREFS_FILE), 'r')
            self.prefs = NSMutableDictionary.dictionaryWithDictionary_(pickle.load(fin))
            fin.close()
        except IOError:
            defaults = {
                'retrievalInterval':10.0,
                'username':'',
                'password':'',
                'fetch_at_replies':0,
                'fetch_public_timeline':0,
                'fetch_friends_timeline':1,
            }
            self.prefs = NSMutableDictionary.dictionaryWithDictionary_(defaults)
            
    def restoreTweets(self):
        try:
            fin = open(self.pathForFile("twits.serialized"),'r')
            self.twits = pickle.load(fin)
            fin.close()
        except IOError:
            self.twits = []
        
    def storePreferences(self):
        newDict = {}
        for key in self.prefs:
            newDict[key] = self.prefs[key]
    
    
        fout = open(self.pathForFile(USER_PREFS_FILE),'w')
        pickle.dump(newDict,fout)
        fout.close()
        
    def storeTweets(self):
        fout = open(self.pathForFile("twits.serialized"),'w')
        pickle.dump(self.twits,fout)
        fout.close()
        
    def incrementProgressIndicator(self):
        self.inputTextField.setBackgroundColor_(self.normalBackground)
        if self.timeProgressIndicator.doubleValue() >= 100.0:
            self.progressIndicatorTimer.invalidate()
            self.resetTime()
        else:
            self.timeProgressIndicator.incrementBy_(1.0)
 
    def resetTime(self):
        self.timeProgressIndicator.setDoubleValue_(100.0)
        self.checkForTweets()
    
        now = datetime.datetime.now()
        self.lastRetrieval = now
        self.nextRetrieval = now + datetime.timedelta(minutes=int(self.prefs['retrievalInterval']))
        
        # Reset progress indicator.
        self.timeProgressIndicator.setDoubleValue_(0.0)
        interval = (self.prefs['retrievalInterval']*60.0) / 100.0
        
        s = objc.selector(self.incrementProgressIndicator,signature="v@:")
        t = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(interval,self,s,None,True)
        self.progressIndicatorTimer = t
        
    def showPrefsWindow(self):
        self.prefsWindow.makeKeyAndOrderFront_(self)
 
    ''' Wrappers for Twitter Functionality '''
    
    @objc.IBAction
    def submitTwit_(self,sender):
        self.postMessage(self.inputTextField.stringValue())
    
    def postMessage(self, msg):
        try:
            status = self.api.PostUpdate(msg)
            self.integrateTweets([status])
            self.updateTwitDict()
            self.inputTextField.setStringValue_(u"")
            self.mainWindow.setTitle_(u"Kappa (140)")
            self.inputTextField.setBackgroundColor_(self.normalBackground)
        except urllib2.URLError:
            self.inputTextField.setBackgroundColor_(self.warningBackground)
            self.mainWindow.setTitle_(u"Kappa [Couldn't connect To internet] (%s)" % (int(140) - int(len(msg))))
            NSLog(u"Kappa: Couldn't connect to internet to send tweet.")
        
    def updateTwitDict(self,tweets=None):
        if tweets is None:
            tweets = self.twits[:50]
            
    
        def convertTwit(tweet):
            objcDict = {}
            objcDict['time'] = NSDate.dateWithTimeIntervalSince1970_(tweet.created_at_in_seconds)
            objcDict['user'] = tweet.user.screen_name
            objcDict['text'] = tweet.text
            return NSDictionary.dictionaryWithDictionary_(objcDict)
        self.twitDicts = [ convertTwit(x) for x in tweets ]
        self.twitDictsController.rearrangeObjects()
 
        
    def checkForTweets(self):
        if self.api is not None:
            try:
                if self.retrievedOwnTimeline == False:
                    ownTweets = self.api.GetUserTimeline(self.username())
                    self.integrateTweets(ownTweets)
                newTweets = []
                if self.prefs['fetch_friends_timeline']:
                    newTweets = newTweets + self.api.GetFriendsTimeline()
                if self.prefs['fetch_at_replies']:
                    newTweets = newTweets + self.api.GetReplies()
                if self.prefs['fetch_public_timeline']:
                    newTweets = newTweets + self.api.GetPublicTimeline()
                self.integrateTweets(newTweets)
            except urllib2.URLError:
                NSLog(u"Kappa: Couldn't connect to Twitter to retrieve tweets.")
            self.updateTwitDict()
                        
    def integrateTweets(self,tweets):
        for tweet in tweets:
            self.integrateTweet(tweet)
            
    def integrateTweet(self,tweet):
        tweets = self.twits
        wasInserted = False
        length = len(tweets)
        for i in xrange(0,length,1):
            stored = tweets[i]
            if tweet.id == stored.id:
                break
            elif tweet.id > stored.id:
                tweets.insert(i,tweet)
                break
 
        if length == 0:
            tweets.insert(-1,tweet)
    
    def login(self):
        if self.prefs['username'] and self.prefs['password']:
            self.api = twitter.Api(username=self.username(),password=self.password())
            return True
        return False
 
    ''' Application Delegate Methods '''
    
    def awakeFromNib(self):
        # load serialized data from disk
        self.restorePreferences()
        self.restoreTweets()
        
        # setup menus on/off state
        if self.prefs['fetch_at_replies']:
            self.toggleMenuItem(self.atRepliesMenu)
        if self.prefs['fetch_friends_timeline']:
            self.toggleMenuItem(self.friendsTimelineMenu)
        if self.prefs['fetch_public_timeline']:
            self.toggleMenuItem(self.publicTimelineMenu)
        
        # setup background stuff
        self.normalBackground = self.inputTextField.backgroundColor()
        self.warningBackground = NSColor.colorWithCalibratedRed_green_blue_alpha_(0.7, 0.65, 0.6, 0.9)
        self.warningBackground.retain()
        
        # setup default sorting for array controller
        sd = NSSortDescriptor.alloc().initWithKey_ascending_(u"time", False)
        self.twitDictsController.setSortDescriptors_([sd])
        
        self.initializedResizing = False
        self.defaultHeaderView = self.tableView.headerView()
                            
    def applicationWillTerminate_(self,sender):
        self.storePreferences()
        self.storeTweets()
    
    def applicationDidFinishLaunching_(self, sender):
        if self.login():
            self.resetTime()
        else:
            self.showPrefsWindow()
            
    def hideColumnHeaders(self):
        self.tableView.setHeaderView_(None)
            
        
    def showColumnHeaders(self):
        self.tableView.setHeaderView_(self.defaultHeaderView)
    
    def windowDidBecomeMain_(self,sender):
        self.mainWindow.setTitle_(u"Kappa (%s)" % (int(140) - int(len(self.inputTextField.stringValue()))))
        if self.initializedResizing == True:
            self.showColumnHeaders()
            scrollView = self.tableView.superview().superview()
            f = scrollView.frame()
            f.origin.y = f.origin.y + 36
            f.size.height = f.size.height - 66
            scrollView.setFrame_(f)
            scrollView.setNeedsDisplay_(True)
            self.searchField.setHidden_(False)
            self.inputTextField.setHidden_(False)
        else:
            self.initializedResizing = True
        
 
        
    def windowDidResignMain_(self,sender):
        self.mainWindow.setTitle_(u"Kappa")
        self.hideColumnHeaders()
        self.searchField.setHidden_(True)
        self.inputTextField.setHidden_(True)
        
        scrollView = self.tableView.superview().superview()
        f = scrollView.frame()
        f.origin.y = f.origin.y - 36
        f.size.height = f.size.height + 66
        scrollView.setFrame_(f)
        scrollView.setNeedsDisplay_(True)
        
    ''' NSControl delegate methods '''
    
    def controlTextDidChange_(self,notification):
        txt = self.inputTextField.stringValue()
        self.mainWindow.setTitle_(u"Kappa (%s)" % unicode(140-len(txt)))
    
    ''' Application Delegate Utility Methods '''
            
    def applicationSupportFolder(self):
        paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,NSUserDomainMask,True)
        basePath = (len(paths) > 0 and paths[0]) or NSTemporaryDirectory()
        fullPath = basePath.stringByAppendingPathComponent_("Kappa")
        if not os.path.exists(fullPath):
            os.mkdir(fullPath)
        return fullPath
        
    def pathForFile(self,filename):
        return self.applicationSupportFolder().stringByAppendingPathComponent_(filename)
        
    ''' Support for NSSearchField '''
    
    
    
    @objc.IBAction
    def search_(self, searchField):
        searchStr = searchField.stringValue()
        if searchStr == u"":
            self.updateTwitDict()
            return
        try:
            SEARCH_RE = re.compile(searchStr, re.MULTILINE|re.IGNORECASE)
            searchField.setTextColor_(NSColor.blackColor())
            def match_search(tweet):
                if SEARCH_RE.match(tweet.user.screen_name) is not None:
                    return True
                if SEARCH_RE.match(tweet.text) is not None:
                    return True
                return False
            matches = [ x for x in self.twits if match_search(x) ]
            self.updateTwitDict(matches)
            
        except re.error:
            searchField.setTextColor_(NSColor.redColor())
            NSLog(u"Kappa: '%s' is not a valid regular expression." % searchStr)
        
    ''' Accessors and mutators '''
    
    def username(self):
        return self.prefs['username']
        
    def setUsername_(self,val):
        self.prefs['username'] = val
        self.login()
        
    def password(self):
        return self.prefs['password']
        
    def setPassword_(self,val):
        self.prefs['password'] = val
        self.login()
        
    def retrievalInterval(self):
        return self.prefs['retrievalInterval']
        
    def setRetrievalInterval(self,val):
        self.prefs['retrievalInterval'] = val