-
Notifications
You must be signed in to change notification settings - Fork 4
/
pushybullet.py
1372 lines (1068 loc) · 41.3 KB
/
pushybullet.py
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
from StringIO import StringIO
import os
import datetime
import time
import base64
import binascii
import urllib
import urlparse
import httplib
import random
try:
import simplejson as json
except ImportError:
import json
class FilelikeGenerator(object):
def __init__(self, gen):
self.__gen = gen
self.__buf = ''
self.__eof = False
def __popbuf(self, buflen):
self.__buf, res = self.__buf[buflen+1:], self.__buf[0:buflen]
return res
def read(self, buflen=0):
if buflen > 0:
if len(self.__buf) >= buflen:
return self.__popbuf(buflen)
if self.__eof:
return None
while len(self.__buf) < buflen:
try:
self.__buf += self.__gen.next()
except StopIteration:
self.__eof = True
break
return self.__popbuf(buflen)
else:
for part in self.__gen:
self.__buf += part
self.__eof = True
res, self.__buf = self.__buf, ''
return res or None
def next(self):
value = self.read(8192)
if value is None:
raise StopIteration
return value
def isatty(self):
return False
@property
def closed(self):
return False
def close(self):
pass
def seek(self, pos, whence=0):
raise NotImplementedError
def filelike_generator(func):
def wrapper(*args, **kwargs):
return FilelikeGenerator(func(*args, **kwargs))
return wrapper
class Session(object):
auth = ()
headers = {}
def get(self, url, params=None, auth=None, headers=None):
return self._request('GET', url, params=params, auth=auth, headers=headers)
def post(self, url, params=None, data=None, files=None, auth=None, headers=None):
return self._request('POST', url, params=params, data=data, files=files, auth=auth, headers=headers)
def delete(self, url, params=None, auth=None, headers=None):
return self._request('DELETE', url, params=params, auth=auth, headers=headers)
def _encode_form_data(self, pairs):
boundary = ''.join(chr(random.choice(xrange(ord('a'), ord('z')))) for _ in xrange(0, 30))
body = []
for name, value in pairs:
if hasattr(value, 'read'):
_body = value.read()
body.append(
'Content-Type: application/octet-stream\r\n'
'Content-Disposition: form-data; name="%s"; filename="%s"\r\n'
'Content-Length: %s\r\n'
'\r\n'
'%s' % (
urllib.quote(name),
urllib.quote(getattr(value, 'name', None) or "file.txt"),
len(_body),
_body))
else:
body.append(
'Content-Type: text/plain\r\n'
'Content-Disposition: form-data; name="%s"\r\n'
'Content-Length: %s\r\n'
'\r\n'
'%s' % (
urllib.quote(name),
len(value),
value))
return 'multipart/form-data; boundary="%s"' % boundary, ('--%s\r\n' % boundary) + ('\r\n--%s\r\n' % boundary).join(body) + ('\r\n--%s--\r\n' % boundary)
class Response(object):
def __init__(self, resp):
self.__resp = resp
def json(self):
return json.load(self.__resp)
def raise_for_status(self):
status = self.__resp.status
kind = status // 100
if kind in (1, 2, 3):
return
raise RuntimeError('%s %s' % (status, self.__resp.reason))
def _request(self, method, url, params=None, data=None, files=None, auth=None, headers=None):
_url = urlparse.urlparse(url)
conn = {'http': httplib.HTTPConnection,
'https': httplib.HTTPSConnection}[_url.scheme](_url.hostname, _url.port)
if params:
_params = params.copy()
for k in _params.keys():
if _params[k] is None:
del _params[k]
_query = urllib.urlencode(_params)
else:
_query = _url.query
_headers = self.headers.copy()
_headers['Host'] = _url.hostname
if files:
content_type, _data = self._encode_form_data(p for n in (data, files) for p in n.iteritems())
elif data:
content_type, _data = ('application/x-www-form-urlencoded',
urllib.urlencode(data) if isinstance(data, dict) else str(data))
else:
content_type, _data = None, None
if _data:
_headers['Content-Type'] = content_type
#_headers['Content-Length'] = str(len(_data))
if headers:
_headers.update(headers)
_auth = auth if auth is not None else (
(_url.username or '', _url.password or '')
if (_url.username is not None or _url.password is not None) else
self.auth)
if _auth:
_headers['Authorization'] = 'Basic %s' % base64.encodestring(':'.join(_auth)).strip()
conn.request(method, '?'.join((_url.path, _query)), _data, _headers)
response = conn.getresponse()
return self.Response(response)
def get_apikey_from_config():
try:
from ConfigParser import SafeConfigParser as ConfigParser
except ImportError:
from configparser import SafeConfigParser as ConfigParser
try:
config = ConfigParser()
config.read(os.path.expanduser('~/.config/pushbullet/config.ini'))
return config.get('pushbullet', 'apikey')
except:
return None
def utf8(s):
return s if isinstance(s, unicode) else unicode(s, 'utf-8') if isinstance(s, str) else unicode(s)
def parse_since(since):
if not since:
return 0
if isinstance(since, (long, int)):
return since + time.time() if since < 0 else since
if isinstance(since, datetime.date):
return since.strftime('%s')
if isinstance(since, datetime.timedelta):
return (datetime.datetime.now() - since).strftime('%s')
try:
since = int(since)
return since + time.time() if since < 0 else since
except ValueError:
from dateutil.parser import parse
return parse(since).strftime('%s')
# Events {{{
class Event(object):
'''
Abstract Pushbullet event
'''
__slots__ = ['api', 'time']
def __init__(self, api):
self.time = time.time()
self.api = api
def __repr__(self):
return '<%s @%s>' % (self.__class__.__name__, self.time)
def pushes(self, skip_empty=False, limit=None):
return xrange(0) # empty generator
def latest_push_time(self):
try:
push = self.pushes(limit=1).next()
return push.get('modified') or push.get('created')
except (StopIteration, AttributeError):
return None
class NopEvent(Event):
'''
Nop event (keep-alive ticks)
'''
__slots__ = ['api', 'time']
class TickleEvent(Event):
'''
Tickle event (user pushes)
'''
__slots__ = ['api', 'time', 'since', 'subtype']
def __init__(self, api, subtype, since):
Event.__init__(self, api)
self.subtype = subtype
self.since = since
def pushes(self, skip_empty=False, limit=None):
return self.api.pushes(since=self.since, skip_empty=skip_empty, limit=limit)
def __repr__(self):
return '<%s[%s] @%s>' % (self.__class__.__name__, self.subtype, self.time)
class PushEvent(Event):
'''
Push event (device notification mirroring)
'''
__slots__ = ['api', 'time', 'push']
def __init__(self, api, push):
Event.__init__(self, api)
self.push = push
def __repr__(self):
return (u'<%s[%r] @%s>' % (self.__class__.__name__, self.push, self.time)).encode('utf-8')
def pushes(self, skip_empty=False, limit=None):
yield self.push
# }}}
class PushBulletError(Exception):
pass
class PushBulletObject(object):
'''
Abstract Pushbullet object for given REST endpoint
'''
collection_name = None
def __init__(self, **data):
self.__dict__.update(data)
@property
def uri(self):
'''
Relative REST-object URI
'''
raise NotImplementedError
def delete(self):
'''
Delete object
'''
self.api.delete(self.uri)
def bind(self, api):
'''
Bind object to given API object
:param PushBullet api: API object to bind to
:returns: self
'''
assert(isinstance(api, PushBullet))
self.api = api
return self
@property
def bound(self):
'''
True if an object is bound to an API object
'''
return bool(getattr(self, 'api', None))
def reload(self):
self.__dict__.update(self.api.get(self.uri))
return self
@classmethod
def iterate(cls, api, skip_inactive=True, since=0, limit=None):
it = api.paged(cls.collection_name,
modified_after=parse_since(since),
limit=limit)
if skip_inactive:
return (cls(api, **o) for o in it if o.get('active', False))
else:
return (cls(api, **o) for o in it)
def get(self, name, default=None):
return getattr(self, name, default)
def json(self):
return dict(self.__dict__)
def __contains__(self, name):
return hasattr(self, name)
def __str__(self):
return unicode(self).encode('utf8')
class ObjectWithIden(object):
@classmethod
def load(cls, api, iden):
self = cls()
self.bind(api)
self.iden = iden
self.reload()
return self
def __init__(self, api, iden=None, **data):
self.iden = iden
self.__dict__.update(data)
self.bind(api)
@property
def uri(self):
return '%s/%s' % (self.collection_name, self.iden)
class Grant(ObjectWithIden, PushBulletObject):
collection_name = 'grants'
def __repr__(self):
return (u'<Grant[%s]: %s>' % (self.iden, self.client['name'])).encode('utf-8')
def __unicode__(self):
return u'grant for %s' % (self.client['name'])
class Subscription(ObjectWithIden, PushBulletObject):
collection_name = 'subscriptions'
def __repr__(self):
return (u'<Subscription[%s] %s>' % (self.iden, getattr(self, 'channel', {}).get('tag', 'untagged'))).encode('utf-8')
def __unicode__(self):
channel = getattr(self, 'channel', {})
return u'%s (%s)' % (
channel.get('name', 'Unnamed'),
channel.get('tag', 'untagged'))
def channel(self):
return ChannelInfo(self.api, **getattr(self, 'channel', {}))
def create(self, channel_tag):
if self.iden:
raise PushBulletError('subscription already exists')
if isinstance(channel_tag, (ChannelInfo, Channel)):
channel_tag = channel_tag.tag
self.__dict__.update(self.api.post('subscriptions', channel_tag=str(channel_tag)))
return self
class ChannelInfo(ObjectWithIden, PushBulletObject):
collection_name = 'channel-info'
@classmethod
def load_by_tag(cls, api, tag):
return cls(api, **api.get('/channel-info', tag=utf8(tag)))
def __repr__(self):
return (u'<ChannelInfo[%s]: %s (%s)>' % (self.iden,
getattr(self, 'name', 'Unnamed'),
getattr(self, 'tag', 'untagged'))).encode('utf-8')
def __unicode__(self):
return u'%s (%s)' % (
getattr(self, 'name', 'Unnamed'),
getattr(self, 'tag', 'untagged'))
def subscribe(self):
return Subscription(self.api, None).create(self.tag)
# Push targets {{{
class PushTarget(PushBulletObject):
'''
Abstract push target object
'''
@property
def ident(self):
'''
Interface property with parameters to identify given push target
:rtype: dict
'''
raise NotImplementedError
def push(self, push=None, **pushargs):
'''
Push a message to the push target
Either `push` or `pushargs` must be given.
If both are present, `pushargs` are ignored.
:param Push push: a push object
:param dict pushargs: parameters to construct push object
'''
if not isinstance(push, Push):
push = self.api.make_push(pushargs, push)
push.send(self)
return push
class Channel(PushTarget, ObjectWithIden):
'''
Channel to push to
'''
collection_name = 'channels'
def __repr__(self):
return (u'<Channel[%s]: %s (%s)>' % (self.iden,
getattr(self, 'name', 'Unnamed'),
getattr(self, 'tag', 'untagged'))).encode('utf-8')
def __unicode__(self):
return u'%s (%s)' % (
getattr(self, 'name', 'Unnamed'),
getattr(self, 'tag', 'untagged'))
@property
def ident(self):
return {'channel_tag': self.tag}
def create(self):
if self.iden:
raise PushBulletError('channel already exists')
self.__dict__.update(self.api.post('clients',
tag=self.tag,
name=getattr(self, 'name', None),
description=getattr(self, 'description', None),
feed_url=getattr(self, 'feed_url', None),
feed_filters=getattr(self, 'feed_filters', None)))
return self
def update(self):
if not self.iden:
raise PushBulletError('channel does not exist yet')
self.__dict__.update(self.api.post(self.uri,
name=getattr(self, 'name', None),
description=getattr(self, 'description', None),
feed_url=getattr(self, 'feed_url', None),
feed_filters=getattr(self, 'feed_filters', None)))
return self
def subscribe(self):
return Subscription(self.api, None).create(self.tag)
class Client(PushTarget, ObjectWithIden):
'''
Current user's OAuth client
By pushing to it you push to all users, who granted access to the client.
'''
collection_name = 'clients'
def __repr__(self):
return (u'<Client[%s]: %s>' % (self.iden, getattr(self, 'name', 'Unnamed'))).encode('utf-8')
def __unicode__(self):
return getattr(self, 'name', 'Unnamed')
@property
def ident(self):
return {'client_iden': self.iden}
class Contact(ObjectWithIden, PushTarget):
'''
Contact to push to
'''
collection_name = 'contacts'
def __repr__(self):
return (u'<Contact[%s]: %s <%s>>' % (self.iden,
getattr(self, 'name', 'Unnamed'),
getattr(self, 'email', None) or getattr(self, 'email_normalized'))).encode('utf-8')
def __unicode__(self):
return u'%s <%s>' % (self.name, self.email)
@property
def ident(self):
return {'email': self.email_normalized}
def create(self):
if self.iden:
raise PushBulletError('contact already exists')
self.__dict__.update(self.api.post('contacts', name=self.name, email=self.email))
return self
def update(self):
if not self.iden:
raise PushBulletError('contact does not exist yet')
self.__dict__.update(self.api.post(self.uri, name=self.name))
return self
def rename(self, newname):
self.name = newname
return self.update()
class Device(ObjectWithIden, PushTarget):
'''
Device to push to
'''
collection_name = 'devices'
def __repr__(self):
return (u'<Device[%s]: %s>' % (self.iden,
getattr(self, 'nickname', None) or
getattr(self, 'model', None) or
'Unnamed')).encode('utf-8')
def __unicode__(self):
return (getattr(self, 'nickname', None) or
getattr(self, 'model', None) or
self.iden)
@property
def ident(self):
return {'device_iden': self.iden}
def create(self):
if self.iden:
raise PushBulletError('device already exists')
self.__dict__.update(self.api.post('devices', nickname=self.nickname, type=getattr(self, 'type', 'stream')))
return self
def update(self):
if not self.iden:
raise PushBulletError('device does not exist yet')
self.__dict__.update(self.api.post(self.uri, nickname=self.nickname))
return self
def rename(self, newname):
self.nickname = newname
return self.update()
class PhoneNumber(PushTarget):
'''
Phone number to push SMS to
'''
device = None
number = None
def __init__(self, device, number):
assert isinstance(device, Device)
self.device = device
self.number = str(number)
@property
def ident(self):
return {
'type': 'messaging_extension_reply',
'package_name': 'com.pushbullet.android',
'conversation_iden': self.number,
'target_device_iden': self.device.iden,
'source_user_iden': self.api.me.iden
}
def push(self, push=None, **pushargs):
api = self.device.api
if not isinstance(push, Push):
push = api.make_push(pushargs, push)
data = self.ident
data['message'] = push.body
api.post("ephemerals", type="push", push=data)
return push
def __repr__(self):
return (u'<PhoneNumber[%s] device=%s>' % (self.number, self.device)).encode('utf-8')
def __unicode__(self):
return self.number
class User(PushTarget):
'''
User profile
'''
def __init__(self, api, **data):
self.__dict__.update(data)
self.bind(api)
@classmethod
def load(cls, api):
return cls(api, **api.get('users/me'))
def __repr__(self):
return (u'<User[%s]: %s <%s>>' % (self.iden,
getattr(self, 'name', 'Unnamed'),
getattr(self, 'email', None) or getattr(self, 'email_normalized'))).encode('utf-8')
@property
def ident(self):
return {}
@property
def uri(self):
return 'users/me'
def update(self):
self.__dict__.update(self.api.post(self.uri, preferences=getattr(self, 'preferences', {})))
return self
def set_prefs(self, **prefs):
try:
self.preferences.update(prefs)
except AttributeError:
self.prefereces = prefs
return self.update()
# }}}
# Pushes {{{
class Push(PushBulletObject):
'''
Abstract push object
'''
type = None
collection_name = 'pushes'
@property
def uri(self):
return "pushes/%s" % self.iden
def decode(self):
try:
self.modified = datetime.datetime.fromtimestamp(self.modified)
except AttributeError:
pass
try:
self.created = datetime.datetime.fromtimestamp(self.created)
except AttributeError:
pass
def send(self, target=None):
'''
Send the push to some target
If target is None (or omitted) or a string, the push must be bound to some API.
By default the push will be sent to API object (i.e. all user devices).
If target is a string, it must be a device iden to push to.
If you use anything except for Device, Contact or PushBullet object as a target
(i.e. a PushTarget object), you must make sure a push is bound to PushBullet
object before by calling `push.bind(api)` method.
Push is already bound if you fetched it with `api.pushes()` call
or sent it before.
:param target: push target
:type target: PushTarget|str|None
'''
if not isinstance(target, PushTarget):
target = self.api.make_target(target)
self.bind(target.api)
data = self.data
data.update(target.ident)
data['type'] = self.type
result = self.api.post('pushes', **data)
self.__dict__.update(result)
def resend(self):
'''
Try to send the push to the same target again (e.g. as a part of error handling logic)
'''
if not hasattr(self, 'target_device_iden'):
raise PushBulletError('push was not sent yet')
self.send(self.target_device_iden)
def update(self):
self.__dict__.update(self.api.post(self.uri, dissmissed=getattr(self, 'dismissed', False)))
return self
def dismiss(self):
'''
Dismiss a push
'''
if getattr(self, 'dismissed', False):
return # don't dismiss twice
self.dismissed = True
return self.update()
@property
def data(self):
'''
Push data necessary to send push to a target
:rtype: dict
'''
raise NotImplementedError
@property
def target_device(self):
'''
Get target device object
'''
iden = self.get('target_device_iden')
return Device(self.api, iden) if iden else None
@property
def source_device(self):
'''
Get source device object
'''
iden = self.get('source_device_iden')
return Device(self.api, iden) if iden else None
def __eq__(self, other):
return isinstance(other, Push) and self.iden == other.iden
def __repr__(self):
return (u'<%s[%s]: %s>' % (self.__class__.__name__, getattr(self, 'iden', None), unicode(self))).encode('utf-8')
def __unicode__(self):
return u'%s push' % getattr(self, 'type', 'general')
class NotePush(Push):
'''
Note push
'''
type = 'note'
def __init__(self, body='', title='', **data):
'''
A note push constructor
Notes has both body and title parameters optional, but at least one of them
must be defined for the push to be useful. The `title` argument defaults to "Note"
by PushBullet service, so I choose to require at least `body` argument.
If you really don't need body (you should define `title` then, or you will end up
with empty note, which usually has no sense), set it to empty string `''`.
:type body: str
:type title: str
'''
self.title, self.body = utf8(title), utf8(body)
Push.__init__(self, **data)
@property
def data(self):
return {'title': self.title, 'body': self.body}
def __unicode__(self):
return self.title
class LinkPush(Push):
'''
Link push
'''
type = 'link'
def __init__(self, url, title='', body='', **data):
'''
A link push constructor
URL is the only required argument, otherwise the push is actually useless.
You can of cause set it to empty string (`''`), but what is the use of it?
:type url: str
:type title: str
:type body: str
'''
self.title, self.url, self.body = utf8(title), utf8(url), utf8(body)
Push.__init__(self, **data)
@property
def data(self):
return {'title': self.title, 'url': self.url, 'body': self.body}
def __unicode__(self):
return self.url
class AddressPush(Push):
'''
Address push
'''
type = 'address'
def __init__(self, address, name='', **data):
'''
An address push constructor
Address argument is the only required argument here.
The push actually has no sense without it, doesn't it?
:type address: str
:type name: str
'''
self.name, self.address = utf8(name), utf8(address)
Push.__init__(self, **data)
@property
def data(self):
return {'name': self.name, 'address': self.address}
def __unicode__(self):
return u'%s (%s)' % (self.name, self.address)
class ListPush(Push):
'''
List push
'''
type = 'list'
def __init__(self, items, title='', **data):
'''
A list push constructor
Items argument is the only required one, and it should be a list
of strings. Of cause you can send empty list (`[]`), but what is the use of it?
:type items: list of str
:type title: str
'''
self.title, self.items = utf8(title), map(utf8, items)
Push.__init__(self, **data)
@property
def data(self):
return {'title': self.title, 'items': self.items}
def __unicode__(self):
return u'%s (%d)' % (self.title, len(self.items))
class FilePush(Push):
'''
File push
'''
type = 'file'
def __init__(self, file=None, file_name=None, file_type=None, body='', **data):
'''
A file push constructor
You must specify at least `file` argument in order to be able to push some new file
The `file` argument is optional only for internal usage, like if a file push fetched
by `api.pushes()` method call, in which case file to push is undefined, but `file_url`
is present to download the file. If you then resend such push, file designated by `file_url`
will be sent, not any new file set by you. You can use this knowledge to try and
set `file_url` directly on `FilePush` object without setting `file` argument on your
own risk, but bear in mind it's an internal implementation detail, so please make sure you
a) understand what you are doing, b) don't abuse the feature.
If you specify `file` only, it must be either a file-like object, a file-handler opened for read,
a buffer (for in-memory files), an openable object (the one with `open([mode])` method)
or a string with absolute file path.
You will see basename of the file (the part of path after final slash).
If you specify both `file` and `file_name`, a push receiver will see `file_name` value
as a file name, not the actual file name. You can use it for example to send some
system stream without user-friendly name, like `sys.stdin`.
The `file_type` argument is optional and must be a string in MIME-type format (e.g. `text/plain`).
If you omit it, file type will be deteremined by magic library by file's content, and if
autodetection will fail, file type will default to `application/octet-stream`.
The autodetection reads first 1024 bytes of file content and then resets file's seek cursor
to the beginning, so it won't work for non-seekable streams, so if you are about to push
something like `sys.stdin`, make sure you set `file_type` manually.
:param file: file to push
:type file: str, file, buffer, int, Path or any file-like or openable object
:param str file_name: file name to push (will be visible to reciever)
:param str file_type: file's MIME type (will be determined by file's content if omitted)
:param str body: optional message to accompany file
'''
assert(file or file_name)
self.file, self.file_name, self.file_type = file, utf8(file_name), utf8(file_type)
if not self.file:
self.file = self.file_name
self.file_url = None
self.body = utf8(body)
Push.__init__(self, **data)
def send(self, target=None):
if not isinstance(target, PushTarget):
target = self.api.make_target(target)
if not self.file_url: # file not uploaded yet
fh = (self.file if hasattr(self.file, 'read') else # file-like object
self.file.open('rb') if hasattr(self.file, 'open') else # openable object
os.fdopen(self.file, 'rb') if isinstance(self.file, int) else # file descriptor
StringIO(self.file) if isinstance(self.file, buffer) else # in-memory file
open(self.file, 'rb')) # file name
try:
file_name = utf8(self.file_name) if self.file_name else os.path.basename(fh.name)
file_type = utf8(self.file_type) if self.file_type else self.guess_type(fh)
req = target.api.get('upload-request', file_name=file_name, file_type=file_type)
target.api.upload(req['upload_url'], data=req['data'], file=fh)
self.file_name, self.file_type, self.file_url = req['file_name'], req['file_type'], req['file_url']
finally:
fh.close()
Push.send(self, target)
def guess_type(self, file):
try:
import magic
guesser = magic.open(magic.MIME_TYPE)
guesser.load()
mime_type = guesser.buffer(file.read(1024))
file.seek(0)
return mime_type or 'application/octet-stream'
except:
return 'application/octet-stream'
@property
def data(self):
return {'file_name': self.file_name, 'file_type': self.file_type, 'file_url': self.file_url, 'body': self.body}
def __unicode__(self):
return self.file_name
class MirrorPush(Push):
'''
Mirror push (internal usage only)
'''
type = 'mirror'
def decode(self):
super(MirrorPush, self).decode()
try:
self.icon = base64.decodestring(self.icon)
except (AttributeError, binascii.Error):
pass