Package Skype4Py :: Package API :: Module darwin
[frames] | no frames]

Source Code for Module Skype4Py.API.darwin

  1  ''' 
  2  Low level Skype for Mac OS X interface implemented 
  3  using Carbon distributed notifications. Uses direct 
  4  Carbon/CoreFoundation calls through ctypes module. 
  5   
  6  This module handles the options that you can pass to 
  7  L{ISkype.__init__<skype.ISkype.__init__>} for Mac OS X 
  8  machines. 
  9   
 10  No further options are currently supported. 
 11   
 12  Thanks to Eion Robb for reversing Skype for Mac API protocol. 
 13  ''' 
 14   
 15  from Skype4Py.API import ICommand, _ISkypeAPIBase 
 16  from ctypes import * 
 17  from ctypes.util import find_library 
 18  from Skype4Py.errors import ISkypeAPIError 
 19  from Skype4Py.enums import * 
 20  import threading, time 
 21   
 22   
23 -class Carbon(object):
24 '''Represents the Carbon.framework. 25 ''' 26
27 - def __init__(self):
28 path = find_library('Carbon') 29 if path == None: 30 raise ImportError('Could not find Carbon.framework') 31 self.lib = cdll.LoadLibrary(path) 32 self.lib.RunCurrentEventLoop.argtypes = (c_double,)
33
34 - def RunCurrentEventLoop(self, timeout=-1):
35 # timeout=-1 means forever 36 return self.lib.RunCurrentEventLoop(timeout)
37
38 - def GetCurrentEventLoop(self):
39 return EventLoop(self, c_void_p(self.lib.GetCurrentEventLoop()))
40 41
42 -class EventLoop(object):
43 '''Represents an EventLoop from Carbon.framework. 44 45 http://developer.apple.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/ 46 ''' 47
48 - def __init__(self, carb, handle):
49 self.carb = carb 50 self.handle = handle
51
52 - def quit(self):
53 self.carb.lib.QuitEventLoop(self.handle)
54 55
56 -class CoreFoundation(object):
57 '''Represents the CoreFoundation.framework. 58 ''' 59
60 - def __init__(self):
61 path = find_library('CoreFoundation') 62 if path == None: 63 raise ImportError('Could not find CoreFoundation.framework') 64 self.lib = cdll.LoadLibrary(path) 65 self.cfstrs = []
66
67 - def CFType(self, handle=0):
68 return CFType(self, handle=handle)
69
70 - def CFStringFromHandle(self, handle=0):
71 return CFString(self, handle=handle)
72
73 - def CFString(self, s=u''):
74 return CFString(self, string=s)
75
76 - def CFSTR(self, s):
77 for cfs in self.cfstrs: 78 if unicode(cfs) == s: 79 return cfs 80 cfs = self.CFString(s) 81 self.cfstrs.append(cfs) 82 return cfs
83
84 - def CFNumberFromHandle(self, handle=0):
85 return CFNumber(self, handle=handle)
86
87 - def CFNumber(self, n=0):
88 return CFNumber(self, number=n)
89
90 - def CFDictionaryFromHandle(self, handle=0):
91 return CFDictionary(self, handle=handle)
92
93 - def CFDictionary(self, d={}):
94 return CFDictionary(self, dictionary=d)
95
98 99
100 -class CFType(object):
101 '''Fundamental type for all CoreFoundation types. 102 103 http://developer.apple.com/documentation/CoreFoundation/Reference/CFTypeRef/ 104 ''' 105
106 - def __init__(self, cf, **kwargs):
107 if isinstance(cf, CFType): 108 self.cf = cf.cf 109 self.handle = cf.get_handle() 110 if len(kwargs): 111 raise TypeError('unexpected additional arguments') 112 else: 113 self.cf = cf 114 self.handle = None 115 self.owner = False 116 self.__dict__.update(kwargs) 117 if self.handle != None and not isinstance(self.handle, c_void_p): 118 self.handle = c_void_p(self.handle)
119
120 - def retain(self):
121 if not self.owner: 122 self.cf.lib.CFRetain(self) 123 self.owner = True
124
125 - def is_owner(self):
126 return self.owner
127
128 - def get_handle(self):
129 return self.handle
130
131 - def __del__(self):
132 if self.owner: 133 self.cf.lib.CFRelease(self) 134 self.handle = None 135 self.cf = None
136
137 - def __repr__(self):
138 return '%s(handle=%s)' % (self.__class__.__name__, repr(self.handle))
139 140 # allows passing CF types as ctypes function parameters 141 _as_parameter_ = property(get_handle)
142 143
144 -class CFString(CFType):
145 '''CoreFoundation string type. 146 147 Supports Python unicode type only. 148 149 http://developer.apple.com/documentation/CoreFoundation/Reference/CFStringRef/ 150 ''' 151
152 - def __init__(self, *args, **kwargs):
153 CFType.__init__(self, *args, **kwargs) 154 if 'string' in kwargs: 155 s = unicode(kwargs['string']).encode('utf8') 156 self.handle = c_void_p(self.cf.lib.CFStringCreateWithBytes(None, 157 s, len(s), 0x08000100, False)) 158 self.owner = True
159
160 - def __str__(self):
161 i = len(self) 162 buf = create_string_buffer(i) 163 self.cf.lib.CFStringGetBytes(self, 0, i, 0x08000100, c_char('?'), False, buf, i, None) 164 return buf.value
165
166 - def __unicode__(self):
167 return str(self).decode('utf8')
168
169 - def __len__(self):
170 return self.cf.lib.CFStringGetLength(self)
171
172 - def __repr__(self):
173 return 'CFString(%s)' % repr(unicode(self))
174 175
176 -class CFNumber(CFType):
177 '''CoreFoundation number type. 178 179 Supports Python int type only. 180 181 http://developer.apple.com/documentation/CoreFoundation/Reference/CFNumberRef/ 182 ''' 183
184 - def __init__(self, *args, **kwargs):
185 CFType.__init__(self, *args, **kwargs) 186 if 'number' in kwargs: 187 n = int(kwargs['number']) 188 self.handle = c_void_p(self.cf.lib.CFNumberCreate(None, 3, byref(c_int(n)))) 189 self.owner = True
190
191 - def __int__(self):
192 n = c_int() 193 if self.cf.lib.CFNumberGetValue(self, 3, byref(n)): 194 return n.value 195 return 0
196
197 - def __repr__(self):
198 return 'CFNumber(%s)' % repr(int(self))
199 200
201 -class CFDictionary(CFType):
202 '''CoreFoundation immutable dictionary type. 203 204 http://developer.apple.com/documentation/CoreFoundation/Reference/CFDictionaryRef/ 205 ''' 206
207 - def __init__(self, *args, **kwargs):
208 CFType.__init__(self, *args, **kwargs) 209 if 'dictionary' in kwargs: 210 d = dict(kwargs['dictionary']) 211 keys = (c_void_p * len(d))() 212 values = (c_void_p * len(d))() 213 i = 0 214 for k, v in d.items(): 215 if not isinstance(k, CFType): 216 raise TypeError('CFDictionary: key is not a CFType') 217 if not isinstance(v, CFType): 218 raise TypeError('CFDictionary: value is not a CFType') 219 keys[i] = k.get_handle() 220 values[i] = v.get_handle() 221 i += 1 222 self.handle = c_void_p(self.cf.lib.CFDictionaryCreate(None, keys, values, len(d), 223 self.cf.lib.kCFTypeDictionaryKeyCallBacks, self.cf.lib.kCFTypeDictionaryValueCallBacks)) 224 self.owner = True
225
226 - def get_dict(self):
227 n = len(self) 228 keys = (c_void_p * n)() 229 values = (c_void_p * n)() 230 self.cf.lib.CFDictionaryGetKeysAndValues(self, keys, values) 231 d = dict() 232 for i in xrange(n): 233 d[self.cf.CFType(keys[i])] = self.cf.CFType(values[i]) 234 return d
235
236 - def __getitem__(self, key):
237 return self.cf.CFType(c_void_p(self.cf.lib.CFDictionaryGetValue(self, key)))
238
239 - def __len__(self):
240 return self.cf.lib.CFDictionaryGetCount(self)
241 242
243 -class CFDistributedNotificationCenter(CFType):
244 '''CoreFoundation distributed notification center type. 245 246 http://developer.apple.com/documentation/CoreFoundation/Reference/CFNotificationCenterRef/ 247 ''' 248 249 CFNotificationCallback = CFUNCTYPE(None, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p) 250
251 - def __init__(self, *args, **kwargs):
252 CFType.__init__(self, *args, **kwargs) 253 self.handle = c_void_p(self.cf.lib.CFNotificationCenterGetDistributedCenter()) 254 # there is only one distributed notification center per application 255 self.owner = False 256 self.callbacks = {} 257 self._callback = self.CFNotificationCallback(self._notification_callback)
258
259 - def _notification_callback(self, center, observer, name, obj, userInfo):
260 observer = self.cf.CFStringFromHandle(observer) 261 name = self.cf.CFStringFromHandle(name) 262 if obj: 263 obj = self.cf.CFStringFromHandle(obj) 264 callback = self.callbacks[(unicode(observer), unicode(name))] 265 callback(self, observer, name, obj, 266 self.cf.CFDictionaryFromHandle(userInfo))
267
268 - def add_observer(self, observer, callback, name=None, obj=None, 269 drop=False, coalesce=False, hold=False, immediate=False):
270 if not isinstance(observer, CFString): 271 observer = self.cf.CFString(observer) 272 if not callable(callback): 273 raise TypeError('callback must be callable') 274 self.callbacks[(unicode(observer), unicode(name))] = callback 275 if name != None and not isinstance(name, CFString): 276 name = self.cf.CFSTR(name) 277 if obj != None and not isinstance(obj, CFString): 278 obj = self.cf.CFSTR(obj) 279 if drop: 280 behaviour = 1 281 elif coalesce: 282 behaviour = 2 283 elif hold: 284 behaviour = 3 285 elif immediate: 286 behaviour = 4 287 else: 288 behaviour = 0 289 self.cf.lib.CFNotificationCenterAddObserver(self, observer, self._callback, name, obj, behaviour)
290
291 - def remove_observer(self, observer, name=None, obj=None):
292 if not isinstance(observer, CFString): 293 observer = self.cf.CFString(observer) 294 if name != None and not isinstance(name, CFString): 295 name = self.cf.CFSTR(name) 296 if obj != None and not isinstance(obj, CFString): 297 obj = self.cf.CFSTR(obj) 298 self.cf.lib.CFNotificationCenterRemoveObserver(self, observer, name, obj) 299 try: 300 del self.callbacks[(unicode(observer), unicode(name))] 301 except KeyError: 302 pass
303
304 - def post_notification(self, name, obj=None, userInfo=None, immediate=False):
305 if not isinstance(name, CFString): 306 name = self.cf.CFSTR(name) 307 if obj != None and not isinstance(obj, CFString): 308 obj = self.cf.CFSTR(obj) 309 if userInfo != None and not isinstance(userInfo, CFDictionary): 310 userInfo = self.cf.CFDictionary(userInfo) 311 self.cf.lib.CFNotificationCenterPostNotification(self, name, obj, userInfo, immediate)
312 313
314 -class _ISkypeAPI(_ISkypeAPIBase):
315 '''Skype for Mac API wrapper. 316 317 Based with permission on code included in Skype Plugin for Pidgin. 318 http://code.google.com/p/skype4pidgin/ 319 ''' 320
321 - def __init__(self, handler, opts):
322 _ISkypeAPIBase.__init__(self, opts) 323 self.RegisterHandler(handler) 324 self.carbon = Carbon() 325 self.coref = CoreFoundation() 326 self.center = self.coref.CFDistributedNotificationCenter() 327 self.is_available = False 328 self.client_id = -1
329
330 - def run(self):
331 self.DebugPrint('thread started') 332 self.loop = self.carbon.GetCurrentEventLoop() 333 self.carbon.RunCurrentEventLoop() 334 self.DebugPrint('thread finished')
335
336 - def Close(self):
337 if hasattr(self, 'loop'): 338 self.loop.quit() 339 self.DebugPrint('closed')
340
341 - def SetFriendlyName(self, FriendlyName):
342 self.FriendlyName = FriendlyName 343 if self.AttachmentStatus == apiAttachSuccess: 344 # reattach with the new name 345 self.SetAttachmentStatus(apiAttachUnknown) 346 self.Attach()
347
348 - def Attach(self, Timeout=30000, Wait=True):
349 if self.AttachmentStatus in (apiAttachPendingAuthorization, apiAttachSuccess): 350 return 351 try: 352 self.start() 353 except AssertionError: 354 pass 355 try: 356 self.init_observer() 357 self.SetAttachmentStatus(apiAttachPendingAuthorization) 358 self.post('SKSkypeAPIAttachRequest') 359 self.wait = True 360 def ftimeout(): 361 self.wait = False
362 t = threading.Timer(Timeout / 1000.0, ftimeout) 363 if Wait: 364 t.start() 365 while self.wait and self.AttachmentStatus == apiAttachPendingAuthorization: 366 time.sleep(1.0) 367 finally: 368 t.cancel() 369 if not self.wait: 370 self.SetAttachmentStatus(apiAttachUnknown) 371 raise ISkypeAPIError('Skype attach timeout') 372 self.SendCommand(ICommand(-1, 'PROTOCOL %s' % self.Protocol))
373
374 - def IsRunning(self):
375 try: 376 self.start() 377 except AssertionError: 378 pass 379 self.init_observer() 380 self.is_available = False 381 self.post('SKSkypeAPIAvailabilityRequest') 382 time.sleep(1.0) 383 return self.is_available
384
385 - def Start(self, Minimized=False, Nosplash=False):
386 if not self.IsRunning(): 387 from subprocess import Popen 388 nul = file('/dev/null') 389 Popen(['/Applications/Skype.app/Contents/MacOS/Skype'], stdin=nul, stdout=nul, stderr=nul)
390
391 - def SendCommand(self, Command):
392 if not self.AttachmentStatus == apiAttachSuccess: 393 self.Attach(Command.Timeout) 394 self.CommandsStackPush(Command) 395 self.CallHandler('send', Command) 396 com = u'#%d %s' % (Command.Id, Command.Command) 397 if Command.Blocking: 398 Command._event = event = threading.Event() 399 else: 400 Command._timer = timer = threading.Timer(Command.Timeout / 1000.0, self.CommandsStackPop, (Command.Id,)) 401 402 self.DebugPrint('->', repr(com)) 403 userInfo = self.coref.CFDictionary({self.coref.CFSTR('SKYPE_API_COMMAND'): self.coref.CFString(com), 404 self.coref.CFSTR('SKYPE_API_CLIENT_ID'): self.coref.CFNumber(self.client_id)}) 405 self.post('SKSkypeAPICommand', userInfo) 406 407 if Command.Blocking: 408 event.wait(Command.Timeout / 1000.0) 409 if not event.isSet(): 410 raise ISkypeAPIError('Skype command timeout') 411 else: 412 timer.start()
413
414 - def init_observer(self):
415 if self.has_observer(): 416 self.delete_observer() 417 self.observer = self.coref.CFString(self.FriendlyName) 418 self.center.add_observer(self.observer, self.SKSkypeAPINotification, 'SKSkypeAPINotification', immediate=True) 419 self.center.add_observer(self.observer, self.SKSkypeWillQuit, 'SKSkypeWillQuit', immediate=True) 420 self.center.add_observer(self.observer, self.SKSkypeBecameAvailable, 'SKSkypeBecameAvailable', immediate=True) 421 self.center.add_observer(self.observer, self.SKAvailabilityUpdate, 'SKAvailabilityUpdate', immediate=True) 422 self.center.add_observer(self.observer, self.SKSkypeAttachResponse, 'SKSkypeAttachResponse', immediate=True)
423
424 - def delete_observer(self):
425 if not self.has_observer(): 426 return 427 self.center.remove_observer(self.observer, 'SKSkypeAPINotification') 428 self.center.remove_observer(self.observer, 'SKSkypeWillQuit') 429 self.center.remove_observer(self.observer, 'SKSkypeBecameAvailable') 430 self.center.remove_observer(self.observer, 'SKAvailabilityUpdate') 431 self.center.remove_observer(self.observer, 'SKSkypeAttachResponse') 432 del self.observer
433
434 - def has_observer(self):
435 return hasattr(self, 'observer')
436
437 - def post(self, name, userInfo=None):
438 if not self.has_observer(): 439 self.init_observer() 440 self.center.post_notification(name, self.observer, userInfo, immediate=True)
441
442 - def SKSkypeAPINotification(self, center, observer, name, obj, userInfo):
443 client_id = int(CFNumber(userInfo[self.coref.CFSTR('SKYPE_API_CLIENT_ID')])) 444 if client_id != 999 and (client_id == 0 or client_id != self.client_id): 445 return 446 com = unicode(CFString(userInfo[self.coref.CFSTR('SKYPE_API_NOTIFICATION_STRING')])) 447 self.DebugPrint('<-', repr(com)) 448 449 if com.startswith(u'#'): 450 p = com.find(u' ') 451 Command = self.CommandsStackPop(int(com[1:p])) 452 if Command: 453 Command.Reply = com[p + 1:] 454 if Command.Blocking: 455 Command._event.set() 456 del Command._event 457 else: 458 Command._timer.cancel() 459 del Command._timer 460 self.CallHandler('rece', Command) 461 else: 462 self.CallHandler('rece_api', com[p + 1:]) 463 else: 464 self.CallHandler('rece_api', com)
465
466 - def SKSkypeWillQuit(self, center, observer, name, obj, userInfo):
467 self.DebugPrint('<-', 'SKSkypeWillQuit') 468 self.SetAttachmentStatus(apiAttachNotAvailable)
469
470 - def SKSkypeBecameAvailable(self, center, observer, name, obj, userInfo):
471 self.DebugPrint('<-', 'SKSkypeBecameAvailable') 472 self.SetAttachmentStatus(apiAttachAvailable)
473
474 - def SKAvailabilityUpdate(self, center, observer, name, obj, userInfo):
475 self.DebugPrint('<-', 'SKAvailabilityUpdate') 476 self.is_available = bool(int(CFNumber(userInfo[self.coref.CFSTR('SKYPE_API_AVAILABILITY')])))
477
478 - def SKSkypeAttachResponse(self, center, observer, name, obj, userInfo):
479 self.DebugPrint('<-', 'SKSkypeAttachResponse') 480 # It seems that this notification is not called if the access is refused. Therefore we can't 481 # distinguish between attach timeout and access refuse. 482 self.client_id = int(CFNumber(userInfo[self.coref.CFSTR('SKYPE_API_ATTACH_RESPONSE')])) 483 if self.client_id: 484 self.SetAttachmentStatus(apiAttachSuccess)
485