forked from UtkarshVerma/i3blocklets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmail
executable file
·58 lines (48 loc) · 1.64 KB
/
gmail
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
#!/bin/bash
#----------------------------------------------------------------------------------------------------
# Scipt for fetching the unread mail count of Gmail.
# Uses OAuth2 for authentication.
# Requires jq - https://stedolan.github.io/jq
#----------------------------------------------------------------------------------------------------
# Exit the script if there's no internet.
ping -c 1 8.8.8.8 > /dev/null 2>&1 || exit 33
# Path to config file.
configFile="$HOME/$BLOCK_INSTANCE"
# Exit script if no config file found.
if [[ ! -f "$configFile" ]]; then
echo "$configFile: No such file or directory";
exit 33;
fi
# Mouse actions for the block.
case $BLOCK_BUTTON in
1) xdg-open https://mail.google.com > /dev/null 2>&1 ;;
esac
# Source variables from config file.
source $configFile
eval tokenFile=$tokenFile
# Google API variables.
refreshToken=$(jq '.refresh_token' "$tokenFile" | tr -d \")
# Generates JSON to be POSTed.
generateJSON() {
cat << EOF
{
"client_id":"$clientID",
"client_secret":"$clientSecret",
"refresh_token":"$refreshToken",
"grant_type":"refresh_token"
}
EOF
}
# Fetch the new access token.
accessToken=$(curl -s https://www.googleapis.com/oauth2/v4/token \
-H "Content-Type: application/json" \
-d "$(generateJSON)" | jq '.access_token' | tr -d \")
# Update access_token in tokenFile.
tmp=$(mktemp)
jq ".access_token = \"$accessToken\"" "$tokenFile" > "$tmp" && mv "$tmp" "$tokenFile"
# Fetch unread mails count.
count=$(curl -s -H "Authorization: Bearer $accessToken" \
'https://www.googleapis.com/gmail/v1/users/me/labels/INBOX' \
| jq '.messagesUnread')
# Display the count, if non-zero.
[[ $count = "0" ]] || echo $count