-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathwebex-space-archive.py
1973 lines (1839 loc) · 93.2 KB
/
webex-space-archive.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
# -*- coding: utf-8 -*-
"""Webex Message Space Archive Script.
Creates a single HTML file with the messages of a Webex Message space
Info/Requirements/release-notes: https://github.com/DJF3/Webex-Message-space-archiver
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately in
writing, software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied.
"""
import json
import datetime
import calendar # for DST support
import re
import time
import sys
import os
import shutil # for file-download with requests
import math # for converting bytes to KB/MB/GB
import string
from pathlib import Path
import configparser
try:
assert sys.version_info[0:2] >= (3, 9)
except:
print("\n\n **ERROR** Minimum Python version is 3.9. Please visit this site to\n install a newer Python version: https://www.python.org/downloads/\n Or in the code, remove line 33 'exit()' to continue with an untested Python version.\n\n")
exit()
try:
import requests
except ImportError:
print("\n\n **ERROR** Missing library 'requests'. Please visit the following site to\n install 'requests': http://docs.python-requests.org/en/master/user/install/ \n\n")
exit()
#--------- DO NOT CHANGE ANYTHING BELOW ---------
__author__ = "Dirk-Jan Uittenbogaard"
__email__ = "[email protected]"
__version__ = "0.30"
__copyright__ = "Copyright (c) 2022 Cisco and/or its affiliates."
__license__ = "Cisco Sample Code License, Version 1.1"
sleepTime = 3
version = __version__
printPerformanceReport = False
printErrorList = True
max_messages = 500
currentDate = datetime.datetime.now().strftime("%x %X")
configFile = "webexspacearchive-config.ini"
myMemberList = dict()
myErrorList = list()
downloadAvatarCount = 1
originalConfigFile = configFile
myRoom = ""
mySearch = ""
# below --> ini maxtotalmessages dateformat. Use %d,%m, %y and %Y, change the order / add slashes
# DON'T use dashes in the date format, only between 2 dates: WRONG: %d-%m-%Y
# correct examples: %Y/%m/%d, %y%m%d, %d%m%Y
maxmsg_format = "%d%m%Y"
def beep(count): # PLAY SOUND (for errors)
for x in range(0, count):
print(chr(7), end="", flush=True)
return
print(f"\n\n\n========================= START ========================={version}")
# First check command line arguments
cl_args = ' '.join(sys.argv[1:]).strip()
cl_count = len(sys.argv) - 1
#___ parameter: nothing - default config file
# = 0 ___
if cl_count == 0:
print(f" Using default config file: {configFile}")
# = 1 ___
#___ parameter: space ID
if cl_count == 1 and "Y2lzY" in cl_args:
myRoom = cl_args
print(f" Alternate Space ID : {myRoom}")
#___ parameter: config_file.ini
elif cl_count == 1 and ".ini" in cl_args:
configFile = cl_args
print(f" Alternate config file: {configFile}")
#___ parameter: space name search argument
elif cl_count == 1:
mySearch = cl_args
print(f" Searching for space containing '{mySearch}'")
# > 1 ___
#___ parameter: Space ID and INI (in no particular order)
if cl_count > 1 and ".ini" in cl_args:
if ".ini" in sys.argv[1]:
configFile = sys.argv[1].strip()
myRoom = sys.argv[2].strip()
elif ".ini" in sys.argv[2]:
configFile = sys.argv[2].strip()
myRoom = sys.argv[1].strip()
print(f" Alternate config file: {configFile}")
print(f" Alternate Space ID : {myRoom}")
elif cl_count > 1:
mySearch = cl_args
print(f" Searching for space containing '{cl_args}'")
config = configparser.ConfigParser(allow_no_value=True)
# ----------- CONFIG FILE: check if config file exists and if the mandatory settings entries are present.
if os.path.isfile("./" + configFile):
try:
config.read('./' + configFile)
if config.has_option('Archive Settings', 'downloadfiles'):
print(" *** NOTE!\n Please change the key 'downloadfiles' in your .ini file to 'download'\n or rename your .ini file and run this script to generate a new .ini file\n\n")
beep(3)
downloadFiles = config['Archive Settings']['downloadfiles'].lower().strip()
else:
downloadFiles = config['Archive Settings']['download'].lower().strip()
if config['Archive Settings']['sortoldnew'] == "yes":
sortOldNew = True
else:
sortOldNew = False
# Webex token in environment variable 'WEBEX_ARCHIVE_TOKEN' or in the .ini file.
if "WEBEX_ARCHIVE_TOKEN" in os.environ:
myToken = os.environ['WEBEX_ARCHIVE_TOKEN']
else:
myToken = config['Archive Settings']['mytoken']
if myRoom == "": # No space id provided as command line parameter
if config.has_option('Archive Settings', 'myroom'): # Added to deal with old naming in .ini files
myRoom = config['Archive Settings']['myroom']
if config.has_option('Archive Settings', 'myspaceid'): # Replacing the old 'myroom' setting
myRoom = config['Archive Settings']['myspaceid']
outputFileName = config['Archive Settings']['outputfilename']
maxTotalMessages = config['Archive Settings']['maxtotalmessages']
if maxTotalMessages:
if 'd' in maxTotalMessages: # Example: maxTotalMessages = 60d = 60 days.
msgMaxAge = int(maxTotalMessages.replace("d", ""))
maxTotalMessages = 9999999
msgMinAge = 0
# Archive msgs between 2 dates.
elif '-' in maxTotalMessages: # Example: maxTotalMessages = 18042021-30102021 (ddmmyyyy-ddmmyyyy)
msgMaxAge = maxTotalMessages.split('-')[0]
msgMinAge = maxTotalMessages.split('-')[1]
if len(msgMinAge) == 0:
msgMinAge = datetime.datetime.today().strftime(maxmsg_format)
for my_date in [msgMaxAge, msgMinAge]: # check the provided date format
try:
test_date = my_date[7] # dummy variable: if the date has less than 8 characters it will generate an error
datetime.datetime.strptime(my_date, maxmsg_format).date()
except:
date_fmt = maxmsg_format.replace("%d", "dd").replace("%b", "mmm").replace("%m", "mm").replace("%y", "yy").replace("%Y", "yyyy")
print(f" ** ERROR reading the from or to date: '{my_date}'")
print(f" use this exact format: {date_fmt}-{date_fmt} or {date_fmt}- \n\n")
exit()
msgMaxAge = (datetime.datetime.today() - datetime.datetime.strptime(msgMaxAge, maxmsg_format)).days
msgMinAge = (datetime.datetime.today() - datetime.datetime.strptime(msgMinAge, maxmsg_format)).days
if msgMaxAge <= msgMinAge:
print(f" ** ERROR end date must be after the start date")
print(f" use this exact format: ddmmyyyy-ddmmyyyy or ddmmyyyy- \n\n")
exit()
maxTotalMessages = 999999
else:
maxTotalMessages = int(maxTotalMessages)
msgMaxAge = 0
msgMinAge = 0
else:
maxTotalMessages = 1000
msgMaxAge = 0
msgMinAge = 0
userAvatar = config['Archive Settings']['useravatar']
outputToJson = config['Archive Settings']['outputjson']
if config.has_option('Archive Settings', 'dst_start') and config.has_option('Archive Settings', 'dst_stop'):
dst_start = config['Archive Settings']['dst_start']
dst_stop = config['Archive Settings']['dst_stop']
else:
print(f" ** config entries 'dst_start' and 'dst_stop' not in config file, please rename config.ini and run script to generate a new ini with the latest enhancements. Then update the new .ini file with your settings")
dst_stop = ""
dst_start = ""
if config.has_option('Archive Settings', 'blurring'):
blurring = config['Archive Settings']['blurring']
else:
print(f" ** config entries 'blurring' not in config file, please rename config.ini and run script to generate a new ini with the latest enhancements. Then update the new .ini file with your settings.\nFor now I will turn off blurring.")
blurring = ""
except Exception as e: # Error: keys missing from .ini file
print(f" **ERROR** reading webexspacearchive-config.ini file settings.\n ERROR: {e}")
print(" Check if your .ini file contains the following keys: \n download, sortoldnew, mytoken, myspaceid, outputfilename, useravatar, maxtotalmessages, outputjson")
print(" Rename your .ini file, re-run this script (generating correct file)\n and put your settings in the new .ini file")
print(" ---------------------------------------\n\n")
beep(3)
exit()
elif os.path.isfile("./" + configFile.replace("webexspacearchive-config", "webexteamsarchive-config")):
print(f" **ERROR** OLD config filename found!\n RENAME 'webexteamsarchive-config.ini' to 'webexspacearchive-config.ini' and retry \n\n")
beep(3)
exit()
else:
# ----------- CONFIG FILE: CREATE new config file because it does not exist
try:
config = configparser.ConfigParser(allow_no_value=True)
config.optionxform = str
config.add_section('Archive Settings')
config.set('Archive Settings', '; Your Cisco Webex developer token (NOTE: tokens are valid for 12 hours!)')
config.set('Archive Settings', '; if empty, create an environment variable "WEBEX_ARCHIVE_TOKEN" with your token.')
config.set('Archive Settings', 'mytoken', '__YOUR_TOKEN_HERE__')
config.set('Archive Settings', ';')
config.set('Archive Settings', '; Space ID: Enter your token above and run this script followed by a search argument')
config.set('Archive Settings', '; "archivescript.py searchstring" - returns lists of spaces matching "searchstring"')
config.set('Archive Settings', '; OR: go to https://developer.webex.com/docs/api/v1/rooms/list-rooms')
config.set('Archive Settings', '; "login, API reference, rooms, list all rooms", set "max" to 900 and run ')
config.set('Archive Settings', 'myspaceid', '__YOUR_SPACE_ID_HERE__')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Download: "no" : (default) only show text "attached_file"')
config.set('Archive Settings', '; "info" : file details (name & size = slower)')
config.set('Archive Settings', '; "images" : download images only')
config.set('Archive Settings', '; "files" : download files & images')
config.set('Archive Settings', '; First try the script with downloadFiles set to "no".')
config.set('Archive Settings', '; Downloading many files can take more time')
config.set('Archive Settings', 'download', 'no')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Download/show user avatar')
config.set('Archive Settings', '; no - (default) show user initials (fast)')
config.set('Archive Settings', '; link - link to avatar image - does need internet connection')
config.set('Archive Settings', '; download - download avatar images')
config.set('Archive Settings', 'useravatar', 'no')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Max Messages: - Maximum number of messages you want to download.')
config.set('Archive Settings', '; important if you want to limit archiving HUGE spaces')
config.set('Archive Settings', '; - 30d = 30 days, 365d = all msg from the last year')
config.set('Archive Settings', '; - 01052021-11062021 = msgs between 1 May and 11 June (ddmmyyyy-ddmmyyyy)')
config.set('Archive Settings', '; or 01052021- = msg after May 1st -> keep the "-"!')
config.set('Archive Settings', '; - empty (default): last 1000 messages')
config.set('Archive Settings', 'maxTotalMessages', '1000')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Output filename: Name of the generated HTML file. EMPTY: use the spacename')
config.set('Archive Settings', '; (downloadFiles enabled? Attachment foldername: same as spacename)')
config.set('Archive Settings', 'outputfilename', '')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Sorting of messages. "yes" (default) means: newest message at the bottom,')
config.set('Archive Settings', '; just like in the Webex Message client. "no" = newest message at the top')
config.set('Archive Settings', 'sortoldnew', 'yes')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Output message data to html _PLUS_ a .json and/or .txt file')
config.set('Archive Settings', '; no (default) only generate .html file')
config.set('Archive Settings', '; yes/both output message data as .json and .txt file')
config.set('Archive Settings', '; json output message data as .json file')
config.set('Archive Settings', '; txt output message data as .txt file')
config.set('Archive Settings', 'outputjson', 'no')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Manually configure Daylight Savings Time (summertime) start/stop dates')
config.set('Archive Settings', '; __EMPTY: (default) will use system information')
config.set('Archive Settings', '; __usa: dst_start: second week (2) sunday (7) of march (3) --> 2,7,3')
config.set('Archive Settings', '; dst_stop: first week (1) sunday (7) of november (11) --> 1,7,11')
config.set('Archive Settings', '; __EUROPE: dst_start: last week (L) sunday (7) of March (3) --> L,7,3')
config.set('Archive Settings', '; dst_stop: last week (L) sunday (7) of October (10) --> L,7,10')
config.set('Archive Settings', '; WEEK_NR:1-4 or L (last), DAY_NR:1-7, MONTH:1-12')
config.set('Archive Settings', '; or empty = only wintertime (of your current timezone)')
config.set('Archive Settings', ';dst_start = L, 7, 3')
config.set('Archive Settings', ';dst_stop = L, 7, 10')
config.set('Archive Settings', 'dst_start', '')
config.set('Archive Settings', 'dst_stop', '')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; ')
config.set('Archive Settings', '; Configure if you want the generated HTML file to have names blurred. You can still copy them but they appear blurred.')
config.set('Archive Settings', '; no / empty = (default) no blurring')
config.set('Archive Settings', '; yes = blurring enabled')
config.set('Archive Settings', 'blurring', '')
with open('./' + configFile, 'w') as configfile:
config.write(configfile)
except Exception as e: # Error creating config file
print(" ** ERROR ** creating config file")
print(f" Error message: {e}")
beep(3)
print(f"\n\n ------------------------------------------------------------------ \n ** WARNING ** Config file '{configFile}' does not exist. \n Creating empty configuration file. \n --> EDIT the configuration in this file and re-run this script.\n ------------------------------------------------------------------\n\n")
# STOP - the script because you need a valid configuration file first
exit()
# ----------------------------------------------------------------------------------------
# CHECK if the configuration VALUES are valid. If not, print error messsage and exit
# ----------------------------------------------------------------------------------------
goExitError = "\n\n ------------------------------------------------------------------"
if downloadFiles not in ['no', 'info', 'images', 'files', 'image', 'file']:
goExitError += "\n **ERROR** the 'download' setting must be: 'no', 'images' or 'files'"
if not myToken or len(myToken) < 55:
goExitError += "\n **ERROR** your token is not set or not long enough. You can also\n create an environment variable \"WEBEX_ARCHIVE_TOKEN\" with your token."
if len(myRoom) < 70 and mySearch == "":
goExitError += "\n **ERROR** your space ID is not set or not long enough\n RUN this script with a search parameter (space name) to find your space ID"
if not outputFileName or len(outputFileName) < 2:
outputFileName = ""
if ("\\" in r"%r" % outputFileName) or ("/" in r"%r" % outputFileName):
goExitError += f"\n **ERROR** the 'outputFileName' should not contain folders (slashes)\n outputfilename : {outputFileName}\n Change the 'outputFileName' to ONLY contain a filename."
if userAvatar not in ['no', 'link', 'download']:
goExitError += "\n **ERROR** the 'useravatar' setting must be: 'no', 'link' or 'download'"
if outputToJson not in ['yes', 'no', 'both', 'txt', 'json']:
outputToJson = "no"
if outputToJson in ['txt', 'yes', 'both']:
outputToText = True
else:
outputToText = False
if blurring == "yes":
blurring = "_blur"
else:
blurring = ""
if dst_start != "": # converting dst_start/stop string to list
try:
dst_start = dst_start.split(",")
dst_stop = dst_stop.split(",")
except Exception as e:
goExitError += "\n **ERROR** the 'dst_start' or 'dst_stop' format is incorrect."
if mySearch == "": # NOT searching for space name
if msgMaxAge == 0:
maxMessageString = str(maxTotalMessages)
elif msgMaxAge > 0 and msgMinAge == 0:
maxMessageString = f"{msgMaxAge} days"
else:
maxMessageString = f"between {msgMinAge}-{msgMaxAge} days "
dst_string = "no" # Only for script GUI, to show that DST is configured or not
if dst_start != "":
dst_string = "yes"
blur_msg = ""
if blurring != "":
blur_msg = "Blur: yes"
print(f" download:{downloadFiles} Max-msg:{maxMessageString} Avatars:{userAvatar} DST:{dst_string} {blur_msg}")
if len(goExitError) > 76: # length goExitError = 66. If error: it is > 76 characters --> print errors + exit
print(f"{goExitError}\n ------------------------------------------------------------------\n\n")
beep(3)
exit()
# ----------------------------------------------------------------------------------------
# HTML header code containing images, styling info (CSS)
# ----------------------------------------------------------------------------------------
htmlheader = """<!DOCTYPE html><html><head><meta charset="utf-8"/>
<script>
function show(yearnr)
{
var myElement = 'expand year-' + yearnr;
if (document.getElementById(myElement).style.display == 'none') {
document.getElementById(myElement).style.display = 'block';
document.getElementById('yeararrow' + yearnr).innerHTML = '▼';
} else {
document.getElementById(myElement).style.display = 'none';
document.getElementById('yeararrow' + yearnr).innerHTML = '▶';
}
}
function show_showall() {
for (let step = 2010; step < 2040; step++) {
let element = 'expand year-' + step;
if(document.body.contains(document.getElementById(element))){
document.getElementById(element).style.display = 'block';
document.getElementById('yeararrow' + step).innerHTML = '▼';
}
}
}
function show_hideall() {
for (let step = 2010; step < 2040; step++) {
let element = 'expand year-' + step;
if(document.body.contains(document.getElementById(element))){
document.getElementById(element).style.display = 'none';
document.getElementById('yeararrow' + step).innerHTML = '▶';
}
}
}
</script>
<style type='text/css'>
body { font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica', 'Arial', 'Lucida Grande', 'sans-serif';}
div[class^="expand"], div[class*=" year-"] {
display:block;
}
.cssRoomName {
height: 100%;
background-color: #029EDB;
font-size: 34px;
color: #fff;
padding-left: 30px;
align-items: center;
padding-top: 8px;
min-width: 1000px;
display: inline-block;
width: 100%;
}
#avatarCircle,
.avatarCircle {
border-radius: 50%;
width: 31px;
height: 31px;
padding: 0px;
background: #fff;
/* border: 1px solid #D2D5D6; */
color: #000;
text-align: center;
font-size: 14px;
line-height: 30px;
float: left;
margin-left: 15px;
background-color: #D2D5D6;
}
/* paperclip icon for file attachments */
#fileicon { background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGlkPSJMYXllcl8xIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA2NCA2NDsiIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDY0IDY0IiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiMxMzQ1NjM7fQo8L3N0eWxlPjxnPjxnIGlkPSJJY29uLVBhcGVyY2xpcCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTI3LjAwMDAwMCwgMzgwLjAwMDAwMCkiPjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik0tMTEwLjMtMzI2Yy0yLjQsMC00LjYtMC45LTYuMy0yLjZjLTEuNy0xLjctMi42LTMuOS0yLjYtNi4zYzAtMi40LDAuOS00LjYsMi42LTYuM2wyNS40LTI1LjQgICAgIGM0LjYtNC42LDEyLjItNC42LDE2LjgsMGMyLjIsMi4yLDMuNSw1LjIsMy41LDguNGMwLDMuMi0xLjIsNi4xLTMuNSw4LjRsLTE5LDE5bC0yLTJsMTktMTljMy41LTMuNSwzLjUtOS4zLDAtMTIuOCAgICAgYy0zLjUtMy41LTkuMy0zLjUtMTIuOCwwbC0yNS40LDI1LjRjLTEuMiwxLjEtMS44LDIuNy0xLjgsNC4zYzAsMS42LDAuNiwzLjIsMS44LDQuM2MyLjQsMi40LDYuMiwyLjQsOC42LDBsMTktMTkgICAgIGMxLjItMS4yLDEuMi0zLjIsMC00LjRjLTEuMi0xLjItMy4yLTEuMi00LjQsMGwtMTIuNywxMi43bC0yLTJsMTIuNy0xMi43YzIuMy0yLjMsNi0yLjMsOC4zLDBjMi4zLDIuMywyLjMsNiwwLDguM2wtMTksMTkgICAgIEMtMTA1LjctMzI2LjktMTA3LjktMzI2LTExMC4zLTMyNiIgaWQ9IkZpbGwtNjAiLz48L2c+PC9nPjwvc3ZnPg==');
display: block;
width: 32px;
height: 32px;
background-repeat: no-repeat;
float:left;
}
.cssNewMonth {
height: 65px;
background-color: #DFE7F1;
font-size: 50px;
color: #C3C4C7;
padding-left: 50px;
margin-bottom: 10px;
}
/* ------ NAME ------ */
.css_email {
font-size: 14px;
color: rgb(133, 134, 136);
padding-left: 6px;
padding-top: 6px;
}
.css_email_blur { /* BLURRING */
font-size: 14px;
color: rgb(133, 134, 136);
padding-left: 6px;
padding-top: 6px;
filter: blur(3px);
-webkit-filter: blur(3px);
}
/* ------ NAME ------ */
.css_email_external {
font-size: 14px;
color: #F0A30B;
padding-left: 6px;
padding-top: 6px;
}
.css_email_external_blur { /* BLURRING */
font-size: 14px;
color: #F0A30B;
padding-left: 6px;
padding-top: 6px;
filter: blur(3px);
-webkit-filter: blur(3px);
}
.myblur { /* BLURRING */
filter: blur(3px);
-webkit-filter: blur(3px);
}
/* ------ @Mentions ------ */
.atmention {
color: red;
display: inline;
}
.atmention_blur { /* BLURRING */
color: red;
display: inline;
filter: blur(3px);
-webkit-filter: blur(3px);
}
/* ------ DATE ------ */
.css_created {
color: #C0C0C1;
font-size: 13px;
padding-left: 50px;
line-height: 14px;
display: inline-block;
}
/* ------ MESSAGE TEXT ------ */
.css_messagetext {
color: rgb(51, 51, 51);
font-size: 16px;
font-weight: 400;
margin-bottom: 20px;
margin-top: 6px;
margin-left: 55px;
padding-bottom: 10px;
}
/* ------ MESSAGE TEXT IMAGES ------ */
.css_messagetext img {
margin-top: 10px;
max-width: 700px;
max-height: 100px;
cursor: pointer;
color: #686868;
font-size: 14px;
display: inline;
line-height: 14px;
}
.css_message:hover {
background-color: #F5F5F5;
border-radius: 8px;
}
.css_message {
margin-left: 10px;
}
.css_message_thread {
border-left: 4px solid #dadada;
margin-left: 80px;
padding-left: 00px;
margin-top: -20px;
}
#myheader
#myheader table,
#myheader td,
#myheader tbody {
width: 900px;
vertical-align: top;
padding-left: 10px;
min-width: 120px;
}
#myheader td {
vertical-align: top;
}
/* to fix HTML code used in text messages */
#myheader tr {
background-color: #fff !important;
}
#mytoc table,
#mytoc td,
#mytoc tbody {
width: 150px !important;
vertical-align: top !important;
min-width: 150px;
}
/* IMAGE POPUP */
.image-animate-zoom {
animation: animatezoom 0.6s
}
@keyframes animatezoom {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
.image-opacity,
.image-hover-opacity:hover {
opacity: 0.60
}
.image-opacity-off,
.image-hover-opacity-off:hover {
opacity: 1
}
.image-modal-content {
margin: auto;
background-color: #fff;
position: relative;
padding: 0;
outline: 0;
max-width: 90vh;
max-height: 100vh;
overflow: auto;
}
.image-modal {
/* For image popups */
z-index: 3;
display: none;
padding-top: 50px;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
/* TOOLTIP CSS (email address at member name) */
.tooltip {
position: relative;
display: inline-block;
}
.imagepopup {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 90%;
max-height: 90%;
}
.filesize {
display: inline-block;
color: #b3afaf;
}
.css_imagetext {
display: inline-block;
color: #8e8e8e;
font-size: 12px;
padding-left: 20px;
}
.tooltip .tooltiptext {
visibility: hidden;
background-color: lightgray;
color: #000;
font-size: 14px;
text-align: center;
border-radius: 6px;
padding: 5px 5px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
/* For quotes */
blockquote {
font-size: 16px;
/* display: inline-block; */
text-align: left;
color: #000;
word-wrap: break-word;
white-space: pre-wrap;
width: 95%;
border-left: 4px solid #dadada;
margin: 1em 0 1em .5em;
padding-left: 30px
}
/* SCROLL TO TOP button */
@media screen {
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 8px;
border-radius: 2px;
}
}
/* Hiding 'back to top' button from printed page */
@media print {
#myBtn {
display: none !important;
position: fixed;
}
/* wrap shared code so it can be printed */
pre, code {
white-space: pre-wrap !important;
word-break: break-word;
}
}
#myBtn:hover {
background-color: #555;
}
.card_class {
background-color: lightgrey;
font-size: 11px;
color: black;
}
.month_msg_count {
color:grey;
display:inline-block;
font-size:12px;
}
</style>
</head><body><div id='top'></div><button onclick="topFunction()" id="myBtn" title="Go to top">↑</button>
"""
# ----------------------------------------------------------------------------------------
# FUNCTIONS
# ----------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
# FUNCTION convert date to format displayed with each message. Used in HTML generation.
# This function checks the timezone difference between you and UTC and updates the
# message date/time so the actual times for your timezone are displayed.
# It also checks for DST
def convertDate(inputdate, returnFormat):
FMT = "%Y-%m-%dT%H:%M:%S.%fZ" # UTC format stored in Webex cloud
inputdate = datetime.datetime.strptime(inputdate, FMT)
dstinfo = time.localtime(int(inputdate.timestamp()))
date_is_dst = bool(dstinfo.tm_isdst)
if date_is_dst:
offset = utc_offset['summer']
else:
offset = utc_offset['winter']
# ---------- NO DST CONFIGURED --------------------
if dst_start == "":
dateMSGnew = inputdate + datetime.timedelta(hours=offset, minutes=0)
else: # ---------- DST CONFIGURED --------------------
if inputdate > dst_table[inputdate.year][0] and inputdate < dst_table[inputdate.year][1]: # = SUMMER
dateMSGnew = inputdate + datetime.timedelta(hours=utc_offset['summer'], minutes=0)
else:
dateMSGnew = inputdate + datetime.timedelta(hours=utc_offset['winter'], minutes=0) # = WINTER
return datetime.datetime.strftime(dateMSGnew, returnFormat)
# ----------------------------------------------------------------------------------------
# FUNCTION used in the lay-out and statistics HTML generation.
# takes a date and outputs "2018" (year), "Feb" (short month), "2" (month number)
def get_monthday(inputdate):
myyear = datetime.datetime.strptime(inputdate, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y")
mymonth = datetime.datetime.strptime(inputdate, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%b")
mymonthnr = datetime.datetime.strptime(inputdate, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%m")
return myyear, mymonth, mymonthnr
# ----------------------------------------------------------------------------------------
# FUNCTION that returns the time difference between 2 dates in seconds
# (to check if msgs from 1 author were send within 60 seconds: no new msg header)
def timedifference(newdate, previousdate):
FMT = "%Y-%m-%dT%H:%M:%S.%fZ"
tdelta = datetime.datetime.strptime(newdate, FMT) - datetime.datetime.strptime(previousdate, FMT)
return tdelta.seconds
# ----------------------------------------------------------------------------------------
# FUNCTION that returns the time difference between the msg-date and today (# of days)
# (used when setting max messages to XX days instead of number of msgs)
def timedifferencedays(msgdate):
FMT = "%Y-%m-%dT%H:%M:%S.%fZ"
tdelta = datetime.datetime.today() - datetime.datetime.strptime(msgdate, FMT)
return tdelta.days
# ----------------------------------------------------------------------------------------
# FUNCTION finds URLs in message text + convert to a hyperlink. Used in HTML generation.
def convertURL(inputtext):
outputtext = inputtext
urls = re.findall('(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&!:/~+#-]*[\w@?^=%&/~+#-])?', inputtext)
urls = set(urls)
if len(urls) > 0:
for replaceThisURL in urls:
replaceNewURL = replaceThisURL[0] + "://" + replaceThisURL[1] + replaceThisURL[2]
outputtext = outputtext.replace(replaceNewURL, "<a href='" + str(replaceNewURL) + "' target='_blank'>" + str(replaceNewURL) + "</a>")
return outputtext
# ----------------------------------------------------------------------------------------
# FUNCTION to convert all Markdown URL's [linktext](http://link.com) to clickable links
def convertMarkdownURL(msgtext, whichreplace):
try:
if whichreplace == 1:
regex = r"alt=(.*?)event\);\""
if whichreplace == 2:
regex = r"\ onClick=(.*?)event\)\;\""
matches = re.finditer(regex, msgtext, re.MULTILINE)
matchDict = dict() # create dictionary with match details so I can _reverse_ replace
for matchNum, match in enumerate(matches, start=1):
matchDict[matchNum] = [match.start(), match.end()]
for i in sorted(matchDict.keys(), reverse=True):
msgtext = msgtext[0:matchDict[i][0]] + " target='_blank'" + msgtext[matchDict[i][1]:]
except Exception as e:
test = msgtext
print(f" **ERROR** replacing markdown URL's in text: {msgtext}")
return msgtext
# ----------------------------------------------------------------------------------------
# FUNCTION that retrieves a list of Space members (displayName + email address)
def get_memberships(mytoken, myroom, maxmembers):
headers = {'Authorization': 'Bearer ' + mytoken, 'content-type': 'application/json; charset=utf-8'}
payload = {'roomId': myroom, 'max': 400}
resultjson = list()
while True:
try:
result = requests.get('https://webexapis.com/v1/memberships', headers=headers, params=payload)
if "Link" in result.headers: # there's MORE members
headerLink = result.headers["Link"]
myCursor = headerLink[headerLink.find("cursor=") + len("cursor="):headerLink.rfind(">")]
payload = {'roomId': myroom, 'max': maxmembers, 'cursor': myCursor}
resultjson += result.json()["items"]
continue
else:
resultjson += result.json()["items"]
print(f" Number of space members: {len(resultjson)}")
break
except requests.exceptions.RequestException as e: # For problems like SSLError/InvalidURL
if e.status_code == 429:
print(" Code 429, waiting for : " + str(sleepTime) + " seconds: ", end='', flush=True)
for x in range(0, sleepTime):
time.sleep(1)
print(".", end='', flush=True) # Progress indicator
else:
print(f" *** ERROR *** getting space members. Error message: {result.status_code}\n {e}")
break
except Exception as e:
print(f" *** ERROR *** getting space members. Error message: {e}")
return resultjson
# ----------------------------------------------------------------------------------------
# FUNCTION that retrieves all space messages - testing error 429 catching
def get_messages(mytoken, myroom, myMaxMessages):
global maxTotalMessages
headers = {'Authorization': 'Bearer ' + mytoken, 'content-type': 'application/json; charset=utf-8'}
payload = {'roomId': myroom, 'max': myMaxMessages}
resultjsonmessages = list()
messageCount = 0
progress_counter = 0
while True:
try:
result = requests.get('https://webexapis.com/v1/messages', headers=headers, params=payload)
if result.status_code != 200 and result.status_code != 429:
print(f" ** ERROR ** Problem retrieving specific messages. Try to lower\n the max_messages variable in the .py and .ini file until it works\nERROR msg: {result.text}\nERROR code: {result.status_code}")
beep(3)
exit()
messageCount += len(result.json()["items"])
progress_counter += 1
sys.stdout.write('\r')
sys.stdout.write(" %d %s " % (messageCount, '*' * progress_counter))
sys.stdout.flush()
if "Link" in result.headers and messageCount < maxTotalMessages: # there's MORE messages
resultjsonmessages = resultjsonmessages + result.json()["items"]
# When retrieving multiple batches _check_ if the last message retrieved
# is _OLDER_ than the configured max msg age (in the .ini). If yes: trim results to the max age.
if msgMaxAge != 0:
msgAge = timedifferencedays(result.json()["items"][-1]["created"])
if msgAge > msgMaxAge:
print(" max messages reached (>" + str(msgMaxAge) + " days old)")
# NOW I set maxTotalMessages to the last msg index that should be included, based on msg age in days.
maxTotalMessages = next((index for (index, d) in enumerate(resultjsonmessages) if timedifferencedays(d["created"]) > msgMaxAge), 99999)
break
myBeforeMessage = result.headers.get('Link').split("beforeMessage=")[1].split(">")[0]
payload = {'roomId': myroom, 'max': myMaxMessages, 'beforeMessage': myBeforeMessage}
continue
else:
resultjsonmessages = resultjsonmessages + result.json()["items"]
if msgMaxAge != 0:
msgAge = timedifferencedays(result.json()["items"][-1]["created"])
lastMsgLocation = next((index for (index, d) in enumerate(resultjsonmessages) if timedifferencedays(d["created"]) > msgMaxAge), 99999)
maxTotalMessages = lastMsgLocation
print(f" FINISHED total messages: {messageCount}")
if "Link" in result.headers: # There ARE more messages but the maxTotalMessages has been reached
print(f" Reached configured maximum # messages ({maxTotalMessages})")
break
except requests.exceptions.RequestException as e: # A serious problem, like an SSLError or InvalidURL
print(f" EXCEPT status_code: {e.status_code}")
print(f" EXCEPT text: {e.text}")
print(f" EXCEPT headers: {e.headers}")
if e.status_code == 429:
print(" Code 429, waiting for : " + str(sleepTime) + " seconds: ", end='', flush=True)
for x in range(0, sleepTime):
time.sleep(1)
print(".", end='', flush=True) # Progress indicator
else:
print(f" EXCEPT ELSE e: {e} e.code: {e.code}")
break
if maxTotalMessages == 0:
print(" **ERROR** there are no messages. Please check your maxMessages setting and try again.\n\n")
beep(3)
exit()
return resultjsonmessages[0:maxTotalMessages]
# ----------------------------------------------------------------------------------------
# FUNCTION to turn Space name into a valid filename string
def format_filename(s):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
filename = ''.join(c for c in s if c in valid_chars)
return filename.strip()
# ----------------------------------------------------------------------------------------
# FUNCTION get the Space-name (Used in the header + optionally for the filename)
def get_roomname(mytoken, myroom):
headers = {'Authorization': 'Bearer ' + mytoken, 'content-type': 'application/json; charset=utf-8'}
returndata = "webex-space-archive"
try:
result = requests.get('https://webexapis.com/v1/rooms/' + myroom, headers=headers)
if result.status_code == 401: # WRONG ACCESS TOKEN
print("__________________________ ERROR ________________________")
print(" Please check your Access Token in the .ini file.")
print(" Note that your Access Token is only valid for 12 hours.")
print(" Go here to get a new token:")
print(" https://developer.webex.com/docs/api/getting-started")
print("_________________________ STOPPED _______________________\n\n\n")
beep(3)
exit()
elif result.status_code == 404: # and "resource could not be found" in str(result.text) --> WRONG SPACE ID
print(" **ERROR** Check if the Space ID in your .ini file is correct.\n Find the Space ID? Run this script with the space name as parameter!")
print("_________________________ STOPPED _______________________\n\n\n")
beep(3)
exit()
elif result.status_code != 200:
print(f" **ERROR** Unknown Error occurred. status code: {result.status_code}\n Info: \n {result.text}\n\n")
beep(3)
exit()
elif result.status_code == 200:
returndata = result.json()['title']
except Exception as e:
print(f" **ERROR** #1 get_roomname API call status_code: {result.status_code}\n status_text: {result.text}\n Exception {e}\n\n")
beep(3)
exit()
return str(returndata.strip())
# ----------------------------------------------------------------------------------------
# FUNCTION get your own details. Name: displayed in the header.
# Also used to get your email domain: mark _other_ domains as 'external' messages
def get_me(mytoken):
try:
header = {'Authorization': "Bearer " + mytoken, 'content-type': 'application/json; charset=utf-8'}
result = requests.get(url='https://webexapis.com/v1/people/me', headers=header)
except Exception as e:
print(f" **ERROR** get_me API call status_code: {result.status_code}\n status_text: {result.text}\n Exception {e}\n\n")
beep(3)
exit()
return result.json()
# ----------------------------------------------------------------------------------------
# FUNCTION to convert file-size "bytes" to readable format (KB,MB,GB)
def convert_size(size_bytes):
if size_bytes == 0:
return "0 B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(int(size_bytes), 1024)))
p = math.pow(1024, i)
# Below: if B/KB/MB --> don't show decimals. Otherwise show 2 decimals
if i > 2:
s = round(int(size_bytes) / p, 2)
s = f"{s:.2f}"
else:
s = round(int(size_bytes) / p, 0)
s = f"{s:.0f}"
return f"{s} {size_name[i]}"
# ----------------------------------------------------------------------------------------
# FUNCTION to download message images & files (if enabled)
def process_Files(fileData, fileDate):
global myErrorList
filelist = list()
for url in fileData:
headers = {"Authorization": f"Bearer {myToken}", "Accept-Encoding": ""}
r = requests.head(url, headers=headers)
if r.status_code == 404: # Item must have been deleted since url was retrieved
continue
try:
filename = str(r.headers['Content-Disposition']).split("\"")[1]
# Files with no name or just spaces: fix so they can still be downloaded:
if len(filename) < 1 or filename.isspace():
filename = "unknown-filename"
if filename == ('+' * (int(len(filename) / len('+')) + 1))[:len(filename)]:
filename = "unknown-filename"
beep(1)
print(f"**process_files** {str(r.headers)}")
except Exception as e:
filename = "error-getting-filename"
myErrorList.append("def process_Files Header 'content-disposition' error for url: " + url)
filename = format_filename(filename)
filesize = int(r.headers['Content-Length'])
fileextension = os.path.splitext(filename)[1][1:].replace("\"", "")
filenamepart = os.path.splitext(filename)[0]
if int(r.headers['Content-Length']) <= 0:
# Not downloading 0 Byte files, only show the filename
filelist.append(filename + "###" + str(filesize))
continue
if downloadFiles not in ['images', 'files', 'image', 'file']:
# No file downloading --> just get the filename + size
filelist.append(filename + "###" + str(filesize))
continue
if "image" in downloadFiles and fileextension.lower() not in ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'tif']:
# File is not an image --> just get the filename + size
filelist.append(filename + "###" + str(filesize))
continue
if fileextension.lower() in ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'tif']:
# File is an image