forked from huyz/wayslack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wayslack.py
executable file
·1631 lines (1422 loc) · 59.4 KB
/
wayslack.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
#!/usr/bin/env python
import os
import re
import sys
import time
import shutil
import urllib
import atexit
import hashlib
import argparse
import codecs
import stat
from Queue import Queue
from random import random
from threading import Thread
from itertools import groupby
from datetime import datetime, timedelta
try:
import ujson as json
except ImportError:
import json
import json as std_json
import yaml
import pathlib
import requests
from requests.exceptions import HTTPError, ReadTimeout, ConnectionError
from slacker import Slacker, Error
from slacker.utilities import get_api_url
DEBUG = False
VERBOSE = False
JSON_INDENT = 4
# In support of the OAuth flow, these are parameters of the "Gimme Slack" app,
# which has been configured with the Redirect URLs:
# - https://huyz.github.io/wayslack/oauth
# (See GitHub Page https://github.com/huyz/wayslack/blob/gh-pages/oauth.html)
# - http://not.a.realhost/
CLIENT_ID = "2526404912.1280845319991"
CLIENT_SECRET = "76c84535a544d8e70750725feffa6ffb" # Not really a secret.
ATTR_TO_PACKAGE = {
'channels': 'conversations',
'groups': 'conversations',
'im': 'conversations',
'mpim': 'conversations',
'users': 'users',
'files': 'files',
'emoji': 'emoji',
}
ATTR_TO_CONVO_TYPE = {
'channels': 'public_channel',
'groups': 'private_channel',
'im': 'im',
'mpim': 'mpim',
}
BOT_SCOPE = (
"app_mentions:read,calls:read,channels:history,channels:join,channels:read,dnd:read"
",emoji:read,files:read,groups:history,groups:read,im:history,im:read,incoming-webhook"
",links:read,mpim:history,mpim:read,pins:read,reactions:read,reminders:read"
",remote_files:read,team:read,usergroups:read,users.profile:read,users:read"
",users:read.email,files:write"
)
USER_SCOPE = (
"calls:read,channels:history,channels:read,dnd:read,emoji:read,files:read,groups:history"
",groups:read,identify,im:history,im:read,links:read,mpim:history,mpim:read,pins:read"
",reactions:read,reminders:read,remote_files:read,search:read,stars:read,team:read"
",usergroups:read,users.profile:read,users:read,users:read.email,files:write"
)
REDIRECT_URI_GITHUB = "https://huyz.github.io/wayslack/oauth"
REDIRECT_URI_PARANOID = "http://not.a.realhost/"
def is_slack_url(url):
return ".slack.com/" in url or "slack-edge.com/" in url or "slack-files.com/" in url
def json_dump(obj, fp):
# Indentation and sorting keys is friendlier for git diffs
json.dump(obj, fp, ensure_ascii=False, indent=JSON_INDENT, sort_keys=True)
def ts2datetime(ts):
return datetime.fromtimestamp(ts)
def ts2ymd(ts):
return ts2datetime(float(ts)).strftime("%Y-%m-%d")
def assert_successful(r):
if not r.successful:
raise AssertionError("Request failed: %s" %(r.error, ))
def parse_age_str(s):
match = re.search("(\d+)\s(m|d)", s)
if not match:
return None
count_str, age_str = match.groups()
try:
count = int(count_str)
except ValueError:
return None
multiplier = {"m": 30, "d": 1}.get(age_str)
if not multiplier:
return None
return datetime.now() - timedelta(days=count * multiplier)
def slack_retry(method, *args, **kwargs):
attempt = 1
while True:
try:
return method(*args, **kwargs)
except (HTTPError, ConnectionError, ReadTimeout) as e:
if isinstance(e, ReadTimeout) or isinstance(e, ConnectionError):
if attempt > 3:
raise
delay = 30
# As of 2020-08-16, it looks like Slack now temporarily hangs requests rather than returning an error,
# probably because it's easier for users to handle this kind of throttling.
# This change may have happened then: https://api.slack.com/changelog/2018-03-great-rate-limits
elif "Too Many Requests" in str(e):
delay = int(e.response.headers["Retry-After"])
else:
raise
# Note: introduce backoff + random delay so concurrent requests don't spam
delay = int(delay * (2 ** (attempt * (1 * random()))))
delay = max(delay, 30)
if VERBOSE:
if isinstance(e, ReadTimeout) or isinstance(e, ConnectionError):
print "WARNING: Slack aborted or timed out request for %r (retrying in %s seconds)" %(
method,
delay,
)
elif "Too Many Requests" in str(e):
print "WARNING: Slack reported Too Many Requests for %r (retrying in %s seconds)" %(
method,
delay,
)
time.sleep(delay)
attempt += 1
# Source: https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/string_.py
def to_str(obj, encoding='utf-8', **encode_args):
r"""
Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
example::
>>> some_str = b"\xff"
>>> some_unicode = u"\u1234"
>>> some_exception = Exception(u'Error: ' + some_unicode)
>>> r(to_str(some_str))
b'\xff'
>>> r(to_str(some_unicode))
b'\xe1\x88\xb4'
>>> r(to_str(some_exception))
b'Error: \xe1\x88\xb4'
>>> r(to_str([42]))
b'[42]'
See source code for detailed semantics.
"""
# Note: On py3, ``b'x'.__str__()`` returns ``"b'x'"``, so we need to do the
# explicit check first.
if isinstance(obj, str):
return obj
# We coerce to unicode if '__unicode__' is available because there is no
# way to specify encoding when calling ``str(obj)``, so, eg,
# ``str(Exception(u'\u1234'))`` will explode.
if isinstance(obj, unicode) or hasattr(obj, "__unicode__"):
# Note: unicode(u'foo') is O(1) (by experimentation)
return unicode(obj).encode(encoding, **encode_args)
return str(obj)
# Source: https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/contextlib_.py
class open_atomic(object):
"""
Opens a file for atomic writing by writing to a temporary file, then moving
the temporary file into place once writing has finished.
When ``close()`` is called, the temporary file is moved into place,
overwriting any file which may already exist (except on Windows, see note
below). If moving the temporary file fails, ``abort()`` will be called *and
an exception will be raised*.
If ``abort()`` is called the temporary file will be removed and the
``aborted`` attribute will be set to ``True``. No exception will be raised
if an error is encountered while removing the temporary file; instead, the
``abort_error`` attribute will be set to the exception raised by
``os.remove`` (note: on Windows, if ``file.close()`` raises an exception,
``abort_error`` will be set to that exception; see implementation of
``abort()`` for details).
By default, ``open_atomic`` will put the temporary file in the same
directory as the target file:
``${dirname(target_file)}/.${basename(target_file)}.temp``. See also the
``prefix``, ``suffix``, and ``dir`` arguments to ``open_atomic()``. When
changing these options, remember:
* The source and the destination must be on the same filesystem,
otherwise the call to ``os.replace()``/``os.rename()`` may fail (and
it *will* be much slower than necessary).
* Using a random temporary name is likely a poor idea, as random names
will mean it's more likely that temporary files will be left
abandoned if a process is killed and re-started.
* The temporary file will be blindly overwritten.
The ``temp_name`` and ``target_name`` attributes store the temporary
and target file names, and the ``name`` attribute stores the "current"
name: if the file is still being written it will store the ``temp_name``,
and if the temporary file has been moved into place it will store the
``target_name``.
.. note::
``open_atomic`` will not work correctly on Windows with Python 2.X or
Python <= 3.2: the call to ``open_atomic.close()`` will fail when the
destination file exists (since ``os.rename`` will not overwrite the
destination file; an exception will be raised and ``abort()`` will be
called). On Python 3.3 and up ``os.replace`` will be used, which
will be safe and atomic on both Windows and Unix.
Example::
>>> _doctest_setup()
>>> f = open_atomic("/tmp/open_atomic-example.txt")
>>> f.temp_name
'/tmp/.open_atomic-example.txt.temp'
>>> f.write("Hello, world!") and None
>>> (os.path.exists(f.target_name), os.path.exists(f.temp_name))
(False, True)
>>> f.close()
>>> os.path.exists("/tmp/open_atomic-example.txt")
True
By default, ``open_atomic`` uses the ``open`` builtin, but this behaviour
can be changed using the ``opener`` argument::
>>> import io
>>> f = open_atomic("/tmp/open_atomic-example.txt",
... opener=io.open,
... mode="w+",
... encoding="utf-8")
>>> some_text = u"\u1234"
>>> f.write(some_text) and None
>>> f.seek(0)
0
>>> f.read() == some_text
True
>>> f.close()
"""
def __init__(self, name, mode="w", prefix=".", suffix=".temp", dir=None,
opener=open, **open_args):
self.target_name = name
self.temp_name = self._get_temp_name(name, prefix, suffix, dir)
self.file = opener(self.temp_name, mode, **open_args)
self.name = self.temp_name
self.closed = False
self.aborted = False
self.abort_error = None
def _get_temp_name(self, target, prefix, suffix, dir):
if dir is None:
dir = os.path.dirname(target)
return os.path.join(dir, "%s%s%s" %(
prefix, os.path.basename(target), suffix,
))
def close(self):
if self.closed:
return
try:
self.file.close()
os.rename(self.temp_name, self.target_name)
self.name = self.target_name
except:
try:
self.abort()
except:
pass
raise
self.closed = True
def abort(self):
try:
if os.name == "nt":
# Note: Windows can't remove an open file, so sacrifice some
# safety and close it before deleting it here. This is only a
# problem if ``.close()`` raises an exception, which it really
# shouldn't... But it's probably a better idea to be safe.
self.file.close()
os.remove(self.temp_name)
except OSError as e:
self.abort_error = e
self.file.close()
self.closed = True
self.aborted = True
def __enter__(self):
return self
def __exit__(self, *exc_info):
if exc_info[0] is None:
self.close()
else:
self.abort()
def __getattr__(self, attr):
return getattr(self.file, attr)
class open_atomic_utf8(open_atomic):
def __init__(self, name, **kwargs):
kwargs.update({
"opener": codecs.open,
"encoding": "utf-8",
})
super(open_atomic_utf8, self).__init__(name, **kwargs)
def pluck(dict, keys):
return [(k, dict[k]) for k in keys if k in dict]
def sha256(s):
return hashlib.sha256(s).hexdigest()
def url_to_filename(url, _t_re=re.compile("\?t=[^&]*$")):
if is_slack_url(url):
url = _t_re.sub("", url)
url = urllib.quote(url.encode('utf8'), safe="")
if len(url) > 190:
url = url[:50] + "+" + sha256(url) + "+" + url[-50:]
return url
class Threadpool(object):
_stop = object()
def __init__(self, func, thread_count=10, queue_size=1000):
self._func = func
self._queue = Queue(maxsize=queue_size)
self._stop = False
self._threads = [
Thread(target=self._run_thread, args=(idx, ))
for idx in range(thread_count)
]
self._thread_current_item = [
self._stop for _ in self._threads
]
for t in self._threads:
t.start()
def put(self, item):
self._queue.put(item)
def qsize(self):
return self._queue.qsize()
def stop(self):
for _ in self._threads:
self._queue.put(self._stop)
def join(self):
self.stop()
for thread in self._threads:
thread.join()
def _run_thread(self, idx):
# To stop thread when the queue isn't empty?
while not self._stop:
try:
item = self._queue.get()
if item is self._stop:
return
self._thread_current_item[idx] = item
self._func(self._thread_current_item[idx])
finally:
self._thread_current_item[idx] = self._stop
def iter_incomplete(self):
for item in self._thread_current_item:
if item is not self._stop:
yield item
for item in self._queue.queue:
if item is self._stop:
continue
yield item
class Downloader(object):
def __init__(self, token, path, no_download=False):
self.counter = 0
self.token = token
self.path = path
if not path.exists():
self.path.mkdir(parents=True)
self.lockdir = self.path / "_lockdir"
if self.lockdir.exists():
shutil.rmtree(str(self.lockdir))
self.lockdir.mkdir()
self.pending_file = self.path / "pending.json"
self.pool = Threadpool(self._downloader)
if self.pending_file.exists():
pending = json.loads(self.pending_file.open().read())
for item in pending:
self.pool.put(item)
atexit.register(self._write_pending)
self.no_download = no_download
def _write_pending(self):
try:
self.pool.join()
finally:
to_write = list(self.pool.iter_incomplete())
if not to_write:
try:
self.pending_file.unlink()
except OSError:
pass
return
with open_atomic(str(self.pending_file)) as f:
json_dump(to_write, f)
def join(self):
self.pool.join()
def _downloader(self, item):
lockdir = None
try:
url, target = item
if os.path.exists(target):
return
base, joiner, name = target.rpartition("/")
lockdir = self.lockdir / name
try:
lockdir.mkdir()
except OSError:
lockdir = None
return
meta_file = base + joiner + "meta-" + name + ".txt"
try:
# Some sites hang and time out if there's no (real?) user-agent
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
}
if is_slack_url(url):
headers["Authorization"] = "Bearer %s" %(self.token, )
res = requests.get(
url,
headers=headers,
stream=True,
timeout=60,
)
except Exception as e:
print "ERROR:", e
with open_atomic(meta_file) as meta:
meta.write("999\nException: %r" %(e, ))
return
with open_atomic(meta_file) as meta, open_atomic(target) as f:
meta.write("%s\n%s" %(
res.status_code,
"\n".join(
"%s: %s" %(key, res.headers[key])
for key
in res.headers
),
))
hash = hashlib.md5()
for chunk in res.iter_content(4096):
hash.update(chunk)
f.write(chunk)
# XXX Slack generally sends an MD5 checksum in the Etag, but they seem to
# occasionally version Etags which breaks the checksum somehow.
if VERBOSE and is_slack_url(url):
etag = res.headers.get("etag")
if etag:
etag = etag.strip('"')
if etag and hash.hexdigest() != etag:
print("WARNING: Downloading %r: checksum does not match. etag %r != md5 %r\n" %(
url,
etag,
hash.hexdigest(),
))
self.counter += 1
print "Downloaded %s (%s left): %s" %(
self.counter,
self.pool.qsize(),
url,
)
except:
if item is not None:
self.pool.put(item)
raise
finally:
if lockdir is not None:
lockdir.rmdir()
def _download_path(self, url):
return self.path / url_to_filename(url)
def add(self, urls):
if self.no_download:
return
for _, url in urls:
download_path = self._download_path(url)
if not download_path.exists():
self.pool.put((url, str(download_path)))
def is_file_missing(self, file_obj):
download_path = self._download_path(file_obj["url_private"])
if not download_path.exists():
return "does not exist", download_path
size = download_path.stat().st_size
# Note: Slack appears to compress JPEG files, so ignore this error if
# the image is a JPEG (the integrity will be checked by the downloader
# to ensure that the file content is correct, but it may not be
# identical to the file originally uploaded).
if size != file_obj["size"] and file_obj["mimetype"] != "image/jpeg":
msg = "size does not match (actual size %s != expected size %s)" %(
size,
file_obj["size"],
)
return msg, download_path
return None, download_path
def add_file(self, file_obj):
self.add(pluck(file_obj, [
"url_private",
"thumb_480",
]))
def add_message(self, msg):
for file_obj in msg.get("files") or msg.get("file") or []:
self.add_file(file_obj)
for att in msg.get("attachments") or []:
self.add(pluck(att, [
"service_icon",
"thumb_url",
]))
def add_user_profile(self, profile):
self.add([
(k, "%s#%s" %(url, profile.get("avatar_hash")))
for (k, url) in pluck(profile, [
"image_512",
"image_192",
"image_72",
])
])
class ItemBase(object):
def __init__(self, attr, slack, downloader, path, obj):
self.attr = attr
self.downloader = downloader
self.slack = slack
self.__dict__.update(obj)
self.path = path
self.pretty_name = (
"#" + obj["name"] if "name" in obj else
"im:" + obj["user"]
)
@property
def _is_bot_token(self):
return self._package.token.startswith("xoxb-")
@property
def _package(self):
return getattr(self.slack, ATTR_TO_PACKAGE[self.attr])
@staticmethod
def _is_trunk_message(msg):
return "thread_ts" not in msg or msg["thread_ts"] == msg["ts"]
@staticmethod
def _is_broadcast_message(msg):
return msg.get("subtype") == "thread_broadcast"
def refresh(self):
self._refresh_messages()
def download_all_files(self):
for archive in self.iter_archives():
for msg in self.load_messages(archive):
if "file" in msg or "files" in msg or "attachments" in msg:
self.downloader.add_message(msg)
def iter_archives(self, reverse=False):
if not self.path.exists():
return
for f in sorted(self.path.glob("*.json"), reverse=reverse):
yield f
def load_messages(self, archive):
with archive.open(encoding="utf-8") as f:
return json.load(f)
def _get_list(self, method, latest_ts, **kwargs):
return slack_retry(method,
channel=self.id,
oldest=latest_ts,
limit=1000, # Default is 100
**kwargs
)
def _join_channel(self, slack):
print "Joining channel ", self.pretty_name
return slack_retry(slack.join, channel=self.id)
def _leave_channel(self, slack):
print "Leaving channel ", self.pretty_name
return slack_retry(slack.leave, channel=self.id)
def _refresh_messages(self):
def get_last_saved_replies_ts():
# type: (...) -> Dict[str, str]
"""
:returns: a dict mapping parent message's ts -> replies' last successfully saved ts.
"""
last_saved_replies_ts = dict()
for archive in self.iter_archives(reverse=True):
for msg in sorted(self.load_messages(archive), key=lambda m: m["ts"], reverse=True):
thread_ts = msg.get("thread_ts")
if not self._is_trunk_message(msg) and thread_ts not in last_saved_replies_ts:
last_saved_replies_ts[thread_ts] = msg["ts"]
return last_saved_replies_ts
def write_fresh_messages(type_str, msgs, latest_ts):
for day, day_msgs in groupby(msgs, key=lambda m: ts2ymd(m["ts"])):
day_msgs = list(day_msgs)
day_archive = self.path / (day + ".json")
cur = (
self.load_messages(day_archive)
if day_archive.exists() else []
)
# Track new and updated messages, and at the same time eliminate duplicates
# that may happen to be in the saved files, even though this shouldn't happen.
cur_msgs = {m["ts"] : m for m in cur}
new_count = updated_count = 0
fresh_msgs = []
for msg in day_msgs:
if msg["ts"] in cur_msgs:
if std_json.dumps(msg, sort_keys=True) == std_json.dumps(cur_msgs[msg["ts"]], sort_keys=True):
continue
updated_count += 1
else:
new_count += 1
fresh_msgs.append(msg)
cur_msgs[msg["ts"]] = msg
cur = [cur_msgs[k] for k in sorted(cur_msgs.keys())]
if new_count > 0:
print "%s: %s new %s messages in %s (saving to %s)" %(
self.pretty_name, new_count, type_str, self.pretty_name, day_archive,
)
if updated_count > 0:
print "%s: %s updated %s messages in %s (saving to %s)" %(
self.pretty_name, updated_count, type_str, self.pretty_name, day_archive,
)
for msg in fresh_msgs:
if "file" in msg or "files" in msg or "attachments" in msg:
self.downloader.add_message(msg)
with open_atomic_utf8(str(day_archive)) as f:
json_dump(cur, f)
if len(day_msgs) > 0 and float(day_msgs[-1]["ts"]) > float(latest_ts):
latest_ts = day_msgs[-1]["ts"]
return latest_ts
slack = self._package
# For public channels, bot user tokens need to auto-join or otherwise get `not_in_channel`.
# For archived channels, this becomes even more complicated as the channel would have to
# be unarchived before joining is possible.
# In contrast, personal oauth tokens don't need to be a member of the public channel to get
# messages, even if the channel is archived. For other reasons, including getting
# conversations.replies, you should be using a bot *user* token anyway.
if self.attr == "channels" and self._is_bot_token and not self.is_member:
if self.is_archived:
print "%s: Skipping archived channel because of bot token (try a personal oauth token instead)" %(
self.pretty_name
)
return
self._join_channel(slack)
last_saved_replies_ts = get_last_saved_replies_ts()
threads_to_fetch = []
# It's important to start at 1 and not 0. If you put in 0, the Slack
# API will give the 1000 latest messages in the first page. But we want
# the oldest to paginate forward
latest_ts = 1
cursor = None
while True:
resp = self._get_list(slack.history, latest_ts, cursor=cursor)
assert_successful(resp)
cursor = resp.body.get("response_metadata", {}).get("next_cursor")
# Filter out the broadcast messages that we're already handling among thread replies.
# (It's important to let the fetch of replies handle these messages as we rely on the
# continuity to compute get_last_saved_replies_ts)
msgs = filter(lambda m: not self._is_broadcast_message(m), resp.body["messages"])
msgs.sort(key=lambda m: m["ts"])
for msg in msgs:
if msg["ts"] == msg.get("thread_ts"):
if msg["thread_ts"] not in last_saved_replies_ts or \
float(msg["latest_reply"]) > float(last_saved_replies_ts[msg["thread_ts"]]):
threads_to_fetch.append(msg["ts"])
if msgs and not self.path.exists():
self.path.mkdir()
latest_ts = write_fresh_messages("trunk", msgs, latest_ts)
if not cursor and not resp.body["has_more"]:
break
for thread_ts in threads_to_fetch:
# It's important to start at 1 and not 0. If you put in 0, the Slack
# API will give the 1000 latest messages in the first page. But we want
# the oldest to paginate forward
latest_ts = last_saved_replies_ts.get(thread_ts, 1)
cursor = None
while True:
resp = self._get_list(slack.replies, latest_ts, cursor=cursor, ts=thread_ts)
assert_successful(resp)
cursor = resp.body.get("response_metadata", {}).get("next_cursor")
# Filter out the parent messages that we've already added during the fetch of trunk messages.
# (The first message in a conversations.replies will always be the parent message,
# no matter what the `oldest` parameter.)
msgs = filter(lambda m: not self._is_trunk_message(m), resp.body["messages"])
msgs.sort(key=lambda m: m["ts"])
if msgs and not self.path.exists():
self.path.mkdir()
latest_ts = write_fresh_messages("reply", msgs, latest_ts)
if not cursor and not resp.body["has_more"]:
break
class BaseArchiver(object):
name = None
item_class = ItemBase
def __init__(self, archive, path):
self.archive = archive
self.slack = archive.slack
self.json_file = path / ("%s.json" %(self.name, ))
self.path = path
def get_list(self):
if not self.json_file.exists():
return []
with self.json_file.open(encoding="utf-8") as f:
return [
self.item_class(self.attr, self.slack, self.archive.downloader, self.path / o["id"], o)
for o in json.load(f)
]
@property
def attr(self):
return "im" if self.name == "ims" else "mpim" if self.name == "mpims" else self.name
@property
def _is_bot_token(self):
return self._package.token.startswith("xoxb-")
@property
def _package(self):
return getattr(self.slack, ATTR_TO_PACKAGE[self.attr])
@property
def _is_convo_type(self):
return self.attr in ATTR_TO_CONVO_TYPE
@property
def _list_args(self):
return {"types": ATTR_TO_CONVO_TYPE[self.attr], "limit": 1000} \
if self.attr in ATTR_TO_CONVO_TYPE else dict()
def update(self):
resp = self._package.list(**self._list_args)
assert_successful(resp)
resp_field = (
"members" if self.name == "users" else
"channels" if self._is_convo_type else
self.name
)
objs = resp.body[resp_field]
objs_json = std_json.dumps(objs, sort_keys=True)
try:
old_objs_json = self.json_file.open(encoding="utf-8").read()
except IOError:
old_objs_json = None
if objs_json == old_objs_json:
return
if not self.path.exists():
self.path.mkdir()
ts = datetime.now().isoformat()
if self.json_file.exists():
archive_path = self.path / "_json-archive"
if not archive_path.exists():
archive_path.mkdir()
os.rename(
str(self.json_file),
str(archive_path / ("%s-%s.json" %(self.name, ts))),
)
with open_atomic_utf8(str(self.json_file)) as f:
f.write(unicode(objs_json))
def upgrade(self):
return
yield
def refresh(self):
self.update()
for obj in self.get_list():
obj.refresh()
def download_all_files(self):
for obj in self.get_list():
obj.download_all_files()
class ArchiveChannels(BaseArchiver):
name = "channels"
def upgrade(self):
archive_channels = self.archive.path / "channels.json"
if archive_channels.exists() and not archive_channels.is_symlink():
yield
if not self.path.exists():
self.path.mkdir()
archive_channels.rename(self.json_file)
archive_channels.symlink_to(os.path.relpath(
str(self.json_file),
str(archive_channels.parent),
))
for chandir in self.archive.path.glob("_channel-*"):
yield
target = self.path / chandir.name.replace("_channel-", "")
print "moving %s -> %s" %(chandir, target)
chandir.rename(target)
for chan in self.get_list():
chan_name_dir = self.archive.path / to_str(chan.name)
if chan_name_dir.is_symlink() or not chan_name_dir.exists():
continue
yield
symlink_target = os.path.relpath(
str(chan.path),
str(chan_name_dir.parent),
)
print "linking %s -> %s" %(chan_name_dir, symlink_target)
chan_name_dir.rename(chan.path)
chan_name_dir.symlink_to(symlink_target)
def _fixup_symlinks(self):
for f in self.archive.path.iterdir():
if not f.is_symlink():
continue
if f.exists():
continue
target = os.readlink(str(f))
if "_channels/" in target or "_channel-" in target:
f.unlink()
for chan in self.get_list():
chan_name_dir = self.archive.path / to_str(chan.name)
if chan_name_dir.exists():
continue
symlink_target = os.path.relpath(
str(chan.path),
str(chan_name_dir.parent),
)
chan_name_dir.symlink_to(symlink_target)
archive_channels = self.archive.path / "channels.json"
if not archive_channels.exists():
if archive_channels.is_symlink():
archive_channels.unlink()
archive_channels.symlink_to("_channels/channels.json")
def refresh(self):
BaseArchiver.refresh(self)
self._fixup_symlinks()
class ArchiveGroups(BaseArchiver):
name = "groups"
def _fixup_symlinks(self):
for chan in self.get_list():
chan_name_dir = self.archive.path / to_str(chan.name)
if chan_name_dir.exists():
continue
if chan_name_dir.is_symlink():
chan_name_dir.unlink()
symlink_target = os.path.relpath(
str(chan.path),
str(chan_name_dir.parent),
)
chan_name_dir.symlink_to(symlink_target)
archive_channels = self.archive.path / "groups.json"
if not archive_channels.exists():
if archive_channels.is_symlink():
archive_channels.unlink()
archive_channels.symlink_to("_private/default/_groups/groups.json")
def refresh(self):
BaseArchiver.refresh(self)
self._fixup_symlinks()
class ArchiveMPIMs(BaseArchiver):
name = "mpims"
def _fixup_symlinks(self):
for chan in self.get_list():
chan_name_dir = self.archive.path / to_str(chan.name)
if chan_name_dir.exists():
continue
if chan_name_dir.is_symlink():
chan_name_dir.unlink()
symlink_target = os.path.relpath(
str(chan.path),
str(chan_name_dir.parent),
)
chan_name_dir.symlink_to(symlink_target)
archive_channels = self.archive.path / "mpims.json"
if not archive_channels.exists():
if archive_channels.is_symlink():
archive_channels.unlink()
archive_channels.symlink_to("_private/default/_mpims/mpims.json")
def refresh(self):
BaseArchiver.refresh(self)
self._fixup_symlinks()
class ArchiveIMs(BaseArchiver):
name = "ims"
def _fixup_symlinks(self):
for chan in self.get_list():
chan_name_dir = self.archive.path / to_str(chan.id)
if chan_name_dir.exists():
continue
if chan_name_dir.is_symlink():
chan_name_dir.unlink()
symlink_target = os.path.relpath(
str(chan.path),
str(chan_name_dir.parent),
)
chan_name_dir.symlink_to(symlink_target)
archive_channels = self.archive.path / "dms.json"
if not archive_channels.exists():
if archive_channels.is_symlink():
archive_channels.unlink()
archive_channels.symlink_to("_private/default/_ims/ims.json")
def refresh(self):
BaseArchiver.refresh(self)
self._fixup_symlinks()
class ArchiveUsers(BaseArchiver):
name = "users"
def upgrade(self):
archive_users = self.archive.path / "users.json"
if archive_users.is_symlink() or not archive_users.exists():
return
yield
if not self.path.exists():
self.path.mkdir()
archive_users.rename(self.json_file)
archive_users.symlink_to(os.path.relpath(
str(self.json_file),
str(archive_users.parent),
))
def refresh(self):
self.update()
for user in self.get_list():
self.archive.downloader.add_user_profile(user.profile)
archive_users = self.archive.path / "users.json"
if not archive_users.exists():
archive_users.symlink_to(os.path.relpath(
str(self.json_file),
str(self.archive.path),
))