-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Osintgram.py
1666 lines (1322 loc) · 59 KB
/
Osintgram.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
import datetime
import json
import sys
import urllib
import os
import codecs
from pathlib import Path
import requests
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
from geopy.geocoders import Nominatim
from instagram_private_api import Client as AppClient
from instagram_private_api import ClientCookieExpiredError, ClientLoginRequiredError, ClientError, ClientThrottledError
from prettytable import PrettyTable
from src import printcolors as pc
from src import config
class Osintgram:
api = None
api2 = None
geolocator = Nominatim(user_agent="http")
user_id = None
target_id = None
is_private = True
following = False
target = ""
writeFile = False
jsonDump = False
cli_mode = False
output_dir = "output"
def __init__(self, target, is_file, is_json, is_cli, output_dir, clear_cookies):
self.output_dir = output_dir or self.output_dir
u = config.getUsername()
p = config.getPassword()
self.clear_cookies(clear_cookies)
self.cli_mode = is_cli
if not is_cli:
print("\nAttempt to login...")
self.login(u, p)
self.setTarget(target)
self.writeFile = is_file
self.jsonDump = is_json
def clear_cookies(self,clear_cookies):
if clear_cookies:
self.clear_cache()
def setTarget(self, target):
self.target = target
user = self.get_user(target)
self.target_id = user['id']
self.is_private = user['is_private']
self.following = self.check_following()
self.__printTargetBanner__()
self.output_dir = self.output_dir + "/" + str(self.target)
Path(self.output_dir).mkdir(parents=True, exist_ok=True)
def __get_feed__(self):
data = []
result = self.api.user_feed(str(self.target_id))
data.extend(result.get('items', []))
next_max_id = result.get('next_max_id')
while next_max_id:
results = self.api.user_feed(str(self.target_id), max_id=next_max_id)
data.extend(results.get('items', []))
next_max_id = results.get('next_max_id')
return data
def __get_comments__(self, media_id):
comments = []
result = self.api.media_comments(str(media_id))
comments.extend(result.get('comments', []))
next_max_id = result.get('next_max_id')
while next_max_id:
results = self.api.media_comments(str(media_id), max_id=next_max_id)
comments.extend(results.get('comments', []))
next_max_id = results.get('next_max_id')
return comments
def __printTargetBanner__(self):
pc.printout("\nLogged as ", pc.GREEN)
pc.printout(self.api.username, pc.CYAN)
pc.printout(". Target: ", pc.GREEN)
pc.printout(str(self.target), pc.CYAN)
pc.printout(" [" + str(self.target_id) + "]")
if self.is_private:
pc.printout(" [PRIVATE PROFILE]", pc.BLUE)
if self.following:
pc.printout(" [FOLLOWING]", pc.GREEN)
else:
pc.printout(" [NOT FOLLOWING]", pc.RED)
print('\n')
def change_target(self):
pc.printout("Insert new target username: ", pc.YELLOW)
line = input()
self.setTarget(line)
return
def get_addrs(self):
if self.check_private_profile():
return
pc.printout("Searching for target localizations...\n")
data = self.__get_feed__()
locations = {}
for post in data:
if 'location' in post and post['location'] is not None:
if 'lat' in post['location'] and 'lng' in post['location']:
lat = post['location']['lat']
lng = post['location']['lng']
locations[str(lat) + ', ' + str(lng)] = post.get('taken_at')
address = {}
for k, v in locations.items():
details = self.geolocator.reverse(k)
unix_timestamp = datetime.datetime.fromtimestamp(v)
address[details.address] = unix_timestamp.strftime('%Y-%m-%d %H:%M:%S')
sort_addresses = sorted(address.items(), key=lambda p: p[1], reverse=True)
if len(sort_addresses) > 0:
t = PrettyTable()
t.field_names = ['Post', 'Address', 'time']
t.align["Post"] = "l"
t.align["Address"] = "l"
t.align["Time"] = "l"
pc.printout("\nWoohoo! We found " + str(len(sort_addresses)) + " addresses\n", pc.GREEN)
i = 1
json_data = {}
addrs_list = []
for address, time in sort_addresses:
t.add_row([str(i), address, time])
if self.jsonDump:
addr = {
'address': address,
'time': time
}
addrs_list.append(addr)
i = i + 1
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_addrs.txt"
file = open(file_name, "w")
file.write(str(t))
file.close()
if self.jsonDump:
json_data['address'] = addrs_list
json_file_name = self.output_dir + "/" + self.target + "_addrs.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
print(t)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_captions(self):
if self.check_private_profile():
return
pc.printout("Searching for target captions...\n")
captions = []
data = self.__get_feed__()
counter = 0
try:
for item in data:
if "caption" in item:
if item["caption"] is not None:
text = item["caption"]["text"]
captions.append(text)
counter = counter + 1
sys.stdout.write("\rFound %i" % counter)
sys.stdout.flush()
except AttributeError:
pass
except KeyError:
pass
json_data = {}
if counter > 0:
pc.printout("\nWoohoo! We found " + str(counter) + " captions\n", pc.GREEN)
file = None
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_captions.txt"
file = open(file_name, "w")
for s in captions:
print(s + "\n")
if self.writeFile:
file.write(s + "\n")
if self.jsonDump:
json_data['captions'] = captions
json_file_name = self.output_dir + "/" + self.target + "_followings.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
if file is not None:
file.close()
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
return
def get_total_comments(self):
if self.check_private_profile():
return
pc.printout("Searching for target total comments...\n")
comments_counter = 0
posts = 0
data = self.__get_feed__()
for post in data:
comments_counter += post['comment_count']
posts += 1
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_comments.txt"
file = open(file_name, "w")
file.write(str(comments_counter) + " comments in " + str(posts) + " posts\n")
file.close()
if self.jsonDump:
json_data = {
'comment_counter': comments_counter,
'posts': posts
}
json_file_name = self.output_dir + "/" + self.target + "_comments.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
pc.printout(str(comments_counter), pc.MAGENTA)
pc.printout(" comments in " + str(posts) + " posts\n")
def get_comment_data(self):
if self.check_private_profile():
return
pc.printout("Retrieving all comments, this may take a moment...\n")
data = self.__get_feed__()
_comments = []
t = PrettyTable(['POST ID', 'ID', 'Username', 'Comment'])
t.align["POST ID"] = "l"
t.align["ID"] = "l"
t.align["Username"] = "l"
t.align["Comment"] = "l"
for post in data:
post_id = post.get('id')
comments = self.api.media_n_comments(post_id)
for comment in comments:
t.add_row([post_id, comment.get('user_id'), comment.get('user').get('username'), comment.get('text')])
comment = {
"post_id": post_id,
"user_id":comment.get('user_id'),
"username": comment.get('user').get('username'),
"comment": comment.get('text')
}
_comments.append(comment)
print(t)
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_comment_data.txt"
with open(file_name, 'w') as f:
f.write(str(t))
f.close()
if self.jsonDump:
file_name_json = self.output_dir + "/" + self.target + "_comment_data.json"
with open(file_name_json, 'w') as f:
f.write("{ \"Comments\":[ \n")
f.write('\n'.join(json.dumps(comment) for comment in _comments) + ',\n')
f.write("]} ")
def get_followers(self):
if self.check_private_profile():
return
pc.printout("Searching for target followers...\n")
_followers = []
followers = []
rank_token = AppClient.generate_uuid()
data = self.api.user_followers(str(self.target_id), rank_token=rank_token)
_followers.extend(data.get('users', []))
next_max_id = data.get('next_max_id')
while next_max_id:
sys.stdout.write("\rCatched %i followers" % len(_followers))
sys.stdout.flush()
results = self.api.user_followers(str(self.target_id), rank_token=rank_token, max_id=next_max_id)
_followers.extend(results.get('users', []))
next_max_id = results.get('next_max_id')
print("\n")
for user in _followers:
u = {
'id': user['pk'],
'username': user['username'],
'full_name': user['full_name']
}
followers.append(u)
t = PrettyTable(['ID', 'Username', 'Full Name'])
t.align["ID"] = "l"
t.align["Username"] = "l"
t.align["Full Name"] = "l"
json_data = {}
followings_list = []
for node in followers:
t.add_row([str(node['id']), node['username'], node['full_name']])
if self.jsonDump:
follow = {
'id': node['id'],
'username': node['username'],
'full_name': node['full_name']
}
followings_list.append(follow)
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_followers.txt"
file = open(file_name, "w")
file.write(str(t))
file.close()
if self.jsonDump:
json_data['followers'] = followers
json_file_name = self.output_dir + "/" + self.target + "_followers.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
print(t)
def get_followings(self):
if self.check_private_profile():
return
pc.printout("Searching for target followings...\n")
_followings = []
followings = []
rank_token = AppClient.generate_uuid()
data = self.api.user_following(str(self.target_id), rank_token=rank_token)
_followings.extend(data.get('users', []))
next_max_id = data.get('next_max_id')
while next_max_id:
sys.stdout.write("\rCatched %i followings" % len(_followings))
sys.stdout.flush()
results = self.api.user_following(str(self.target_id), rank_token=rank_token, max_id=next_max_id)
_followings.extend(results.get('users', []))
next_max_id = results.get('next_max_id')
print("\n")
for user in _followings:
u = {
'id': user['pk'],
'username': user['username'],
'full_name': user['full_name']
}
followings.append(u)
t = PrettyTable(['ID', 'Username', 'Full Name'])
t.align["ID"] = "l"
t.align["Username"] = "l"
t.align["Full Name"] = "l"
json_data = {}
followings_list = []
for node in followings:
t.add_row([str(node['id']), node['username'], node['full_name']])
if self.jsonDump:
follow = {
'id': node['id'],
'username': node['username'],
'full_name': node['full_name']
}
followings_list.append(follow)
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_followings.txt"
file = open(file_name, "w")
file.write(str(t))
file.close()
if self.jsonDump:
json_data['followings'] = followings_list
json_file_name = self.output_dir + "/" + self.target + "_followings.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
print(t)
def get_hashtags(self):
if self.check_private_profile():
return
pc.printout("Searching for target hashtags...\n")
hashtags = []
counter = 1
texts = []
data = self.api.user_feed(str(self.target_id))
texts.extend(data.get('items', []))
next_max_id = data.get('next_max_id')
while next_max_id:
results = self.api.user_feed(str(self.target_id), max_id=next_max_id)
texts.extend(results.get('items', []))
next_max_id = results.get('next_max_id')
for post in texts:
if post['caption'] is not None:
caption = post['caption']['text']
for s in caption.split():
if s.startswith('#'):
hashtags.append(s.encode('UTF-8'))
counter += 1
if len(hashtags) > 0:
hashtag_counter = {}
for i in hashtags:
if i in hashtag_counter:
hashtag_counter[i] += 1
else:
hashtag_counter[i] = 1
ssort = sorted(hashtag_counter.items(), key=lambda value: value[1], reverse=True)
file = None
json_data = {}
hashtags_list = []
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_hashtags.txt"
file = open(file_name, "w")
for k, v in ssort:
hashtag = str(k.decode('utf-8'))
print(str(v) + ". " + hashtag)
if self.writeFile:
file.write(str(v) + ". " + hashtag + "\n")
if self.jsonDump:
hashtags_list.append(hashtag)
if file is not None:
file.close()
if self.jsonDump:
json_data['hashtags'] = hashtags_list
json_file_name = self.output_dir + "/" + self.target + "_hashtags.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_user_info(self):
try:
endpoint = 'users/{user_id!s}/full_detail_info/'.format(**{'user_id': self.target_id})
content = self.api._call_api(endpoint)
data = content['user_detail']['user']
pc.printout("[ID] ", pc.GREEN)
pc.printout(str(data['pk']) + '\n')
pc.printout("[FULL NAME] ", pc.RED)
pc.printout(str(data['full_name']) + '\n')
pc.printout("[BIOGRAPHY] ", pc.CYAN)
pc.printout(str(data['biography']) + '\n')
pc.printout("[FOLLOWED] ", pc.BLUE)
pc.printout(str(data['follower_count']) + '\n')
pc.printout("[FOLLOW] ", pc.GREEN)
pc.printout(str(data['following_count']) + '\n')
pc.printout("[BUSINESS ACCOUNT] ", pc.RED)
pc.printout(str(data['is_business']) + '\n')
if data['is_business']:
if not data['can_hide_category']:
pc.printout("[BUSINESS CATEGORY] ")
pc.printout(str(data['category']) + '\n')
pc.printout("[VERIFIED ACCOUNT] ", pc.CYAN)
pc.printout(str(data['is_verified']) + '\n')
if 'public_email' in data and data['public_email']:
pc.printout("[EMAIL] ", pc.BLUE)
pc.printout(str(data['public_email']) + '\n')
pc.printout("[HD PROFILE PIC] ", pc.GREEN)
pc.printout(str(data['hd_profile_pic_url_info']['url']) + '\n')
if 'fb_page_call_to_action_id' in data and data['fb_page_call_to_action_id']:
pc.printout("[FB PAGE] ", pc.RED)
pc.printout(str(data['connected_fb_page']) + '\n')
if 'whatsapp_number' in data and data['whatsapp_number']:
pc.printout("[WHATSAPP NUMBER] ", pc.GREEN)
pc.printout(str(data['whatsapp_number']) + '\n')
if 'city_name' in data and data['city_name']:
pc.printout("[CITY] ", pc.YELLOW)
pc.printout(str(data['city_name']) + '\n')
if 'address_street' in data and data['address_street']:
pc.printout("[ADDRESS STREET] ", pc.RED)
pc.printout(str(data['address_street']) + '\n')
if 'contact_phone_number' in data and data['contact_phone_number']:
pc.printout("[CONTACT PHONE NUMBER] ", pc.CYAN)
pc.printout(str(data['contact_phone_number']) + '\n')
if self.jsonDump:
user = {
'id': data['pk'],
'full_name': data['full_name'],
'biography': data['biography'],
'edge_followed_by': data['follower_count'],
'edge_follow': data['following_count'],
'is_business_account': data['is_business'],
'is_verified': data['is_verified'],
'profile_pic_url_hd': data['hd_profile_pic_url_info']['url']
}
if 'public_email' in data and data['public_email']:
user['email'] = data['public_email']
if 'fb_page_call_to_action_id' in data and data['fb_page_call_to_action_id']:
user['connected_fb_page'] = data['fb_page_call_to_action_id']
if 'whatsapp_number' in data and data['whatsapp_number']:
user['whatsapp_number'] = data['whatsapp_number']
if 'city_name' in data and data['city_name']:
user['city_name'] = data['city_name']
if 'address_street' in data and data['address_street']:
user['address_street'] = data['address_street']
if 'contact_phone_number' in data and data['contact_phone_number']:
user['contact_phone_number'] = data['contact_phone_number']
json_file_name = self.output_dir + "/" + self.target + "_info.json"
with open(json_file_name, 'w') as f:
json.dump(user, f)
except ClientError as e:
print(e)
pc.printout("Oops... " + str(self.target) + " non exist, please enter a valid username.", pc.RED)
pc.printout("\n")
exit(2)
def get_total_likes(self):
if self.check_private_profile():
return
pc.printout("Searching for target total likes...\n")
like_counter = 0
posts = 0
data = self.__get_feed__()
for post in data:
like_counter += post['like_count']
posts += 1
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_likes.txt"
file = open(file_name, "w")
file.write(str(like_counter) + " likes in " + str(like_counter) + " posts\n")
file.close()
if self.jsonDump:
json_data = {
'like_counter': like_counter,
'posts': like_counter
}
json_file_name = self.output_dir + "/" + self.target + "_likes.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
pc.printout(str(like_counter), pc.MAGENTA)
pc.printout(" likes in " + str(posts) + " posts\n")
def get_media_type(self):
if self.check_private_profile():
return
pc.printout("Searching for target captions...\n")
counter = 0
photo_counter = 0
video_counter = 0
data = self.__get_feed__()
for post in data:
if "media_type" in post:
if post["media_type"] == 1:
photo_counter = photo_counter + 1
elif post["media_type"] == 2:
video_counter = video_counter + 1
counter = counter + 1
sys.stdout.write("\rChecked %i" % counter)
sys.stdout.flush()
sys.stdout.write(" posts")
sys.stdout.flush()
if counter > 0:
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_mediatype.txt"
file = open(file_name, "w")
file.write(str(photo_counter) + " photos and " + str(video_counter) + " video posted by target\n")
file.close()
pc.printout("\nWoohoo! We found " + str(photo_counter) + " photos and " + str(video_counter) +
" video posted by target\n", pc.GREEN)
if self.jsonDump:
json_data = {
"photos": photo_counter,
"videos": video_counter
}
json_file_name = self.output_dir + "/" + self.target + "_mediatype.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_people_who_commented(self):
if self.check_private_profile():
return
pc.printout("Searching for users who commented...\n")
data = self.__get_feed__()
users = []
for post in data:
comments = self.__get_comments__(post['id'])
for comment in comments:
if not any(u['id'] == comment['user']['pk'] for u in users):
user = {
'id': comment['user']['pk'],
'username': comment['user']['username'],
'full_name': comment['user']['full_name'],
'counter': 1
}
users.append(user)
else:
for user in users:
if user['id'] == comment['user']['pk']:
user['counter'] += 1
break
if len(users) > 0:
ssort = sorted(users, key=lambda value: value['counter'], reverse=True)
json_data = {}
t = PrettyTable()
t.field_names = ['Comments', 'ID', 'Username', 'Full Name']
t.align["Comments"] = "l"
t.align["ID"] = "l"
t.align["Username"] = "l"
t.align["Full Name"] = "l"
for u in ssort:
t.add_row([str(u['counter']), u['id'], u['username'], u['full_name']])
print(t)
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_users_who_commented.txt"
file = open(file_name, "w")
file.write(str(t))
file.close()
if self.jsonDump:
json_data['users_who_commented'] = ssort
json_file_name = self.output_dir + "/" + self.target + "_users_who_commented.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_people_who_tagged(self):
if self.check_private_profile():
return
pc.printout("Searching for users who tagged target...\n")
posts = []
result = self.api.usertag_feed(self.target_id)
posts.extend(result.get('items', []))
next_max_id = result.get('next_max_id')
while next_max_id:
results = self.api.user_feed(str(self.target_id), max_id=next_max_id)
posts.extend(results.get('items', []))
next_max_id = results.get('next_max_id')
if len(posts) > 0:
pc.printout("\nWoohoo! We found " + str(len(posts)) + " photos\n", pc.GREEN)
users = []
for post in posts:
if not any(u['id'] == post['user']['pk'] for u in users):
user = {
'id': post['user']['pk'],
'username': post['user']['username'],
'full_name': post['user']['full_name'],
'counter': 1
}
users.append(user)
else:
for user in users:
if user['id'] == post['user']['pk']:
user['counter'] += 1
break
ssort = sorted(users, key=lambda value: value['counter'], reverse=True)
json_data = {}
t = PrettyTable()
t.field_names = ['Photos', 'ID', 'Username', 'Full Name']
t.align["Photos"] = "l"
t.align["ID"] = "l"
t.align["Username"] = "l"
t.align["Full Name"] = "l"
for u in ssort:
t.add_row([str(u['counter']), u['id'], u['username'], u['full_name']])
print(t)
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_users_who_tagged.txt"
file = open(file_name, "w")
file.write(str(t))
file.close()
if self.jsonDump:
json_data['users_who_tagged'] = ssort
json_file_name = self.output_dir + "/" + self.target + "_users_who_tagged.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_photo_description(self):
if self.check_private_profile():
return
content = requests.get("https://www.instagram.com/" + str(self.target) + "/?__a=1")
data = content.json()
dd = data['graphql']['user']['edge_owner_to_timeline_media']['edges']
if len(dd) > 0:
pc.printout("\nWoohoo! We found " + str(len(dd)) + " descriptions\n", pc.GREEN)
count = 1
t = PrettyTable(['Photo', 'Description'])
t.align["Photo"] = "l"
t.align["Description"] = "l"
json_data = {}
descriptions_list = []
for i in dd:
node = i.get('node')
descr = node.get('accessibility_caption')
t.add_row([str(count), descr])
if self.jsonDump:
description = {
'description': descr
}
descriptions_list.append(description)
count += 1
if self.writeFile:
file_name = self.output_dir + "/" + self.target + "_photodes.txt"
file = open(file_name, "w")
file.write(str(t))
file.close()
if self.jsonDump:
json_data['descriptions'] = descriptions_list
json_file_name = self.output_dir + "/" + self.target + "_descriptions.json"
with open(json_file_name, 'w') as f:
json.dump(json_data, f)
print(t)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_user_photo(self):
if self.check_private_profile():
return
limit = -1
if self.cli_mode:
user_input = ""
else:
pc.printout("How many photos you want to download (default all): ", pc.YELLOW)
user_input = input()
try:
if user_input == "":
pc.printout("Downloading all photos available...\n")
else:
limit = int(user_input)
pc.printout("Downloading " + user_input + " photos...\n")
except ValueError:
pc.printout("Wrong value entered\n", pc.RED)
return
data = []
counter = 0
result = self.api.user_feed(str(self.target_id))
data.extend(result.get('items', []))
next_max_id = result.get('next_max_id')
while next_max_id:
results = self.api.user_feed(str(self.target_id), max_id=next_max_id)
data.extend(results.get('items', []))
next_max_id = results.get('next_max_id')
try:
for item in data:
if counter == limit:
break
if "image_versions2" in item:
counter = counter + 1
url = item["image_versions2"]["candidates"][0]["url"]
photo_id = item["id"]
end = self.output_dir + "/" + self.target + "_" + photo_id + ".jpg"
urllib.request.urlretrieve(url, end)
sys.stdout.write("\rDownloaded %i" % counter)
sys.stdout.flush()
else:
carousel = item["carousel_media"]
for i in carousel:
if counter == limit:
break
counter = counter + 1
url = i["image_versions2"]["candidates"][0]["url"]
photo_id = i["id"]
end = self.output_dir + "/" + self.target + "_" + photo_id + ".jpg"
urllib.request.urlretrieve(url, end)
sys.stdout.write("\rDownloaded %i" % counter)
sys.stdout.flush()
except AttributeError:
pass
except KeyError:
pass
sys.stdout.write(" photos")
sys.stdout.flush()
pc.printout("\nWoohoo! We downloaded " + str(counter) + " photos (saved in " + self.output_dir + " folder) \n", pc.GREEN)
def get_user_propic(self):
try:
endpoint = 'users/{user_id!s}/full_detail_info/'.format(**{'user_id': self.target_id})
content = self.api._call_api(endpoint)
data = content['user_detail']['user']
if "hd_profile_pic_url_info" in data:
URL = data["hd_profile_pic_url_info"]['url']
else:
#get better quality photo
items = len(data['hd_profile_pic_versions'])
URL = data["hd_profile_pic_versions"][items-1]['url']
if URL != "":
end = self.output_dir + "/" + self.target + "_propic.jpg"
urllib.request.urlretrieve(URL, end)
pc.printout("Target propic saved in output folder\n", pc.GREEN)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
except ClientError as e:
error = json.loads(e.error_response)
print(error['message'])
print(error['error_title'])
exit(2)
def get_user_stories(self):
if self.check_private_profile():
return
pc.printout("Searching for target stories...\n")
data = self.api.user_reel_media(str(self.target_id))
counter = 0
if data['items'] is not None: # no stories avaibile
counter = data['media_count']
for i in data['items']:
story_id = i["id"]
if i["media_type"] == 1: # it's a photo
url = i['image_versions2']['candidates'][0]['url']
end = self.output_dir + "/" + self.target + "_" + story_id + ".jpg"
urllib.request.urlretrieve(url, end)
elif i["media_type"] == 2: # it's a gif or video
url = i['video_versions'][0]['url']
end = self.output_dir + "/" + self.target + "_" + story_id + ".mp4"
urllib.request.urlretrieve(url, end)
if counter > 0:
pc.printout(str(counter) + " target stories saved in output folder\n", pc.GREEN)
else:
pc.printout("Sorry! No results found :-(\n", pc.RED)
def get_people_tagged_by_user(self):
pc.printout("Searching for users tagged by target...\n")
ids = []
username = []
full_name = []
post = []
counter = 1
data = self.__get_feed__()
try:
for i in data:
if "usertags" in i:
c = i.get('usertags').get('in')
for cc in c:
if cc.get('user').get('pk') not in ids:
ids.append(cc.get('user').get('pk'))
username.append(cc.get('user').get('username'))
full_name.append(cc.get('user').get('full_name'))
post.append(1)
else:
index = ids.index(cc.get('user').get('pk'))
post[index] += 1
counter = counter + 1
except AttributeError as ae: