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
24 '''Represents the Carbon.framework.
25 '''
26
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
37
40
41
43 '''Represents an EventLoop from Carbon.framework.
44
45 http://developer.apple.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/
46 '''
47
49 self.carb = carb
50 self.handle = handle
51
53 self.carb.lib.QuitEventLoop(self.handle)
54
55
57 '''Represents the CoreFoundation.framework.
58 '''
59
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
68 return CFType(self, handle=handle)
69
72
75
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
86
89
92
95
98
99
101 '''Fundamental type for all CoreFoundation types.
102
103 http://developer.apple.com/documentation/CoreFoundation/Reference/CFTypeRef/
104 '''
105
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
121 if not self.owner:
122 self.cf.lib.CFRetain(self)
123 self.owner = True
124
127
130
132 if self.owner:
133 self.cf.lib.CFRelease(self)
134 self.handle = None
135 self.cf = None
136
138 return '%s(handle=%s)' % (self.__class__.__name__, repr(self.handle))
139
140
141 _as_parameter_ = property(get_handle)
142
143
145 '''CoreFoundation string type.
146
147 Supports Python unicode type only.
148
149 http://developer.apple.com/documentation/CoreFoundation/Reference/CFStringRef/
150 '''
151
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
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
167 return str(self).decode('utf8')
168
170 return self.cf.lib.CFStringGetLength(self)
171
173 return 'CFString(%s)' % repr(unicode(self))
174
175
177 '''CoreFoundation number type.
178
179 Supports Python int type only.
180
181 http://developer.apple.com/documentation/CoreFoundation/Reference/CFNumberRef/
182 '''
183
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
192 n = c_int()
193 if self.cf.lib.CFNumberGetValue(self, 3, byref(n)):
194 return n.value
195 return 0
196
198 return 'CFNumber(%s)' % repr(int(self))
199
200
202 '''CoreFoundation immutable dictionary type.
203
204 http://developer.apple.com/documentation/CoreFoundation/Reference/CFDictionaryRef/
205 '''
206
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
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
237 return self.cf.CFType(c_void_p(self.cf.lib.CFDictionaryGetValue(self, key)))
238
240 return self.cf.lib.CFDictionaryGetCount(self)
241
242
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
252 CFType.__init__(self, *args, **kwargs)
253 self.handle = c_void_p(self.cf.lib.CFNotificationCenterGetDistributedCenter())
254
255 self.owner = False
256 self.callbacks = {}
257 self._callback = self.CFNotificationCallback(self._notification_callback)
258
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
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
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
329
335
337 if hasattr(self, 'loop'):
338 self.loop.quit()
339 self.DebugPrint('closed')
340
347
348 - def Attach(self, Timeout=30000, Wait=True):
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
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
413
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
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
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
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
469
471 self.DebugPrint('<-', 'SKSkypeBecameAvailable')
472 self.SetAttachmentStatus(apiAttachAvailable)
473
475 self.DebugPrint('<-', 'SKAvailabilityUpdate')
476 self.is_available = bool(int(CFNumber(userInfo[self.coref.CFSTR('SKYPE_API_AVAILABILITY')])))
477
479 self.DebugPrint('<-', 'SKSkypeAttachResponse')
480
481
482 self.client_id = int(CFNumber(userInfo[self.coref.CFSTR('SKYPE_API_ATTACH_RESPONSE')]))
483 if self.client_id:
484 self.SetAttachmentStatus(apiAttachSuccess)
485