Retrieving Flickr photo views using shell scripting

From Christiaan008 Wiki
Jump to: navigation, search
#The purpose of this script is to retrieve the amount of views for your Flickr photos.

#Your Flickr API key

#Your Flickr user ID

#Format for today's date
today=$(date +"%m-%d-%Y")

#Format for date in filename
filedate=$(date +"%y%m%d_flickr_stats.txt")
filedateyesterday=$(date --date="1 day ago" +"%y%m%d_flickr_stats.txt")

#If you run as an automated cron job this helps to store files

#Get all the IDs of the Flickr photos for certain user using the Flickr API
#Only grep the ID numbers
ids=$(curl -s ""$KEY"&user_id="$user"&per_page=500&format=rest" | grep -o -P '(?<=photo id=").*(?=" owner=)')

#Read the output from variable ids in idsarray, remove all the whitespaces in the ids variable
read -r -a idsarray <<< $ids

#Iterate through the array and for every entry do the following
for id in "${idsarray[@]}"
	#Request the information of the photo using the photo's ID
	info=$(curl -s ""$KEY"&photo_id="$id"&format=rest")

	#From the ouput of the API request only take the values for title and views
	title=$(echo $info | grep -o -P '(?<=<title>).*(?=</title>)')
	views=$(echo $info | grep -o -P '(?<=views=").*(?=" media)')

	echo "Photo $title has $views views"

	#Get the views for this photo ID from yesterday
	photoviewsyesterday=$(cat $path$filedateyesterday | grep "$id" | cut -d '|' -f 4)

	#Calculate the difference between todays and yesterdays views for this photo ID
	photoviewsdifference=`expr $views - $photoviewsyesterday`

	#Write the output to the file
	echo "$today|$id|$title|$views|$photoviewsdifference">> $path$filedate

	#Add the current views to the total views
	totalviews=`expr $totalviews + $views`

#Get the total views from yesterday
totalviewsyesterday=$(cat "$path"flickr_total_views.txt | grep "$(date --date="1 day ago" +"%m-%d-%Y")" | cut -d '|' -f 2)

#Calculate the difference betweeen todays and yesterdays total views
difference=`expr $totalviews - $totalviewsyesterday`

#Write the output to the file
echo "$today|$totalviews|$difference" >> "$path"flickr_total_views.txt