-
Notifications
You must be signed in to change notification settings - Fork 3
/
github_monitor.py
1978 lines (1600 loc) · 89.3 KB
/
github_monitor.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
"""
Author: Michal Szymanski <[email protected]>
v1.4
OSINT tool implementing real-time tracking of Github users activities including profile and repositories changes:
https://github.com/misiektoja/github_monitor/
Python pip3 requirements:
PyGithub
pytz
tzlocal
python-dateutil
requests
"""
VERSION = 1.4
# ---------------------------
# CONFIGURATION SECTION START
# ---------------------------
# Get your Github personal access token (classic) by going to: https://github.com/settings/apps
# Then click Personal access tokens -> Tokens (classic) -> Generate new token (classic)
# Put the token value below (or use -t parameter)
GITHUB_TOKEN = "your_github_classic_personal_access_token"
# SMTP settings for sending email notifications, you can leave it as it is below and no notifications will be sent
SMTP_HOST = "your_smtp_server_ssl"
SMTP_PORT = 587
SMTP_USER = "your_smtp_user"
SMTP_PASSWORD = "your_smtp_password"
SMTP_SSL = True
SENDER_EMAIL = "your_sender_email"
# SMTP_HOST = "your_smtp_server_plaintext"
# SMTP_PORT = 25
# SMTP_USER = "your_smtp_user"
# SMTP_PASSWORD = "your_smtp_password"
# SMTP_SSL = False
# SENDER_EMAIL = "your_sender_email"
RECEIVER_EMAIL = "your_receiver_email"
# How often do we perform checks for user activity, you can also use -c parameter; in seconds
GITHUB_CHECK_INTERVAL = 600 # 10 mins
# Specify your local time zone so we convert Github API timestamps to your time (for example: 'Europe/Warsaw')
# If you leave it as 'Auto' we will try to automatically detect the local timezone
LOCAL_TIMEZONE = 'Auto'
# What kind of events we want to monitor, if you put 'ALL' then all of them will be monitored
EVENTS_TO_MONITOR = ['ALL', 'PushEvent', 'PullRequestReviewEvent', 'CreateEvent', 'DeleteEvent', 'PullRequestEvent', 'PullRequestReviewCommentEvent', 'IssuesEvent', 'WatchEvent', 'ForkEvent', 'ReleaseEvent', 'IssueCommentEvent']
# How many last events we check when we get signal that last event ID has changed
EVENTS_NUMBER = 10
# How often do we perform alive check by printing "alive check" message in the output; in seconds
TOOL_ALIVE_INTERVAL = 21600 # 6 hours
# URL we check in the beginning to make sure we have internet connectivity
CHECK_INTERNET_URL = 'http://www.google.com/'
# Default value for initial checking of internet connectivity; in seconds
CHECK_INTERNET_TIMEOUT = 5
# The name of the .log file; the tool by default will output its messages to github_monitor_username.log file
GITHUB_LOGFILE = "github_monitor"
# Value used by signal handlers increasing/decreasing the user activity check (GITHUB_CHECK_INTERVAL); in seconds
GITHUB_CHECK_SIGNAL_VALUE = 60 # 1 minute
# -------------------------
# CONFIGURATION SECTION END
# -------------------------
TOOL_ALIVE_COUNTER = TOOL_ALIVE_INTERVAL / GITHUB_CHECK_INTERVAL
stdout_bck = None
csvfieldnames = ['Date', 'Type', 'Name', 'Old', 'New']
event_notification = False
profile_notification = False
repo_notification = False
repo_update_date_notification = False
track_repos_changes = False
# to solve the issue: 'SyntaxError: f-string expression part cannot include a backslash'
nl_ch = "\n"
import sys
import time
import string
import os
from datetime import datetime
from dateutil import relativedelta
import calendar
import requests as req
import signal
import smtplib
import ssl
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import argparse
import csv
import pytz
try:
from tzlocal import get_localzone
except ImportError:
pass
import platform
import re
import ipaddress
from github import Github
from github import Auth
# Logger class to output messages to stdout and log file
class Logger(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.logfile = open(filename, "a", buffering=1, encoding="utf-8")
def write(self, message):
self.terminal.write(message)
self.logfile.write(message)
self.terminal.flush()
self.logfile.flush()
def flush(self):
pass
# Signal handler when user presses Ctrl+C
def signal_handler(sig, frame):
sys.stdout = stdout_bck
print('\n* You pressed Ctrl+C, tool is terminated.')
sys.exit(0)
# Function to check internet connectivity
def check_internet():
url = CHECK_INTERNET_URL
try:
_ = req.get(url, timeout=CHECK_INTERNET_TIMEOUT)
print("OK")
return True
except Exception as e:
print(f"No connectivity, please check your network - {e}")
sys.exit(1)
return False
# Function to convert absolute value of seconds to human readable format
def display_time(seconds, granularity=2):
intervals = (
('years', 31556952), # approximation
('months', 2629746), # approximation
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
result = []
if seconds > 0:
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append(f"{value} {name}")
return ', '.join(result[:granularity])
else:
return '0 seconds'
# Function to calculate time span between two timestamps in seconds
def calculate_timespan(timestamp1, timestamp2, show_weeks=True, show_hours=True, show_minutes=True, show_seconds=True, granularity=3):
result = []
intervals = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']
ts1 = timestamp1
ts2 = timestamp2
if type(timestamp1) is int:
dt1 = datetime.fromtimestamp(int(ts1))
elif type(timestamp1) is float:
ts1 = int(round(ts1))
dt1 = datetime.fromtimestamp(ts1)
elif type(timestamp1) is datetime:
dt1 = timestamp1
ts1 = int(round(dt1.timestamp()))
else:
return ""
if type(timestamp2) is int:
dt2 = datetime.fromtimestamp(int(ts2))
elif type(timestamp2) is float:
ts2 = int(round(ts2))
dt2 = datetime.fromtimestamp(ts2)
elif type(timestamp2) is datetime:
dt2 = timestamp2
ts2 = int(round(dt2.timestamp()))
else:
return ""
if ts1 >= ts2:
ts_diff = ts1 - ts2
else:
ts_diff = ts2 - ts1
dt1, dt2 = dt2, dt1
if ts_diff > 0:
date_diff = relativedelta.relativedelta(dt1, dt2)
years = date_diff.years
months = date_diff.months
weeks = date_diff.weeks
if not show_weeks:
weeks = 0
days = date_diff.days
if weeks > 0:
days = days - (weeks * 7)
hours = date_diff.hours
if (not show_hours and ts_diff > 86400):
hours = 0
minutes = date_diff.minutes
if (not show_minutes and ts_diff > 3600):
minutes = 0
seconds = date_diff.seconds
if (not show_seconds and ts_diff > 60):
seconds = 0
date_list = [years, months, weeks, days, hours, minutes, seconds]
for index, interval in enumerate(date_list):
if interval > 0:
name = intervals[index]
if interval == 1:
name = name.rstrip('s')
result.append(f"{interval} {name}")
return ', '.join(result[:granularity])
else:
return '0 seconds'
# Function to send email notification
def send_email(subject, body, body_html, use_ssl, smtp_timeout=15):
fqdn_re = re.compile(r'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}\.?$)')
email_re = re.compile(r'[^@]+@[^@]+\.[^@]+')
try:
is_ip = ipaddress.ip_address(str(SMTP_HOST))
except ValueError:
if not fqdn_re.search(str(SMTP_HOST)):
print("Error sending email - SMTP settings are incorrect (invalid IP address/FQDN in SMTP_HOST)")
return 1
try:
port = int(SMTP_PORT)
if not (1 <= port <= 65535):
raise ValueError
except ValueError:
print("Error sending email - SMTP settings are incorrect (invalid port number in SMTP_PORT)")
return 1
if not email_re.search(str(SENDER_EMAIL)) or not email_re.search(str(RECEIVER_EMAIL)):
print("Error sending email - SMTP settings are incorrect (invalid email in SENDER_EMAIL or RECEIVER_EMAIL)")
return 1
if not SMTP_USER or not isinstance(SMTP_USER, str) or SMTP_USER == "your_smtp_user" or not SMTP_PASSWORD or not isinstance(SMTP_PASSWORD, str) or SMTP_PASSWORD == "your_smtp_password":
print("Error sending email - SMTP settings are incorrect (check SMTP_USER & SMTP_PASSWORD variables)")
return 1
if not subject or not isinstance(subject, str):
print("Error sending email - SMTP settings are incorrect (subject is not a string or is empty)")
return 1
if not body and not body_html:
print("Error sending email - SMTP settings are incorrect (body and body_html cannot be empty at the same time)")
return 1
try:
if use_ssl:
ssl_context = ssl.create_default_context()
smtpObj = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=smtp_timeout)
smtpObj.starttls(context=ssl_context)
else:
smtpObj = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=smtp_timeout)
smtpObj.login(SMTP_USER, SMTP_PASSWORD)
email_msg = MIMEMultipart('alternative')
email_msg["From"] = SENDER_EMAIL
email_msg["To"] = RECEIVER_EMAIL
email_msg["Subject"] = Header(subject, 'utf-8')
if body:
part1 = MIMEText(body, 'plain')
part1 = MIMEText(body.encode('utf-8'), 'plain', _charset='utf-8')
email_msg.attach(part1)
if body_html:
part2 = MIMEText(body_html, 'html')
part2 = MIMEText(body_html.encode('utf-8'), 'html', _charset='utf-8')
email_msg.attach(part2)
smtpObj.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, email_msg.as_string())
smtpObj.quit()
except Exception as e:
print(f"Error sending email - {e}")
return 1
return 0
# Function to write CSV entry
def write_csv_entry(csv_file_name, timestamp, object_type, object_name, old, new):
try:
csv_file = open(csv_file_name, 'a', newline='', buffering=1, encoding="utf-8")
csvwriter = csv.DictWriter(csv_file, fieldnames=csvfieldnames, quoting=csv.QUOTE_NONNUMERIC)
csvwriter.writerow({'Date': timestamp, 'Type': object_type, 'Name': object_name, 'Old': old, 'New': new})
csv_file.close()
except Exception as e:
raise
# Function to return the timestamp in human readable format; eg. Sun, 21 Apr 2024, 15:08:45
def get_cur_ts(ts_str=""):
return (f'{ts_str}{calendar.day_abbr[(datetime.fromtimestamp(int(time.time()))).weekday()]}, {datetime.fromtimestamp(int(time.time())).strftime("%d %b %Y, %H:%M:%S")}')
# Function to print the current timestamp in human readable format; eg. Sun, 21 Apr 2024, 15:08:45
def print_cur_ts(ts_str=""):
print(get_cur_ts(str(ts_str)))
print("---------------------------------------------------------------------------------------------------------")
# Function to return the timestamp/datetime object in human readable format (long version); eg. Sun, 21 Apr 2024, 15:08:45
def get_date_from_ts(ts):
if type(ts) is datetime:
ts_new = int(round(ts.timestamp()))
elif type(ts) is int:
ts_new = ts
elif type(ts) is float:
ts_new = int(round(ts))
else:
return ""
return (f'{calendar.day_abbr[(datetime.fromtimestamp(ts_new)).weekday()]} {datetime.fromtimestamp(ts_new).strftime("%d %b %Y, %H:%M:%S")}')
# Function to return the timestamp/datetime object in human readable format (short version); eg.
# Sun 21 Apr 15:08
# Sun 21 Apr 24, 15:08 (if show_year == True and current year is different)
# Sun 21 Apr (if show_hour == False)
def get_short_date_from_ts(ts, show_year=False, show_hour=True):
if type(ts) is datetime:
ts_new = int(round(ts.timestamp()))
elif type(ts) is int:
ts_new = ts
elif type(ts) is float:
ts_new = int(round(ts))
else:
return ""
if show_hour:
hour_strftime = " %H:%M"
else:
hour_strftime = ""
if show_year and int(datetime.fromtimestamp(ts_new).strftime("%Y")) != int(datetime.now().strftime("%Y")):
if show_hour:
hour_prefix = ","
else:
hour_prefix = ""
return (f'{calendar.day_abbr[(datetime.fromtimestamp(ts_new)).weekday()]} {datetime.fromtimestamp(ts_new).strftime(f"%d %b %y{hour_prefix}{hour_strftime}")}')
else:
return (f'{calendar.day_abbr[(datetime.fromtimestamp(ts_new)).weekday()]} {datetime.fromtimestamp(ts_new).strftime(f"%d %b{hour_strftime}")}')
# Function to convert UTC string returned by Github API to datetime object in specified timezone
def convert_utc_str_to_tz_datetime(utc_string, timezone, version=1):
try:
if version == 1:
utc_string_sanitize = utc_string.split('+', 1)[0]
utc_string_sanitize = utc_string_sanitize.split('.', 1)[0]
dt_utc = datetime.strptime(utc_string_sanitize, '%Y-%m-%d %H:%M:%S')
elif version == 2:
utc_string_sanitize = utc_string
dt_utc = datetime.strptime(utc_string_sanitize, '%Y-%m-%dT%H:%M:%SZ')
old_tz = pytz.timezone("UTC")
new_tz = pytz.timezone(timezone)
dt_new_tz = old_tz.localize(dt_utc).astimezone(new_tz)
return dt_new_tz
except Exception as e:
return datetime.fromtimestamp(0)
def print_v(text=""):
print(text)
return text + "\n"
# Signal handler for SIGUSR1 allowing to switch email notifications for user's profile changes
def toggle_profile_changes_notifications_signal_handler(sig, frame):
global profile_notification
profile_notification = not profile_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [profile changes = {profile_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGUSR2 allowing to switch email notifications for user's new events
def toggle_new_events_notifications_signal_handler(sig, frame):
global event_notification
event_notification = not event_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [new events = {event_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGCONT allowing to switch email notifications for user's repositories changes (except for update date)
def toggle_repo_changes_notifications_signal_handler(sig, frame):
global repo_notification
repo_notification = not repo_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [repos changes = {repo_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGPIPE allowing to switch email notifications for user's repositories update date changes
def toggle_repo_update_date_changes_notifications_signal_handler(sig, frame):
global repo_update_date_notification
repo_update_date_notification = not repo_update_date_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [repos update date = {repo_update_date_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGTRAP allowing to increase check timer by GITHUB_CHECK_SIGNAL_VALUE seconds
def increase_check_signal_handler(sig, frame):
global GITHUB_CHECK_INTERVAL
GITHUB_CHECK_INTERVAL = GITHUB_CHECK_INTERVAL + GITHUB_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Github timers: [check interval: {display_time(GITHUB_CHECK_INTERVAL)}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGABRT allowing to decrease check timer by GITHUB_CHECK_SIGNAL_VALUE seconds
def decrease_check_signal_handler(sig, frame):
global GITHUB_CHECK_INTERVAL
if GITHUB_CHECK_INTERVAL - GITHUB_CHECK_SIGNAL_VALUE > 0:
GITHUB_CHECK_INTERVAL = GITHUB_CHECK_INTERVAL - GITHUB_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Github timers: [check interval: {display_time(GITHUB_CHECK_INTERVAL)}]")
print_cur_ts("Timestamp:\t\t\t")
# Function converting Github API URL to HTML URL
def github_convert_api_to_html_url(url):
html_url = ""
if "https://api.github.com/repos/" in url:
url_suffix = url.split('https://api.github.com/repos/', 1)[1]
html_url = "https://github.com/" + url_suffix
return html_url
# Function printing followers & followings for Github user (-f)
def github_print_followers_and_followings(user):
print(f"Getting followers & followings for user '{user}' ...")
auth = Auth.Token(GITHUB_TOKEN)
g = Github(auth=auth)
g_user = g.get_user(user)
user_login = g_user.login
user_name = g_user.name
user_url = g_user.html_url
followers_count = g_user.followers
followings_count = g_user.following
followers_list = g_user.get_followers()
followings_list = g_user.get_following()
user_name_str = user_login
if user_name:
user_name_str += f" ({user_name})"
print(f"\nUsername:\t{user_name_str}")
print(f"URL:\t\t{user_url}/")
print(f"\nFollowers:\t{followers_count}")
if followers_list:
for follower in followers_list:
follower_str = f"\n- {follower.login}"
if follower.name:
follower_str += f" ({follower.name})"
if follower.html_url:
follower_str += f"\n[ {follower.html_url}/ ]"
print(follower_str)
print(f"\nFollowings:\t{followings_count}")
if followings_list:
for following in followings_list:
following_str = f"\n- {following.login}"
if following.name:
following_str += f" ({following.name})"
if following.html_url:
following_str += f"\n[ {following.html_url}/ ]"
print(following_str)
g.close()
# Function processing items of all passed repos and returning list of dictionaries
def github_process_repos(repos_list):
list_of_repos = []
stargazers = []
subscribers = []
forked_repos = []
if repos_list:
for repo in repos_list:
try:
repo_created_date = repo.created_at
repo_created_date_ts = convert_utc_str_to_tz_datetime(str(repo_created_date), LOCAL_TIMEZONE, 1).timestamp()
repo_updated_date = repo.updated_at
repo_updated_date_ts = convert_utc_str_to_tz_datetime(str(repo_updated_date), LOCAL_TIMEZONE, 1).timestamp()
stargazers = [star.login for star in repo.get_stargazers()]
subscribers = [subscriber.login for subscriber in repo.get_subscribers()]
forked_repos = [fork.full_name for fork in repo.get_forks()]
list_of_repos.append({"name": repo.name, "descr": repo.description, "is_fork": repo.fork, "forks": repo.forks_count, "stars": repo.stargazers_count, "watchers": repo.subscribers_count, "url": repo.html_url, "language": repo.language, "date": repo_created_date_ts, "update_date": repo_updated_date_ts, "stargazers": stargazers, "forked_repos": forked_repos, "subscribers": subscribers})
except Exception as e:
print(f"Error while processing info for repo '{repo.name}', skipping for now - {e}")
print_cur_ts("Timestamp:\t\t")
continue
return list_of_repos
# Function printing list of public repositories for Github user (-r)
def github_print_repos(user):
print(f"Getting public repositories for user '{user}' ...")
auth = Auth.Token(GITHUB_TOKEN)
g = Github(auth=auth)
g_user = g.get_user(user)
user_login = g_user.login
user_name = g_user.name
user_url = g_user.html_url
repos_count = g_user.public_repos
repos_list = g_user.get_repos()
user_name_str = user_login
if user_name:
user_name_str += f" ({user_name})"
print(f"\nUsername:\t{user_name_str}")
print(f"URL:\t\t{user_url}/")
print(f"\nRepositories:\t{repos_count}")
if repos_list:
for repo in repos_list:
repo_str = f"\n- '{repo.name}' (fork: {repo.fork})"
repo_str += f"\n[ {repo.language}, forks: {repo.forks_count}, stars: {repo.stargazers_count}, watchers: {repo.subscribers_count} ]"
if repo.html_url:
repo_str += f"\n[ {repo.html_url}/ ]"
repo_created_date = repo.created_at
repo_created_date_ts = convert_utc_str_to_tz_datetime(str(repo_created_date), LOCAL_TIMEZONE, 1).timestamp()
repo_updated_date = repo.updated_at
repo_updated_date_ts = convert_utc_str_to_tz_datetime(str(repo_updated_date), LOCAL_TIMEZONE, 1).timestamp()
repo_str += f"\n[ date: {get_date_from_ts(repo_created_date_ts)} - {calculate_timespan(int(time.time()), int(repo_created_date_ts), granularity=2)} ago) ]"
repo_str += f"\n[ update: {get_date_from_ts(repo_updated_date_ts)} - {calculate_timespan(int(time.time()), int(repo_updated_date_ts), granularity=2)} ago) ]"
if repo.description:
repo_str += f"\n'{repo.description}'"
print(repo_str)
g.close()
# Function printing list of starred repositories by Github user (-g)
def github_print_starred_repos(user):
print(f"Getting repositories starred by user '{user}' ...")
auth = Auth.Token(GITHUB_TOKEN)
g = Github(auth=auth)
g_user = g.get_user(user)
user_login = g_user.login
user_name = g_user.name
user_url = g_user.html_url
starred_list = g_user.get_starred()
starred_count = starred_list.totalCount
user_name_str = user_login
if user_name:
user_name_str += f" ({user_name})"
print(f"\nUsername:\t\t{user_name_str}")
print(f"URL:\t\t\t{user_url}/")
print(f"\nRepos starred by user:\t{starred_count}")
if starred_list:
for star in starred_list:
star_str = f"\n- {star.full_name}"
if star.html_url:
star_str += f" [ {star.html_url}/ ]"
print(star_str)
g.close()
def github_print_event(event, g, time_passed=False, ts=0):
event_date_ts = 0
repo_name = ""
repo_url = ""
st = ""
tp = ""
event_date_ts = convert_utc_str_to_tz_datetime(str(event.created_at), LOCAL_TIMEZONE, 1).timestamp()
if time_passed and not ts:
tp = f" ({calculate_timespan(int(time.time()), int(event_date_ts), show_seconds=False, granularity=2)} ago)"
elif time_passed and ts:
tp = f" (after {calculate_timespan(int(event_date_ts), int(ts), show_seconds=False, granularity=2)}: {get_short_date_from_ts(int(ts))})"
st += print_v(f"Event date:\t\t\t{get_date_from_ts(event_date_ts)}{tp}")
st += print_v(f"Event ID:\t\t\t{event.id}")
st += print_v(f"Event type:\t\t\t{event.type}")
if event.repo.id:
repo_name = event.repo.name
repo_url = github_convert_api_to_html_url(event.repo.url)
st += print_v(f"\nRepo name:\t\t\t{repo_name}")
st += print_v(f"Repo URL:\t\t\t{repo_url}")
repo = g.get_repo(event.repo.name)
if hasattr(event.actor, 'login'):
if event.actor.login:
st += print_v(f"\nEvent actor login:\t\t{event.actor.login}")
if hasattr(event.actor, 'name'):
if event.actor.name:
st += print_v(f"Event actor name:\t\t{event.actor.name}")
if event.payload.get("ref"):
st += print_v(f"\nObject name:\t\t\t{event.payload.get('ref')}")
if event.payload.get("ref_type"):
st += print_v(f"Object type:\t\t\t{event.payload.get('ref_type')}")
if event.payload.get("description"):
st += print_v(f"Description:\t\t\t'{event.payload.get('description')}'")
if event.payload.get("action"):
st += print_v(f"\nAction:\t\t\t\t{event.payload.get('action')}")
if event.payload.get("commits"):
st += print_v(f"\nNumber of commits:\t\t{len(event.payload.get('commits'))}")
commits = event.payload["commits"]
for commit in commits:
commit_details = repo.get_commit(sha=commit["sha"])
commit_date_ts = convert_utc_str_to_tz_datetime(str(commit_details.commit.author.date), LOCAL_TIMEZONE, 1).timestamp()
st += print_v(f" - Commit date:\t\t\t{get_date_from_ts(commit_date_ts)}")
st += print_v(f" - Commit sha:\t\t\t{commit['sha']}")
st += print_v(f" - Commit author:\t\t{commit['author']['name']}")
st += print_v(f" - Commit URL:\t\t\t{github_convert_api_to_html_url(commit['url'])}")
st += print_v(f" - Commit message:\t\t'{commit['message']}'")
if commit != commits[-1]:
st += print_v()
if event.payload.get("release"):
st += print_v(f"\nRelease name:\t\t\t{event.payload['release'].get('name')}")
st += print_v(f"Release URL:\t\t\t{event.payload['release'].get('html_url')}")
st += print_v(f"Release tag name:\t\t{event.payload['release'].get('tag_name')}")
if event.payload["release"].get("assets"):
assets = event.payload["release"].get("assets")
for asset in assets:
st += print_v(f" - Asset name:\t\t\t{asset.get('name')}")
st += print_v(f" - Asset size:\t\t\t{asset.get('size')}")
st += print_v(f" - Download URL:\t\t{asset.get('browser_download_url')}")
if asset != assets[-1]:
st += print_v()
st += print_v(f"Release description:\n\n'{event.payload['release'].get('body')}'")
if event.payload.get("pull_request"):
st += print_v(f"\nPR title:\t\t\t{event.payload['pull_request'].get('title')}")
pr_date_ts = convert_utc_str_to_tz_datetime(str(event.payload["pull_request"].get("created_at")), LOCAL_TIMEZONE, 2).timestamp()
st += print_v(f"PR date:\t\t\t{get_date_from_ts(pr_date_ts)}")
st += print_v(f"PR URL:\t\t\t\t{event.payload['pull_request'].get('html_url')}")
if event.payload["pull_request"].get("issue_url"):
st += print_v(f"Issue URL:\t\t\t{github_convert_api_to_html_url(event.payload['pull_request'].get('issue_url'))}")
if event.payload["pull_request"].get("state"):
st += print_v(f"PR state:\t\t\t{event.payload['pull_request'].get('state')}")
st += print_v(f"Commits:\t\t\t{event.payload['pull_request'].get('commits', 0)}")
st += print_v(f"Comments:\t\t\t{event.payload['pull_request'].get('comments', 0)}")
additions = event.payload["pull_request"].get("additions", 0)
deletions = event.payload["pull_request"].get("deletions", 0)
st += print_v(f"Additions/deletions:\t\t{additions}/{deletions}")
st += print_v(f"Changed files:\t\t\t{event.payload['pull_request'].get('changed_files', 0)}")
if event.payload["pull_request"].get("body"):
st += print_v(f"PR description:\n\n'{event.payload['pull_request'].get('body')}'")
if event.payload["pull_request"].get("requested_reviewers"):
for requested_reviewer in event.payload["pull_request"].get("requested_reviewers"):
st += print_v(f"\n - Requested reviewer name:\t{requested_reviewer.get('login')}")
st += print_v(f" - Requested reviewer URL:\t{requested_reviewer.get('html_url')}")
if event.payload["pull_request"].get("assignees"):
for assignee in event.payload["pull_request"].get("assignees"):
st += print_v(f"\n - Assignee name:\t\t{assignee.get('login')}")
st += print_v(f" - Assignee URL:\t\t{assignee.get('html_url')}")
if event.payload.get("review"):
review_date_ts = convert_utc_str_to_tz_datetime(str(event.payload["review"].get("submitted_at")), LOCAL_TIMEZONE, 2).timestamp()
st += print_v(f"\nRequested review date:\t\t{get_date_from_ts(review_date_ts)}")
st += print_v(f"Requested review URL:\t\t{event.payload['review'].get('html_url')}")
if event.payload["review"].get("state"):
st += print_v(f"Requested review state:\t\t{event.payload['review'].get('state')}")
if event.payload["review"].get("body"):
st += print_v(f"Requested review description:\n'{event.payload['review'].get('body')}'")
if event.payload.get("comment"):
comment_date_ts = convert_utc_str_to_tz_datetime(str(event.payload["comment"].get("created_at")), LOCAL_TIMEZONE, 2).timestamp()
st += print_v(f"\nComment date:\t\t\t{get_date_from_ts(comment_date_ts)}")
if event.payload["comment"].get("body"):
st += print_v(f"Comment body:\t\t\t'{event.payload['comment'].get('body')}'")
st += print_v(f"Comment URL:\t\t\t{event.payload['comment'].get('html_url')}")
if event.payload["comment"].get("path"):
st += print_v(f"Comment path:\t\t\t{event.payload['comment'].get('path')}")
if event.payload.get("issue"):
st += print_v(f"\nIssue title:\t\t\t{event.payload['issue'].get('title')}")
issue_date_ts = convert_utc_str_to_tz_datetime(str(event.payload["issue"].get("created_at")), LOCAL_TIMEZONE, 2).timestamp()
st += print_v(f"Issue date:\t\t\t{get_date_from_ts(issue_date_ts)}")
st += print_v(f"Issue URL:\t\t\t{event.payload['issue'].get('html_url')}")
if event.payload["issue"].get("state"):
st += print_v(f"Issue state:\t\t\t{event.payload['issue'].get('state')}")
st += print_v(f"Issue comments:\t\t\t{event.payload['issue'].get('comments', 0)}")
if event.payload["issue"].get("assignees"):
assignees = event.payload["issue"].get("assignees")
for assignee in assignees:
st += print_v(f" - Assignee name:\t\t{assignee.get('name')}")
if assignee != assignees[-1]:
st += print_v()
if event.payload["issue"].get("body"):
st += print_v(f"Issue body:\n'{event.payload['issue'].get('body')}'")
if event.payload.get("forkee"):
st += print_v(f"\nForked to repo:\t\t\t{event.payload['forkee'].get('full_name')}")
st += print_v(f"Forked to repo (URL):\t\t{event.payload['forkee'].get('html_url')}")
return event_date_ts, repo_name, repo_url, st
# Function listing recent events for the user (-l)
def github_list_events(user, number, g):
g_user = g.get_user(user)
events = g_user.get_events()
for i in reversed(range(number)):
event = events[i]
if event.type in EVENTS_TO_MONITOR or 'ALL' in EVENTS_TO_MONITOR:
github_print_event(event, g)
print_cur_ts("\nTimestamp:\t\t\t")
# Main function monitoring activity of the specified Github user
def github_monitor_user(user, error_notification, csv_file_name, csv_exists):
try:
if csv_file_name:
csv_file = open(csv_file_name, 'a', newline='', buffering=1, encoding="utf-8")
csvwriter = csv.DictWriter(csv_file, fieldnames=csvfieldnames, quoting=csv.QUOTE_NONNUMERIC)
if not csv_exists:
csvwriter.writeheader()
csv_file.close()
except Exception as e:
print(f"* Error - {e}")
followers_count = 0
followings_count = 0
repos_count = 0
starred_count = 0
try:
auth = Auth.Token(GITHUB_TOKEN)
g = Github(auth=auth)
g_user_myself = g.get_user()
user_myself_login = g_user_myself.login
user_myself_name = g_user_myself.name
g_user = g.get_user(user)
user_login = g_user.login
user_name = g_user.name
user_url = g_user.html_url
location = g_user.location
bio = g_user.bio
company = g_user.company
email = g_user.email
blog = g_user.blog
account_created_date = g_user.created_at
account_updated_date = g_user.updated_at
followers_count = g_user.followers
followings_count = g_user.following
repos_count = g_user.public_repos
followers_list = g_user.get_followers()
followings_list = g_user.get_following()
repos_list = g_user.get_repos()
starred_list = g_user.get_starred()
starred_count = starred_list.totalCount
events = g_user.get_events()
except Exception as e:
print(f"* Error - {e}")
sys.exit(1)
last_event_id = 0
last_event_ts = 0
events_list_of_ids = []
try:
for i in reversed(range(EVENTS_NUMBER)):
event = events[i]
if i == 0:
last_event_id = event.id
if last_event_id:
last_event_ts = int(convert_utc_str_to_tz_datetime(str(event.created_at), LOCAL_TIMEZONE, 1).timestamp())
events_list_of_ids.append(event.id)
except Exception as e:
print(f"* Cannot get event IDs / timestamps - {e}")
pass
followers_old_count = followers_count
followings_old_count = followings_count
repos_old_count = repos_count
starred_old_count = starred_count
user_name_old = user_name
location_old = location
bio_old = bio
company_old = company
email_old = email
blog_old = blog
last_event_id_old = last_event_id
last_event_ts_old = last_event_ts
events_list_of_ids_old = events_list_of_ids
user_myself_name_str = user_myself_login
if user_myself_name:
user_myself_name_str += f" ({user_myself_name})"
print(f"\nToken belongs to:\t\t{user_myself_name_str}")
user_name_str = user_login
if user_name:
user_name_str += f" ({user_name})"
print(f"\nUsername:\t\t\t{user_name_str}")
print(f"URL:\t\t\t\t{user_url}/")
if location:
print(f"Location:\t\t\t{location}")
if company:
print(f"Company:\t\t\t{company}")
if email:
print(f"Email:\t\t\t\t{email}")
if blog:
print(f"Blog URL:\t\t\t{blog}")
account_created_date_ts = convert_utc_str_to_tz_datetime(str(account_created_date), LOCAL_TIMEZONE, 1).timestamp()
print(f"\nAccount creation date:\t\t{get_date_from_ts(account_created_date_ts)} ({calculate_timespan(int(time.time()), int(account_created_date_ts), granularity=2)} ago)")
account_updated_date_ts = convert_utc_str_to_tz_datetime(str(account_updated_date), LOCAL_TIMEZONE, 1).timestamp()
print(f"Account updated date:\t\t{get_date_from_ts(account_updated_date_ts)} ({calculate_timespan(int(time.time()), int(account_updated_date_ts), granularity=2)} ago)")
account_updated_date_old_ts = account_updated_date_ts
print(f"\nFollowers:\t\t\t{followers_count}")
print(f"Followings:\t\t\t{followings_count}")
print(f"Repositories:\t\t\t{repos_count}")
print(f"Starred repos:\t\t\t{starred_count}")
if bio:
print(f"\nBio:\n\n'{bio}'")
print_cur_ts("\nTimestamp:\t\t\t")
list_of_repos = []
if repos_list and track_repos_changes:
print("Processing list of public repositories (be patient, it might take a while) ...")
list_of_repos = github_process_repos(repos_list)
print_cur_ts("\nTimestamp:\t\t\t")
list_of_repos_old = list_of_repos
print(f"Latest event:\n")
try:
last_event = events[0]
github_print_event(last_event, g, True)
except IndexError:
print("There are no events yet")
except Exception as e:
print(f"Cannot print last event details - {e}")
print_cur_ts("\nTimestamp:\t\t\t")
followers = []
followings = []
repos = []
starred = []
try:
followers = [follower.login for follower in followers_list]
followings = [following.login for following in followings_list]
repos = [repo.name for repo in repos_list]
starred = [star.full_name for star in starred_list]
except Exception as e:
print(f"* Error - {e}")
sys.exit(1)
followers_old = followers
followings_old = followings
repos_old = repos
starred_old = starred
g.close()
time.sleep(GITHUB_CHECK_INTERVAL)
alive_counter = 0
email_sent = False
# main loop
while True:
try:
g = Github(auth=auth)
g_user = g.get_user(user)
user_name = g_user.name
location = g_user.location
bio = g_user.bio
company = g_user.company
email = g_user.email
blog = g_user.blog
account_updated_date = g_user.updated_at
if account_updated_date:
account_updated_date_ts = convert_utc_str_to_tz_datetime(str(account_updated_date), LOCAL_TIMEZONE, 1).timestamp()
followers_count = g_user.followers
followings_count = g_user.following
repos_count = g_user.public_repos
if track_repos_changes:
repos_list = g_user.get_repos()
starred_list = g_user.get_starred()
starred_count = starred_list.totalCount
events = g_user.get_events()
email_sent = False