This repository has been archived by the owner on Nov 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathinstaview.py
1402 lines (1206 loc) · 60.1 KB
/
instaview.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 python3
# INSTAGRAM JSON VIEWER
# 2020 (c) Micha Johannes Birklbauer
# https://github.com/michabirklbauer/
from datetime import datetime as dt
import urllib.request as ur
import traceback as tb
import time
import json
import os
# template html
# largely taken and adapted from w3schools.com
# -> https://www.w3schools.com/howto/howto_css_fixed_sidebar.asp
# -> https://www.w3schools.com/howto/howto_css_chat.asp
html_template = \
"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Instagram Data Report">
<meta name="author" content="Micha Birklbauer">
<title>Instagram Data Report</title>
<style>
body {
font-family: "Times New Roman", Times, serif;
}
.sidenav {
height: 100%;
width: 160px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #fff;
overflow-x: hidden;
padding-top: 20px;
}
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 25px;
color: #111;
display: block;
}
.sidenav a:hover {
color: #f1f1f1;
}
.main {
margin-left: 160px;
font-size: 25px;
padding: 0px 10px;
}
.main img {
max-width: 500px;
width: 100%;
}
.main audio {
max-width: 500px;
width: 100%;
}
.main video {
max-width: 500px;
width: 100%;
}
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
.container {
border: 2px solid #000;
background-color: #ffffff;
border-radius: 5px;
padding: 10px;
margin: 10px 0;
}
.darker {
border-color: #000;
background-color: #66b3ff;
}
.container::after {
content: "";
clear: both;
display: table;
}
.container img {
max-width: 500px;
width: 100%;
}
.container img.left {
float: left;
max-width: 60px;
width: 100%;
margin-right: 20px;
border-radius: 50%;
}
.container img.right {
float: right;
max-width: 60px;
width: 100%;
margin-left: 20px;
border-radius: 50%;
}
.container audio {
max-width: 500px;
width: 100%;
}
.container video {
max-width: 500px;
width: 100%;
}
.time-right {
float: right;
color: #000;
}
.time-left {
float: left;
color: #000;
}
</style>
</head>
<body>
"""
# template sidebar html
sidebar_template = \
"""
<div class="sidenav">
<a href="#profile">Profile Information</a>
<a href="#searches">Searches</a>
<a href="#connections">Profile Connections</a>
<a href="#media">Media</a>
<a href="#stories">Stories</a>
<a href="#photos">Photos</a>
<a href="#pictures">Profile Pictures</a>
<a href="#videos">Videos</a>
<a href="#comments">Comments</a>
<a href="#messages">Messages</a>
<a href="#devices">Devices</a>
"""
# patting myself on the shoulder for this one uwu
credits = \
"""
<h2 id="credits">Credits</h2>
<p>
Report created with Micha Birklbauer's <a href="https://github.com/michabirklbauer/instagram_json_viewer">Instagram JSON Viewer</a>.
</p>
"""
# reading profile information and converting it to html string
# default filenames and arguments should be fine for all functions if script is in the right directory
def read_profile(filename = "profile.json"):
# error controls and logging
status = 0
errors = []
# html template
html_string = "<h2 id=\"profile\">Profile Information</h2>\n\t<ul>\n"
# json to html conversion
try:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
for item in data:
html_string = html_string + "\t\t<li><b>" + str(item) + ":</b> " + str(data[item]) + "</li>\n"
except Exception as e:
print("ERROR reading profile!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
html_string = html_string + "\t</ul>\n<hr>\n"
# creating an error log for file output
error_log = "Encountered errors reading profile: " + str(status) + "\nError messages:\n" + str("\n".join(errors)) + "\n\n"
return [html_string, status, error_log]
# reading search information and converting it to html string
def read_searches(filename = "searches.json"):
# error controls and logging
status = 0
errors = []
# html template
html_string = "<h2 id=\"searches\">Searches</h2>\n"
# json to html conversion
try:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
main_search = data["main_search_history"]
shopping_search = data["shopping_search_history"]
html_string = html_string + "\t<h3>Profile Searches</h3>\n\t\t<ul>\n"
counter = 1
for item in main_search:
if item == "You have no data in this section":
html_string = html_string + "\t\t\t<li>You have no data in this section.</li>\n"
break
html_string = html_string + "\t\t\t<li><b>Search " + str(counter) + ":</b>\n\t\t\t\t<ul>\n"
for subitem in item:
html_string = html_string + "\t\t\t\t\t<li><b>" + str(subitem) + ":</b> " + str(item[subitem]) + "</li>\n"
html_string = html_string + "\t\t\t\t</ul>\n\t\t\t</li>\n"
counter = counter + 1
html_string = html_string + "\t\t</ul>\n\t<h3>Shopping Searches</h3>\n\t\t<ul>\n"
counter = 1
for item in shopping_search:
if item == "You have no data in this section":
html_string = html_string + "\t\t\t<li>You have no data in this section.</li>\n"
break
html_string = html_string + "\t\t\t<li><b>Search " + str(counter) + ":</b>\n\t\t\t\t<ul>\n"
for subitem in item:
html_string = html_string + "\t\t\t\t\t<li><b>" + str(subitem) + ":</b> " + str(item[subitem]) + "</li>\n"
html_string = html_string + "\t\t\t\t</ul>\n\t\t\t</li>\n"
counter = counter + 1
except Exception as e:
print("ERROR reading searches!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
html_string = html_string + "\t\t</ul>\n<hr>\n"
# creating an error log for file output
error_log = "Encountered errors reading searches: " + str(status) + "\nError messages:\n" + str("\n".join(errors)) + "\n\n"
return [html_string, status, error_log]
# reading connection information and converting it to html string
def read_connections(filename = "connections.json"):
# error controls and logging
status = 0
errors = []
# html template
html_string = "<h2 id=\"connections\">Profile Connections</h2>\n\t<ul>\n"
# json to html conversion
try:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
# blocked users - this field is not available in newer backups
if "blocked_users" in data:
try:
blocked_users = data["blocked_users"]
html_string = html_string + "<h3>Blocked Users</h3>\n\t<ul>\n"
if len(blocked_users) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in blocked_users:
html_string = html_string + "\t\t<li>" + str(item) + " <b>blocked since</b> " + str(blocked_users[item]) + "</li>\n"
except Exception as e:
print("ERROR reading blocked_users!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# restriced users - this field is not available in newer backups
if "restricted_users" in data:
try:
restricted_users = data["restricted_users"]
html_string = html_string + "\t</ul>\n\n<h3>Restricted Users</h3>\n\t<ul>\n"
if len(restricted_users) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in restricted_users:
html_string = html_string + "\t\t<li>" + str(item) + " <b>restricted since</b> " + str(restricted_users[item]) + "</li>\n"
except Exception as e:
print("ERROR reading restricted_users!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# follow requests sent
try:
follow_requests_sent = data["follow_requests_sent"]
html_string = html_string + "\t</ul>\n\n<h3>Requested Following</h3>\n\t<ul>\n"
if len(follow_requests_sent) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in follow_requests_sent:
html_string = html_string + "\t\t<li>" + str(item) + " <b>request sent</b> " + str(follow_requests_sent[item]) + "</li>\n"
except Exception as e:
print("ERROR reading follow_requests_sent!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# following
try:
following = data["following"]
html_string = html_string + "\t</ul>\n\n<h3>Following Users</h3>\n\t<ul>\n"
if len(following) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in following:
html_string = html_string + "\t\t<li>" + str(item) + " <b>followed since</b> " + str(following[item]) + "</li>\n"
except Exception as e:
print("ERROR reading following!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# followers
try:
followers = data["followers"]
html_string = html_string + "\t</ul>\n\n<h3>Followers</h3>\n\t<ul>\n"
if len(followers) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in followers:
html_string = html_string + "\t\t<li>" + str(item) + " <b>has followed since</b> " + str(followers[item]) + "</li>\n"
except Exception as e:
print("ERROR reading followers!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# following hashtags
try:
following_hashtags = data["following_hashtags"]
html_string = html_string + "\t</ul>\n\n<h3>Following Hashtags</h3>\n\t<ul>\n"
if len(following_hashtags) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in following_hashtags:
html_string = html_string + "\t\t<li>" + str(item) + " <b>followed since</b> " + str(following_hashtags[item]) + "</li>\n"
except Exception as e:
print("ERROR reading following_hashtags!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# dismissed suggested users - this field is not available in newer backups
if "dismissed_suggested_users" in data:
try:
dismissed_suggested_users = data["dismissed_suggested_users"]
html_string = html_string + "\t</ul>\n\n<h3>Dismissed Suggested Users</h3>\n\t<ul>\n"
if len(dismissed_suggested_users) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in dismissed_suggested_users:
html_string = html_string + "\t\t<li>" + str(item) + " <b>dismissed on</b> " + str(dismissed_suggested_users[item]) + "</li>\n"
except Exception as e:
print("ERROR reading dismissed_suggested_users!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
except Exception as e:
print("ERROR reading connections!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1000
html_string = html_string + "\t</ul>\n<hr>\n"
# creating an error log for file output
error_log = "Encountered errors reading connections: " + str(status) + "\nError messages:\n" + str("\n".join(errors)) + "\n\n"
return [html_string, status, error_log]
# reading media information and converting it to html string
def read_media(filename = "media.json"):
# error controls and logging
status = 0
errors = []
# html template
html_string = "<h2 id=\"media\">Media</h2>\n\t<ul>\n"
# json to html conversion
try:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
# stories
try:
stories = data["stories"]
html_string = html_string + "<h3 id=\"stories\">Stories</h3>\n\t<ul>\n"
if len(stories) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in stories:
html_string = html_string + "\t\t<li>\n"
if len(item["caption"]) == 0:
caption = "None"
else:
caption = item["caption"]
html_string = html_string + "\t\t\t<b>Caption:</b> " + str(caption) + "<br>\n\t\t\t<b>Taken at:</b> " + str(item["taken_at"]) + "<br>\n"
if str(item["path"]).split(".")[-1] == "mp4":
html_string = html_string + "\t\t\t<video controls>\n"
html_string = html_string + "\t\t\t\t<source src=\"" + str(item["path"]) + "\" type=\"video/mp4\">\n"
html_string = html_string + "\t\t\t</video>\n"
else:
html_string = html_string + "\t\t\t<img src=\"" + str(item["path"]) + "\" alt=\"Caption: " + str(caption).replace("\"", "'") + "\">\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print("ERROR reading stories media!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# photos
try:
photos = data["photos"]
html_string = html_string + "\t</ul>\n\n<h3 id=\"photos\">Photos</h3>\n\t<ul>\n"
if len(photos) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in photos:
html_string = html_string + "\t\t<li>\n"
if len(item["caption"]) == 0:
caption = "None"
else:
caption = item["caption"]
html_string = html_string + "\t\t\t<b>Caption:</b> " + str(caption) + "<br>\n\t\t\t<b>Taken at:</b> " + str(item["taken_at"]) + "<br>\n"
html_string = html_string + "\t\t\t<img src=\"" + str(item["path"]) + "\" alt=\"Caption: " + str(caption).replace("\"", "'") + "\">\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print("ERROR reading photos media!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# profile
try:
profile = data["profile"]
html_string = html_string + "\t</ul>\n\n<h3 id=\"pictures\">Profile Pictures</h3>\n\t<ul>\n"
if len(profile) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in profile:
html_string = html_string + "\t\t<li>\n"
if len(item["caption"]) == 0:
caption = "None"
else:
caption = item["caption"]
html_string = html_string + "\t\t\t<b>Caption:</b> " + str(caption) + "<br>\n\t\t\t<b>Taken at:</b> " + str(item["taken_at"]) + "<br>\n"
html_string = html_string + "\t\t\t<img src=\"" + str(item["path"]) + "\" alt=\"Caption: " + str(caption).replace("\"", "'") + "\">\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print("ERROR reading profile media!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# videos
try:
videos = data["videos"]
html_string = html_string + "\t</ul>\n\n<h3 id=\"videos\">Videos</h3>\n\t<ul>\n"
if len(videos) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in videos:
html_string = html_string + "\t\t<li>\n"
if len(item["caption"]) == 0:
caption = "None"
else:
caption = item["caption"]
html_string = html_string + "\t\t\t<b>Caption:</b> " + str(caption) + "<br>\n\t\t\t<b>Taken at:</b> " + str(item["taken_at"]) + "<br>\n"
html_string = html_string + "\t\t\t<video controls>\n"
html_string = html_string + "\t\t\t\t<source src=\"" + str(item["path"]) + "\" type=\"video/mp4\">\n"
html_string = html_string + "\t\t\t</video>\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print("ERROR reading video media!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# direct - this field is not available in newer backups
if "direct" in data:
try:
direct = data["direct"]
html_string = html_string + "\t</ul>\n\n<h3 id=\"direct\">Direct Messages Media</h3>\n\t<ul>\n"
if len(direct) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in direct:
html_string = html_string + "\t\t<li>\n"
html_string = html_string + "\t\t\t<b>Taken at:</b> " + str(item["taken_at"]) + "<br>\n"
if str(item["path"]).split(".")[-1] == "mp4":
html_string = html_string + "\t\t\t<video controls>\n"
html_string = html_string + "\t\t\t\t<source src=\"" + str(item["path"]) + "\" type=\"video/mp4\">\n"
html_string = html_string + "\t\t\t</video>\n"
elif str(item["path"]).split(".")[-1] == "m4a":
html_string = html_string + "\t\t\t<audio controls>\n"
html_string = html_string + "\t\t\t\t<source src=\"" + str(item["path"]) + "\" type=\"audio/mpeg\">\n"
html_string = html_string + "\t\t\t</audio>\n"
else:
html_string = html_string + "\t\t\t<img src=\"" + str(item["path"]) + "\" alt=\"Caption: " + str(caption).replace("\"", "'") + "\">\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print("ERROR reading direct media!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
except Exception as e:
print("ERROR reading media!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1000
html_string = html_string + "\t</ul>\n<hr>\n"
# creating an error log for file output
error_log = "Encountered errors reading media: " + str(status) + "\nError messages:\n" + str("\n".join(errors)) + "\n\n"
return [html_string, status, error_log]
# reading comment information and converting it to html string
def read_comments(filename = "comments.json"):
# error controls and logging
status = 0
errors = []
# html template
html_string = "<h2 id=\"comments\">Comments</h2>\n\t<ul>\n"
# json to html conversion
try:
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
# media comments
try:
media_comments = data["media_comments"]
html_string = html_string + "<h3 id=\"mediacomments\">Media Comments</h3>\n\t<ul>\n"
if len(media_comments) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in media_comments:
html_string = html_string + "\t\t<li>\n"
html_string = html_string + "\t\t\t<b>Post Owner:</b> " + str(item[2]) + "<br>\n\t\t\t<b>Commented on:</b> " + str(item[0]) + "<br>\n\t\t\t<b>Comment:</b> " + str(item[1]) + "\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print("ERROR reading media comments!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# live comments - this field is not available in newer backups
if "live_comments" in data:
try:
live_comments = data["live_comments"]
html_string = html_string + "\t</ul>\n\n<h3 id=\"livecomments\">Live Comments</h3>\n\t<ul>\n"
# this is rather experimental because I had no live comments available
try:
if len(live_comments) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in live_comments:
html_string = html_string + "\t\t<li>\n"
html_string = html_string + "\t\t\t<b>Live Owner:</b> " + str(item[2]) + "<br>\n\t\t\t<b>Commented on:</b> " + str(item[0]) + "<br>\n\t\t\t<b>Comment:</b> " + str(item[1]) + "\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print(e)
pass
except Exception as e:
print("ERROR reading live comments!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
# story comments - this field is not available in newer backups
if "story_comments" in data:
try:
story_comments = data["story_comments"]
html_string = html_string + "\t</ul>\n\n<h3 id=\"storycomments\">Story Comments</h3>\n\t<ul>\n"
# this is rather experimental because I had no story comments available
try:
if len(story_comments) == 0:
html_string = html_string + "\t\t<li>None</li>\n"
else:
for item in story_comments:
html_string = html_string + "\t\t<li>\n"
html_string = html_string + "\t\t\t<b>Story Owner:</b> " + str(item[2]) + "<br>\n\t\t\t<b>Commented on:</b> " + str(item[0]) + "<br>\n\t\t\t<b>Comment:</b> " + str(item[1]) + "\n"
html_string = html_string + "\t\t</li>\n"
except Exception as e:
print(repr(e))
pass
except Exception as e:
print("ERROR reading story comments!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
except Exception as e:
print("ERROR reading comments!")
tb.print_exc()
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1000
html_string = html_string + "\t</ul>\n<hr>\n"
# creating an error log for file output
error_log = "Encountered errors reading comments: " + str(status) + "\nError messages:\n" + str("\n".join(errors)) + "\n\n"
return [html_string, status, error_log]
# helper function to generate a messages json file from a directory
# dirname is the directory that stores the split message_*.json files
def generate_messages_json(dirname = "messages"):
if not os.path.isdir(dirname):
print("ERROR - Specified directory does not exist", dirname)
return 1
try:
messages_json = []
for dirpath, dirnames, filenames in os.walk(dirname):
for fname in filenames:
if fname.endswith(".json"):
with open(os.path.join(dirpath, fname), "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
messages_json.append(data)
filename = dirname + ".json"
with open(filename, "w", encoding="utf-8") as f:
json.dump(messages_json, f)
f.close()
return 0
except Exception as e:
print("ERROR creating specified messages JSON file!")
print(repr(e))
print("Detailed Traceback:")
tb.print_exc()
return 1
# this is a debug function to reversely generate a messages-folder-like structure
# for testing purposes
def reverse_generate_messages_json(filename = "messages.json"):
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
for item in data:
dirname = "messages/inbox/"+", ".join(item["participants"])
print(dirname)
try:
os.mkdir(dirname)
except Exception:
tb.print_exc()
with open(dirname+"/message_1.json", "w", encoding="utf-8") as f:
json.dump(item, f)
# reading message information and converting it to html string (only links)
# also creates "chat" subdirectory in current directory
# creates chat html pages in "chat" subdirectory
# for args refer to README.md
# there are no input checks, incorrect inputs will lead to crashes!
# so be careful if you don't want things to go sideways
def read_messages(filename = "messages.json", profile = "profile.json", reverse_conversations = False, profile_pic = None, default_avatar = None, download_all = False, hd = False, infer_usernames = False, avatars_dict = {}, avatar_warnings = False, http_traceback = False):
GENERATED = False
# generate messages.json (or specified messages json file) if not present on
# the current file tree
if not os.path.isfile(filename):
GENERATED = True
mjson_status = generate_messages_json(filename.split(".")[0])
if mjson_status != 0:
print("WARNING - Generating", filename, "was unsuccessful! Trying to continue...")
# print warning for older instagram backups
if not GENERATED:
print("\n\nWARNING - you are serving an old instagram backup! You might want to consider using an older release!")
print("https://github.com/michabirklbauer/instagram_json_viewer/tree/v2020.12.07\n\n")
# error controls and logging
status = 0
errors = []
# logging errors in conversations
conv_errors = []
# creating chat directory
try:
os.mkdir("chat")
except Exception as e:
print("ERROR creating directory 'chat'!")
print(repr(e))
print("Detailed Traceback:")
tb.print_exc()
# creating icons directory
try:
os.mkdir("chat/icons")
except Exception as e:
print("ERROR creating directory 'chat/icons'!")
print(repr(e))
print("Detailed Traceback:")
tb.print_exc()
# creating media directory if media is downloaded
if download_all:
try:
os.mkdir("chat/media")
except Exception as e:
print("ERROR creating directory 'chat/icons'!")
print(repr(e))
print("Detailed Traceback:")
tb.print_exc()
chat_list = []
# html template
html_string = "<h2 id=\"messages\">Messages</h2>\n\n<ul>\n"
# reading self username from profile.json
with open(profile, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
user_username = str(data["username"])
if "name" in data:
user_profile_name = str(data["name"])
else:
user_profile_name = str(data["username"])
# setting a default avatar if None is provided
if default_avatar is not None:
default_avatar = str(default_avatar)
else:
if hd:
default_avatar = "https://raw.githubusercontent.com/michabirklbauer/instagram_json_viewer/master/icons/icon_hd.jpg"
else:
default_avatar = "https://raw.githubusercontent.com/michabirklbauer/instagram_json_viewer/master/icons/icon.jpg"
# setting self profile picture if None is provided
if profile_pic is None:
try:
pp_list = os.listdir("profile")
pp_last = pp_list[-1]
pp_pics = os.listdir(("profile/" + str(pp_last)))
pp_pic = pp_pics[-1]
profile_pic = "../profile/" + str(pp_last) + "/" + str(pp_pic)
except Exception as e:
print(repr(e))
print("ERROR fetching profile picture locally!")
print("Trying to fetch online...")
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
try:
ig_url = "https://instagram.com/" + user_username + "/?__a=1"
request_header = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; Win64; x64)" }
request = ur.Request(ig_url, headers=request_header)
data = ur.urlopen(request).read()
json_data = json.loads(data)
if hd:
profile_pic_url = str(json_data["graphql"]["user"]["profile_pic_url_hd"])
file_name = "chat/icons/" + str(profile_pic_url).split("/")[-1].split("?")[0]
ur.urlretrieve(str(profile_pic_url), file_name)
profile_pic = "icons/" + str(profile_pic_url).split("/")[-1].split("?")[0]
else:
profile_pic_url = str(json_data["graphql"]["user"]["profile_pic_url"])
file_name = "chat/icons/" + str(profile_pic_url).split("/")[-1].split("?")[0]
ur.urlretrieve(str(profile_pic_url), file_name)
profile_pic = "icons/" + str(profile_pic_url).split("/")[-1].split("?")[0]
except Exception as e:
print(repr(e))
print("ERROR fetching profile picture online!")
print("Profile picture set to default avatar!")
errors.append(str(repr(e)))
errors.append("Detailed Traceback:")
errors.append(tb.format_exc())
status = status + 1
profile_pic = default_avatar
# function to fetch avatar for given username
def get_avatar(username, profile_pic = profile_pic, default = default_avatar, hd = hd, avatar_warnings = avatar_warnings, http_traceback = http_traceback):
if str(username) == user_username:
return profile_pic
else:
ig_url = "https://instagram.com/" + username + "/?__a=1"
try:
request_header = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; Win64; x64)" }
request = ur.Request(ig_url, headers=request_header)
data = ur.urlopen(request).read()
json_data = json.loads(data)
if hd:
avatar_url = str(json_data["graphql"]["user"]["profile_pic_url_hd"])
file_name = "chat/icons/" + str(username) + ".jpg"
ur.urlretrieve(str(avatar_url), file_name)
avatar = "icons/" + str(username) + ".jpg"
else:
avatar_url = str(json_data["graphql"]["user"]["profile_pic_url"])
file_name = "chat/icons/" + str(username) + ".jpg"
ur.urlretrieve(str(avatar_url), file_name)
avatar = "icons/" + str(username) + ".jpg"
except Exception as e:
try:
avatar_url = default
file_name = "chat/icons/" + str(username) + ".jpg"
ur.urlretrieve(str(avatar_url), file_name)
avatar = "icons/" + str(username) + ".jpg"
except:
if avatar_warnings:
print("INFO: Downloading of default avatar was unsuccessful! Avatar is still set!")
avatar = default
if avatar_warnings:
print(("WARNING - error getting avatar for user " + str(username) + "!\n Set to default!"))
print(repr(e))
if http_traceback:
print("Detailed Traceback:")
tb.print_exc()
return avatar
# save media locally if possible
def get_media(media_share_url, download_all = download_all):
if download_all:
try:
file_name = "chat/media/" + str(media_share_url).split("/")[-1].split("?")[0]
ur.urlretrieve(str(media_share_url), file_name)
media = "media/" + str(media_share_url).split("/")[-1].split("?")[0]
return str(media)
except:
return str(media_share_url)
else:
return str(media_share_url)
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
f.close()
avatars = avatars_dict
avatars[user_username] = profile_pic
avatars[user_profile_name] = profile_pic
for item in data:
participants = item["participants"]
# helper list for new json structure - NEW ^= Refers to Instagram Data post ~20th December 2020
participants_new = []
try:
# getting avatars might not work if u send to many requests to instagram
# if avatars are not shown correctly in chat, run script again at a different time
# or change IP address if u can
for participant in participants:
# checks for old json structure
if isinstance(participant, str):
participants_new.append(participant)
if participant not in avatars:
avatars[participant] = str(get_avatar(participant))
# checks for new json structure
elif isinstance(participant, dict):
# ----
# new json seems to be wrongly encoded and it gets really ugly from here
# ----
# remove any """.encode("ISO-8859-1").decode("utf-8")""" when this is fixed
#
participant = participant["name"].encode("ISO-8859-1").decode("utf-8")
participants_new.append(participant)
if participant not in avatars:
infered_participant_username = item["thread_path"].split("/")[-1].split("_")[0].split("-")[0]
if infer_usernames:
avatars[participant] = str(get_avatar(infered_participant_username))
else: