By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,326 Members | 2,873 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,326 IT Pros & Developers. It's quick & easy.

Global name is not defined

P: 2
Hello, first of all I want to say that this is new for me and maybe this question/error for others can be ridiculos.

So, I have the script tinfoleak 1.5 and after some obstacles, I have filled up all the information (consumer key/secret and token/token secret) on the tinfoleak.py and tinfoleak.conf files, but when I execute the script I get a error
Expand|Select|Wrap|Line Numbers
  1.  global name 'and here is my number of consumer key, so i can't write' is not defined 
Really i don't understand how can fix that...

The whole code is this
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # License:
  5. # This work is licensed under a Creative Commons Attribution Share-Alike v4.0 License.
  6. # https://creativecommons.org/licenses/by-sa/4.0/
  7.  
  8. """
  9. Tinfoleak - Get detailed info about a Twitter user 
  10.     :author:     Vicente Aguilera Diaz
  11.     :version:     1.5
  12. """
  13.  
  14. import argparse
  15. import tweepy
  16. import sys
  17. import ConfigParser
  18. import datetime
  19. import errno
  20. import os
  21. import urllib2
  22. from PIL import Image, ExifTags, ImageCms
  23. import exifread
  24. import struct
  25. import time
  26. import pyexiv2
  27. from collections import OrderedDict
  28. from operator import itemgetter
  29. import urllib2
  30. from OpenSSL import SSL
  31. from jinja2 import Template, Environment, FileSystemLoader
  32.  
  33.  
  34. # ----------------------------------------------------------------------
  35. def credits(parameters):
  36.     """Show program credits"""
  37.  
  38.     print "+++ " 
  39.     print "+++ " + parameters.program_name + " " + parameters.program_version + " - \"Get detailed information about a Twitter user\""
  40.     print "+++ " + parameters.program_author_name + ". " + parameters.program_author_twitter
  41.     print "+++ " + parameters.program_author_companyname
  42.     print "+++ " + parameters.program_date
  43.     print "+++ " 
  44.     print
  45.  
  46.  
  47. class Configuration():
  48.     """Configuration information"""
  49.     # ----------------------------------------------------------------------
  50.     def __init__(self):
  51.         try:
  52.             # Read tinfoleak configuration file ("tinfoleak.conf")
  53.             config = ConfigParser.RawConfigParser()
  54.             config.read('tinfoleak.conf')
  55.             self.color = config.get('colors', 'INFO')
  56.             self.color_hdr = config.get('colors', 'HEADER')
  57.             self.color_fun = config.get('colors', 'FUNCTION')
  58.  
  59.             CONSUMER_KEY = ('Twitter OAuth', 'CONSUMER_KEY')
  60.             CONSUMER_SECRET = ('Twitter OAuth', 'CONSUMER_SECRET')
  61.             ACCESS_TOKEN = ('Twitter OAuth', 'ACCESS_TOKEN')
  62.             ACCESS_TOKEN_SECRET = ('Twitter OAuth', 'ACCESS_TOKEN_SECRET') 
  63.  
  64.             # User authentication
  65.             auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
  66.             auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
  67.  
  68.             # Tweepy (a Python library for accessing the Twitter API)
  69.  
  70.  
  71.             # Tweepy (a Python library for accessing the Twitter API)
  72.             self.api = tweepy.API(True)
  73.  
  74.         except Exception, e:
  75.             show_error(e)
  76.             sys.exit(1)
  77.  
  78.  
  79.  
  80. # --------------------------------------------------------------------------
  81. class User:
  82.     """Information about a Twitter user"""
  83.     screen_name = ""
  84.     name = ""
  85.     id = ""
  86.     created_at = ""
  87.     followers_count = ""
  88.     statuses_count = ""
  89.     location = ""
  90.     geo_enabled = ""
  91.     description = ""
  92.     expanded_description = ""
  93.     url = ""
  94.     expanded_url = ""
  95.     profile_image_url = ""
  96.     profile_banner_url = ""
  97.     tweets_average = ""
  98.     meta = ""
  99.     friend_source = ""
  100.     friend_target = ""
  101.     friend_source_followed_by_target = ""
  102.     friend_target_followed_by_source = ""
  103.     friend_source_following_target = ""
  104.     friend_target_following_source = ""
  105.     friend_source_can_dm_target = ""
  106.     friend_target_can_dm_source = ""
  107.  
  108.  
  109.  
  110.  
  111.     # ----------------------------------------------------------------------
  112.     def set_user_information(self, api):
  113.         try:
  114.             self.screen_name = api.screen_name
  115.             self.name = api.name
  116.             self.id = api.id
  117.             self.created_at = api.created_at
  118.             self.followers_count = api.followers_count
  119.             self.friends_count = api.friends_count
  120.             self.statuses_count = api.statuses_count
  121.             self.location = api.location
  122.             self.geo_enabled = api.geo_enabled
  123.             self.time_zone = api.time_zone
  124.  
  125.             td = datetime.datetime.today() - self.created_at
  126.             self.tweets_average = round(float(self.statuses_count / (td.days * 1.0)),2) 
  127.  
  128.             self.url = api.url
  129.  
  130.             if len(api.entities) > 1:
  131.                 if api.entities['url']['urls']:
  132.                     self.expanded_url = api.entities['url']['urls'][0]['expanded_url']
  133.                 else:
  134.                     self.expanded_url = ""
  135.             else:
  136.                 self.expanded_url = ""
  137.  
  138.             try:
  139.                 self.description = api.description 
  140.                 if api.entities['description']['urls']:
  141.                     tmp_expanded_description = api.description
  142.                     url = api.entities['description']['urls'][0]['url']
  143.                     expanded_url = api.entities['description']['urls'][0]['expanded_url']
  144.                     self.expanded_description = tmp_expanded_description.replace(url, expanded_url)
  145.                 else:
  146.                     self.expanded_description= ""
  147.             except:
  148.                 self.expanded_description= ""        
  149.  
  150.             self.profile_image_url = str(api.profile_image_url).replace("_normal","")
  151.  
  152.             try:
  153.                 if api.profile_banner_url:
  154.                     self.profile_banner_url = str(api.profile_banner_url).replace("_normal","")
  155.                 else:
  156.                     self.profile_banner_url = ""
  157.             except:
  158.                 self.profile_banner_url = ""
  159.  
  160.         except Exception, e:
  161.             show_error(e)
  162.             sys.exit(1)
  163.  
  164.     # ----------------------------------------------------------------------
  165.     def show_user_information(self,info_color, header_color, fun_color):
  166.         try:
  167.             string = "USER INFORMATION "
  168.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  169.  
  170.             print_header(header_color, "General Information")
  171.             print_info(info_color, "Screen Name:\t\t\t" + self.screen_name)
  172.             print_info(info_color, "User Name:\t\t\t" + self.name)
  173.             print_info(info_color, "Twitter Unique ID:\t\t" + str(self.id))
  174.             print_info(info_color, "Account created at:\t\t" + self.created_at.strftime('%m/%d/%Y'))
  175.             print_info(info_color, "Followers:\t\t\t" + '{:,}'.format(self.followers_count))
  176.             print_info(info_color, "Friends:\t\t\t" + '{:,}'.format(self.friends_count))
  177.             print_info(info_color, "Tweets:\t\t\t\t" + '{:,}'.format(self.statuses_count))
  178.             try:
  179.                 print_info(info_color, "Location:\t\t\t" + str(self.location))
  180.             except:
  181.                 print_info(info_color, "Location:")
  182.             print_info(info_color, "Time zone:\t\t\t" + str(self.time_zone))
  183.             print_info(info_color, "Geo enabled:\t\t\t" + str(self.geo_enabled))
  184.  
  185.             print_info(info_color, "URL:\t\t\t\t" + str(self.url))
  186.             if self.expanded_url:
  187.                 print_info(info_color, "Expanded URL:\t\t\t" + str(self.expanded_url))
  188.  
  189.             print_info(info_color, "Description:\t\t\t" + str(self.description.encode('utf-8')).replace("\n"," "))
  190.             if self.expanded_description:
  191.                 print_info(info_color, "Expanded Description:\t\t" + str(self.expanded_description.encode('utf-8')).replace("\n"," "))
  192.  
  193.             print_info(info_color, "Profile image URL:\t\t" + str(self.profile_image_url))
  194.  
  195.             print_info(info_color, "Tweets average:\t\t\t" + str(self.tweets_average) + " tweets/day")
  196.  
  197.         except Exception, e:
  198.             show_error(e)
  199.             sys.exit(1)
  200.  
  201.  
  202. class Sources:
  203.     """Get tools used to publish tweets"""
  204.     # source = [source1, source2, ... ]
  205.     # sources_firstdate = {source1: first_date1, source2: first_date2, ... ]
  206.     # sources_lastdate = {source1: last_date1, source2: last_date2, ... ]
  207.     # sources_count = {source1: tweets_number1, source2: tweets_number2, ... ]
  208.     sources = []
  209.     sources_firstdate = {}
  210.     sources_lastdate = {}
  211.     sources_count = {}
  212.     sources_total_count = 0
  213.     sources_percent = {}
  214.  
  215.     # ----------------------------------------------------------------------
  216.     def set_sources_information(self, tweet):
  217.         try:
  218.             add = 1
  219.             for index, item in enumerate(self.sources):
  220.                 if tweet.source == item[0]:
  221.                     add = 0
  222.                     self.sources_count[tweet.source] += 1
  223.                     self.sources_total_count += 1
  224.                     if tweet.created_at < self.sources_firstdate[tweet.source]:
  225.                         self.sources_firstdate[tweet.source] = tweet.created_at
  226.                     if tweet.created_at > self.sources_lastdate[tweet.source]:
  227.                         self.sources_lastdate[tweet.source] = tweet.created_at
  228.  
  229.             if add:
  230.                 self.sources.append([tweet.source])
  231.                 self.sources_count[tweet.source] = 1
  232.                 self.sources_firstdate[tweet.source] = tweet.created_at
  233.                 self.sources_lastdate[tweet.source] = tweet.created_at
  234.                 self.sources_total_count += 1
  235.  
  236.         except Exception, e:
  237.             show_error(e)
  238.             sys.exit(1)
  239.  
  240.  
  241.     # ----------------------------------------------------------------------
  242.     def show_sources_information(self, info_color, header_color, fun_color):
  243.         try:
  244.             string = "CLIENT APPLICATIONS "
  245.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  246.  
  247.             print_header(header_color, "Sources\t\t\t\t\t\tUses\t%\tFirst Use\tLast Use")
  248.  
  249.             for s in self.sources:
  250.                 value = get_string_with_padding(s[0], 40)
  251.                 self.sources_percent[s[0]] = round((self.sources_count[s[0]] * 100.0) / self.sources_total_count, 1) 
  252.                 print_info(info_color, value + "\t" + str(self.sources_count[s[0]]) + "\t" + str(self.sources_percent[s[0]]) + "%\t" + str(self.sources_firstdate[s[0]].strftime('%m/%d/%Y')) + "\t" + str(self.sources_lastdate[s[0]].strftime('%m/%d/%Y')))
  253.  
  254.             print_info(info_color, "\n\t" + str(len(self.sources)) + " results.")        
  255.  
  256.         except Exception, e:
  257.             show_error(e)
  258.             sys.exit(1)
  259.  
  260.  
  261.  
  262. class Geolocation:
  263.     """Get geolocation info included in tweets"""
  264.     toplocations = {}
  265.     toplocationsstartdate = {}
  266.     toplocatonsenddate = {}
  267.     geoimg = 0 # tweets with images and geolocation (parameter: -p 0)
  268.     toplocations = {} # store the user most visited locations 
  269.     toplocationsdatetime = {} # store date and time of the user most visited locations
  270.     toplocationsstartdate = {} # store initial date of the user most visited locations
  271.     toplocationsenddate = {} # store final date of the user most visited locations
  272.     toplocationsstarttime = {} # store initial time of the user most visited locations
  273.     toplocationsdays = {} # store week day of the user most visited locations
  274.     toplocationsendtime = {} # store final time of the user most visited locations
  275.     toplocationsdaysmo = {} # store week day of the user most visited locations
  276.     toplocationsdaystu = {} # store week day of the user most visited locations
  277.     toplocationsdayswe = {} # store week day of the user most visited locations
  278.     toplocationsdaysth = {} # store week day of the user most visited locations
  279.     toplocationsdaysfr = {} # store week day of the user most visited locations
  280.     toplocationsdayssa = {} # store week day of the user most visited locations
  281.     toplocationsdayssu = {} # store week day of the user most visited locations
  282.     geo_info = []
  283.     toplocations_tweets = {}
  284.     toplocations_tweets_route = {}
  285.  
  286.     visited_locations = []
  287.     visited_locations_startdate = []
  288.     visited_locations_enddate = []
  289.     visited_locations_starttime = []
  290.     visited_locations_endtime = []
  291.     visited_locations_days = []
  292.  
  293.     kml_info = []
  294.     media_info = {}
  295.     toploc = []
  296.  
  297.  
  298.     # ----------------------------------------------------------------------
  299.     def set_geolocation_information(self, tweet):
  300.         try:
  301.  
  302.             add = 0
  303.             splace = ""
  304.             sgeo = ""
  305.  
  306.             if tweet.place:
  307.                 splace = tweet.place.name.encode('utf-8')
  308.                 add = 1
  309.             if tweet.geo:
  310.                 sgeo = tweet.geo['coordinates']
  311.                 add = 1
  312.                 lat = str(sgeo[0])[:str(sgeo[0]).find(".")+4]
  313.                 lon = str(sgeo[1])[:str(sgeo[1]).find(".")+4]    
  314.                 location = "[" + lat + ", " + lon + "]"
  315.                 for i in range (1, 20-len(location)):
  316.                     location += " "
  317.                 location = location + "\t" + splace
  318.  
  319.                 if location in self.toplocations.keys():
  320.                     self.toplocations[location] += 1
  321.                     if tweet.created_at < self.toplocationsstartdate[location]:
  322.                         self.toplocationsstartdate[location] = tweet.created_at 
  323.                     if tweet.created_at > self.toplocationsenddate[location]:
  324.                         self.toplocationsenddate[location] = tweet.created_at
  325.                     if tweet.created_at.time() < self.toplocationsstarttime[location]:
  326.                         self.toplocationsstarttime[location] = tweet.created_at.time() 
  327.                     if tweet.created_at.time() > self.toplocationsendtime[location]:
  328.                         self.toplocationsendtime[location] = tweet.created_at.time() 
  329.                 else:
  330.                     self.toplocations[location] = 1
  331.                     self.toplocationsstartdate[location] = tweet.created_at 
  332.                     self.toplocationsenddate[location] = tweet.created_at 
  333.                     self.toplocationsstarttime[location] = tweet.created_at.time()
  334.                     self.toplocationsendtime[location] = tweet.created_at.time()
  335.                     self.toplocationsdaysmo[location] = 0
  336.                     self.toplocationsdaystu[location] = 0
  337.                     self.toplocationsdayswe[location] = 0
  338.                     self.toplocationsdaysth[location] = 0
  339.                     self.toplocationsdaysfr[location] = 0
  340.                     self.toplocationsdayssa[location] = 0
  341.                     self.toplocationsdayssu[location] = 0
  342.                 if tweet.created_at.weekday() == 0: # Monday
  343.                         self.toplocationsdaysmo[location] += 1
  344.                 elif tweet.created_at.weekday() == 1:   # Tuesday
  345.                         self.toplocationsdaystu[location] += 1
  346.                 elif tweet.created_at.weekday() == 2: # Wednesday
  347.                         self.toplocationsdayswe[location] += 1
  348.                 elif tweet.created_at.weekday() == 3: # Thursday
  349.                         self.toplocationsdaysth[location] += 1
  350.                 elif tweet.created_at.weekday() == 4: # Friday
  351.                         self.toplocationsdaysfr[location] += 1
  352.                 elif tweet.created_at.weekday() == 5: # Saturday
  353.                         self.toplocationsdayssa[location] += 1
  354.                 elif tweet.created_at.weekday() == 6: # Sunday
  355.                         self.toplocationsdayssu[location] += 1                    
  356.  
  357.             place = splace.decode('utf-8')
  358.             if splace in self.toplocations_tweets:
  359.                 self.toplocations_tweets[place] += 1    
  360.             else:
  361.                 self.toplocations_tweets[place] = 1
  362.  
  363.             sinfo = ""
  364.             media_url = ""
  365.  
  366.             if tweet.entities.has_key('media') :
  367.                 medias = tweet.entities['media']
  368.                 for m in medias :
  369.                     media_url = m['media_url']
  370.  
  371.             if add:
  372.                 place = splace.decode('utf-8')
  373.                 sinfo = media_url + splace.decode('utf-8') + " " + str(sgeo).decode('utf-8')
  374.                 self.geo_info.append([media_url, place, str(sgeo).decode('utf-8'), str(tweet.created_at.strftime('%m/%d/%Y')), str(tweet.created_at.time()), str(tweet.id)])
  375.  
  376.                 if len(self.visited_locations)>0 and place in self.visited_locations[len(self.visited_locations)-1][0]: 
  377.                     self.visited_locations[len(self.visited_locations)-1][1] = tweet.created_at 
  378.                     self.visited_locations[len(self.visited_locations)-1][2] = tweet.created_at.time() 
  379.                     delta = self.visited_locations[len(self.visited_locations)-1][3] - tweet.created_at 
  380.                     self.visited_locations[len(self.visited_locations)-1][5] = delta.days+1 
  381.                     self.visited_locations[len(self.visited_locations)-1][6] = self.toplocations_tweets[place]
  382.  
  383.                 else:
  384.                     # [place, date (since), time (since), date (until), time (until), days, tweets] 
  385.                     self.visited_locations.append([place, tweet.created_at,  tweet.created_at.time(), tweet.created_at, tweet.created_at.time(), 1, 1])
  386.  
  387.             else:
  388.                 sinfo = ""        
  389.  
  390.  
  391.         except Exception, e:
  392.             show_error(e)
  393.             sys.exit(1)
  394.  
  395.     # ----------------------------------------------------------------------
  396.     def show_geolocation_information(self, info_color, header_color, fun_color):
  397.         try:
  398.             string = "GEOLOCATION "
  399.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  400.  
  401.             # Show tweet coordinates
  402.             print_header(header_color, "Date\t\tTime\t\tCoordinates\t\t\tMedia\tLocation")
  403.             for g in self.geo_info:
  404.                 coord = get_string_with_padding(g[2], 30)
  405.                 media = ""
  406.                 if len(g[0]):
  407.                     if str(g[0]).find(".mp4") >= 0:
  408.                         media = "Video"
  409.                     else:
  410.                         media = "Photo"
  411.                     self.media_info[g[0]] = media
  412.  
  413.                 print_info(info_color, g[3] + "\t" + g[4] + "\t" + coord + "\t" + media + "\t" + g[1])
  414.  
  415.             print_info(info_color, "\n\t" + str(len(self.geo_info)) + " results.")        
  416.  
  417.             # Show user route
  418.             print_header(header_color, "User route\n\tTweets\t\tDate-Time (since)\tDate-Time (until)\tDays\tLocation")
  419.  
  420.             for l in self.visited_locations: 
  421.                 splace = l[0]
  422.                 value = get_string_with_padding(str(l[6]) + " [" + str(self.toplocations_tweets[splace]) + "]", 12)
  423.  
  424.                 print_info(info_color,  value + "\t" + str(l[1].strftime('%m/%d/%Y')) + " " + str(l[2].strftime('%H:%M:%S')) + "\t" + str(l[3].strftime('%m/%d/%Y')) + " " + str(l[4].strftime('%H:%M:%S')) + "\t" + str(l[5]) + "\t" + splace)
  425.                 self.toplocations_tweets_route[splace] = 0
  426.             print_info(info_color, "\n\t" + str(len(self.visited_locations)) + " results.")        
  427.  
  428.         except Exception, e:
  429.             show_error(e)
  430.             sys.exit(1)
  431.  
  432.  
  433.     # ----------------------------------------------------------------------
  434.     def show_top_locations(self, info_color, header_color, top, fun_color):
  435.         try:
  436.             string = "TOP LOCATIONS "
  437.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  438.  
  439.             sort_loc = OrderedDict(sorted(self.toplocations.items(), key=itemgetter(1), reverse=True))
  440.             loc = sort_loc.items()
  441.  
  442.             print_header(header_color, "Locations with more tweets\n\tTweets\tDate\t\t\tTime\t\t\tWeek Days\t\tCoordinates\t\tPlace")
  443.  
  444.             n = 1
  445.             for place, value in loc:
  446.                 startdate = self.toplocationsstartdate[place]
  447.                 enddate = self.toplocationsenddate[place]
  448.                 starttime = self.toplocationsstarttime[place]
  449.                 endtime = self.toplocationsendtime[place]
  450.  
  451.                 weekdays = "Mo Tu We Th Fr Sa Su"
  452.                 favorite = 1
  453.  
  454.                 mo = self.toplocationsdaysmo[place]
  455.                 tu = self.toplocationsdaystu[place]
  456.                 we = self.toplocationsdayswe[place]
  457.                 th = self.toplocationsdaysth[place]
  458.                 fr = self.toplocationsdaysfr[place]
  459.                 sa = self.toplocationsdayssa[place]
  460.                 su = self.toplocationsdayssu[place]
  461.  
  462.                 week = [mo, tu, we, th, fr, sa, su]
  463.                 week_sort = sorted(week, reverse = True)
  464.                 maxday = week_sort [0]
  465.  
  466.                 if week_sort[0] > 0 and week_sort[1] == 0:
  467.                     favorite = 0
  468.                 else:
  469.                     while week_sort[0] == maxday:
  470.                         del week_sort[0]
  471.                     if len(week_sort) > 0:
  472.                         if week_sort[0] == 0:
  473.                             favorite = 0
  474.  
  475.                 cad = chr(27) + "[1;31m" + "DD" + chr(27) + info_color 
  476.                 day = []
  477.                 fav = 0
  478.                 mo_day = "Mo"
  479.                 tu_day = "Tu"
  480.                 we_day = "We"
  481.                 th_day = "Th"
  482.                 fr_day = "Fr"
  483.                 sa_day = "Sa"
  484.                 su_day = "Su" 
  485.  
  486.                 if mo == 0:
  487.                         weekdays = weekdays.replace("Mo", "__")
  488.                         mo_day = ""
  489.                 else:
  490.                         if mo == maxday and favorite:
  491.                             weekdays = weekdays.replace("Mo", cad.replace("DD","Mo"))
  492.                             fav = "1"
  493.                             day.append("Mo")
  494.                 if tu == 0:
  495.                         weekdays = weekdays.replace("Tu", "__")
  496.                         tu_day = ""
  497.                 else:
  498.                         if tu == maxday and favorite:
  499.                             weekdays = weekdays.replace("Tu", cad.replace("DD","Tu"))
  500.                             fav = "2"                            
  501.                             day.append("Tu")
  502.                 if we == 0:
  503.                         weekdays = weekdays.replace("We", "__")
  504.                         we_day = ""
  505.                 else:
  506.                         if we == maxday and favorite:
  507.                             weekdays = weekdays.replace("We", cad.replace("DD","We"))
  508.                             fav = "3"
  509.                             day.append("We")
  510.                 if th == 0:
  511.                         weekdays = weekdays.replace("Th", "__")
  512.                         th_day = ""
  513.                 else:
  514.                         if th == maxday and favorite:
  515.                             weekdays = weekdays.replace("Th", cad.replace("DD","Th"))
  516.                             fav = "4"
  517.                             day.append("Th")
  518.                 if fr == 0:
  519.                         weekdays = weekdays.replace("Fr", "__")
  520.                         fr_day = ""
  521.                 else:
  522.                         if fr == maxday and favorite:
  523.                             weekdays = weekdays.replace("Fr", cad.replace("DD","Fr"))
  524.                             fav = "5"
  525.                             day.append("Fr")
  526.                 if sa == 0:
  527.                         weekdays = weekdays.replace("Sa", "__")
  528.                         sa_day = ""
  529.                 else:
  530.                         if sa == maxday and favorite:
  531.                             weekdays = weekdays.replace("Sa", cad.replace("DD","Sa"))
  532.                             fav = "6"
  533.                             day.append("Sa")
  534.                 if su == 0:
  535.                         weekdays = weekdays.replace("Su", "__")
  536.                         su_day = ""
  537.                 else:
  538.                         if su == maxday and favorite:
  539.                             weekdays = weekdays.replace("Su", cad.replace("DD","Su"))
  540.                             fav = "7"
  541.                             day.append("Su")
  542.  
  543.                 coordinates = place[1:place.find("]")]
  544.                 location = place[20:len(place)]
  545.                 print_info(info_color, str(value) + "\t" + str(startdate.strftime('%m/%d/%Y')) + "-" + str(enddate.strftime('%m/%d/%Y')) + "\t" + str(starttime) + "-" + str(endtime) + "\t" + weekdays + "\t" + place)
  546.                 self.toploc.append([str(value), str(startdate.strftime('%m/%d/%Y')), str(enddate.strftime('%m/%d/%Y')), str(starttime), str(endtime), mo_day, tu_day, we_day, th_day, fr_day, sa_day, su_day, coordinates, location, fav, day])
  547.  
  548.                 if  n == int(top):
  549.                     break
  550.                 n += 1
  551.  
  552.             print_info(info_color, "\n\t" + str(n-1) + " results.")        
  553.  
  554.         except Exception, e:
  555.             show_error(e)
  556.             sys.exit(1)
  557.  
  558.  
  559.  
  560.     # ----------------------------------------------------------------------
  561.     def set_geofile_information(self, tweet, user):
  562.         try:
  563.             tweet_geo = 0
  564.             place = ""
  565.             geo = ""
  566.  
  567.             # Get place from tweet
  568.             if tweet.place:
  569.                 place = tweet.place.name.encode('utf-8')
  570.  
  571.             # Get coordinates from tweet
  572.             if tweet.geo:
  573.                 geo = tweet.geo['coordinates']
  574.                 tweet_geo = 1
  575.  
  576.             media_url = []
  577.             # Get media content from tweet
  578.             if tweet.entities.has_key('media') :
  579.                 medias = tweet.entities['media']
  580.                 for m in medias :
  581.                     media_url.append(m['media_url'])
  582.  
  583.             photo = ""
  584.             if tweet_geo:
  585.                 # Tweet with coordinates
  586.                 content = "<table width=\"100%\"><tr><td width=\"48\"><img src=\""+user.profile_image_url.encode('utf-8') +"\"></td><td bgcolor=\"#cde4f3\"><b>" + user.name.encode('utf-8') + "</b> @" + user.screen_name.encode('utf-8') + "<br>" + tweet.text.encode('utf-8') + "</td></tr></table>"
  587.  
  588.                 for media in media_url:
  589.                     photo = " [Media] "
  590.                     content += "<table width=\"100%\"><tr><td><img src=\"" + str(media) + "\"></td></tr></table>"
  591.  
  592.                 date = tweet.created_at.strftime('%m/%d/%Y')
  593.                 time = tweet.created_at.time()
  594.                 self.kml_info.append([geo, content, photo, place, date, time])
  595.  
  596.         except Exception, e:
  597.             show_error(e)
  598.             sys.exit(1)
  599.  
  600.  
  601.     # ----------------------------------------------------------------------
  602.     def generates_geofile(self, geofile, parameters):
  603.         kml_file_content = ""
  604.         kml_file_header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://earth.google.com/kml/2.2\">\n<Folder>\n"
  605.         kml_file_body = ""
  606.         kml_file_foot = "</Folder>\n</kml>"
  607.         header = ""
  608.         content = ""
  609.  
  610.         try:
  611.             f = open(geofile, "w")
  612.  
  613.             header = "<table bgcolor=\"#000000\" width=\"100%\"><tr><td><font color=\"white\"><b>" + parameters.program_name + " " + parameters.program_version + "</b></font><td align=\"right\"><font color=\"white\">" + parameters.program_author_twitter + "</font></td></tr></table>"
  614.  
  615.             for info in self.kml_info:
  616.                 #INFO: [coordinates, content, photo, place, date, time]
  617.                 coord = str(info[0])
  618.                 lat = coord[1:coord.find(",")]
  619.                 lon = coord[coord.find(",")+2:coord.find("]")]
  620.  
  621.                 cdata = ""
  622.                 cdata = "\t\t<![CDATA[" + header + str(info[1]) + "]]>\n"
  623.                 snippet = ""
  624.  
  625.                 # Place + [Photo]
  626.                 snippet = info[3] + " " + str(info[2])
  627.                 kml_file_body += "\t<Placemark>\n"
  628.                 # Date + Time
  629.                 kml_file_body += "\t\t<name>" + str(info[4]) + " - " + str(info[5]) + "</name>\n"
  630.                 kml_file_body += "\t\t<Snippet>" + snippet + "</Snippet>\n"
  631.                 kml_file_body += "\t\t<description>\n" + cdata + "\t\t</description>\n"                
  632.                 kml_file_body += "\t\t<Point>\n"
  633.                 kml_file_body += "\t\t\t<coordinates>" + lon + "," + lat + "</coordinates>\n"
  634.                 kml_file_body += "\t\t</Point>\n"
  635.                 kml_file_body += "\t</Placemark>\n"
  636.  
  637.             kml_file_content = kml_file_header + kml_file_body + kml_file_foot
  638.             f.write(kml_file_content)
  639.             f.close()            
  640.  
  641.         except Exception, e:
  642.             show_error(e)
  643.             sys.exit(1)
  644.  
  645.  
  646.  
  647. class Hashtags:
  648.     """Get hashtags included in tweets"""
  649.     # hashtag = [hashtag1, hashtag2, ... ]
  650.     # hashtags_firstdate = {hashtag1: first_date1, hashtag2: first_date2, ... ]
  651.     # hashtags_lastdate = {hashtag1: last_date1, hashtag2: last_date2, ... ]
  652.     # hashtags_count = {hashtag1: tweets_number1, hashtag2: tweets_number2, ... ]
  653.     hashtags = []
  654.     hashtags_firstdate = {}
  655.     hashtags_lastdate = {}
  656.     hashtags_count = {}
  657.     hashtags_tweet = []
  658.     hashtags_rt = {}
  659.     hashtags_fv = {}
  660.     hashtags_results1 = 0
  661.     hashtags_results2 = 0
  662.     hashtags_results3 = 0    
  663.     hashtags_top = {}
  664.  
  665.     # ----------------------------------------------------------------------
  666.     def set_hashtags_information(self, tweet):
  667.         try:
  668.  
  669.             tmp = ""
  670.             for i in tweet.entities['hashtags']:
  671.                 if i['text']:
  672.                     tmp = tmp + "#" + i['text'] + " "
  673.  
  674.                 if i['text'].upper() in (name.upper() for name in self.hashtags_rt):
  675.                     self.hashtags_rt[i['text'].upper()] += tweet.retweet_count                        
  676.                 else:
  677.                     self.hashtags_rt[i['text'].upper()] = tweet.retweet_count
  678.  
  679.                 if i['text'].upper() in (name.upper() for name in self.hashtags_fv):
  680.                     self.hashtags_fv[i['text'].upper()] += tweet.favorite_count                        
  681.                 else:
  682.                     self.hashtags_fv[i['text'].upper()] = tweet.favorite_count
  683.  
  684.             if len(tmp):
  685.                 self.hashtags_tweet.append([str(tweet.created_at.strftime('%m/%d/%Y')), str(tweet.created_at.time()), str(tweet.retweet_count), str(tweet.favorite_count), tmp, str(tweet.id)])
  686.                 self.hashtags_results1 += 1
  687.  
  688.             for h in tweet.entities['hashtags']:
  689.                 orig = h['text']
  690.                 upper = h['text'].upper()
  691.  
  692.                 if upper in (name.upper() for name in self.hashtags):
  693.                     self.hashtags_count[upper] += 1
  694.                     if tweet.created_at < self.hashtags_firstdate[upper]:
  695.                         self.hashtags_firstdate[upper] = tweet.created_at
  696.                     if tweet.created_at > self.hashtags_lastdate[upper]:
  697.                         self.hashtags_lastdate[upper] = tweet.created_at
  698.  
  699.                 else:
  700.                     self.hashtags.append(orig)
  701.                     self.hashtags_count[upper] = 1
  702.                     self.hashtags_firstdate[upper] = tweet.created_at
  703.                     self.hashtags_lastdate[upper] = tweet.created_at
  704.                     self.hashtags_results2 += 1
  705.  
  706.         except Exception, e:
  707.             show_error(e)
  708.             sys.exit(1)
  709.  
  710.     # ----------------------------------------------------------------------
  711.     def show_hashtags_information(self, info_color, header_color, fun_color):
  712.         try:
  713.             string = "HASHTAGS "
  714.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  715.  
  716.             print_info(info_color, "\n\n\tHASHTAGS IN TWEEETS")
  717.  
  718.             # Show hashtags in tweets
  719.             print_header(header_color, "Date\t\tTime\t\tRTs\tFAVs\tHashtags")
  720.             for h in self.hashtags_tweet:
  721.                 tmp = h[0] + "\t" + h[1] + "\t" + h[2] + "\t" + h[3] + "\t" + h[4]
  722.                 print_info(info_color, tmp)
  723.  
  724.             print_info(info_color, "\n\t" + str(len(self.hashtags_tweet)) + " results.")        
  725.  
  726.             print_info(info_color, "\n\n\tHASHTAG DETAIL")
  727.             # Show summary for every hashtag
  728.             print_header(header_color, "Date (since)\tDate (until)\tRTs\tFAVs\tCount\tHashtag")
  729.             for h in self.hashtags:                
  730.                 print_info(info_color, str(self.hashtags_firstdate[h.upper()].strftime('%m/%d/%Y')) + "\t" + str(self.hashtags_lastdate[h.upper()].strftime('%m/%d/%Y')) + "\t" + str(self.hashtags_rt[h.upper()]) + "\t" + str(self.hashtags_fv[h.upper()]) + "\t" + str(self.hashtags_count[h.upper()]) + "\t" + "#" + h)
  731.                 self.hashtags_top[h] = self.hashtags_count[h.upper()]
  732.  
  733.             sort_has = OrderedDict(sorted(self.hashtags_top.items(), key=itemgetter(1), reverse=True))
  734.             self.hashtags_top = sort_has.items()[0:10]
  735.             self.hashtags_results3 = len (self.hashtags_top)
  736.  
  737.             print_info(info_color, "\n\t" + str(len(self.hashtags)) + " results.")
  738.  
  739.             print_info(info_color, "\n\n\tTOP HASHTAGS")
  740.             # Show top 10 hashtags
  741.             print_header(header_color, "Date (since)\tDate (until)\tRTs\tFAVs\tCount\tHashtag")
  742.             for h in self.hashtags_top:                
  743.                 print_info(info_color, str(self.hashtags_firstdate[h[0].upper()].strftime('%m/%d/%Y')) + "\t" + str(self.hashtags_lastdate[h[0].upper()].strftime('%m/%d/%Y')) + "\t" + str(self.hashtags_rt[h[0].upper()]) + "\t" + str(self.hashtags_fv[h[0].upper()]) + "\t" + str(self.hashtags_count[h[0].upper()]) + "\t" + "#" + h[0])
  744.  
  745.             print_info(info_color, "\n\t" + str(len(self.hashtags_top)) + " results.")
  746.  
  747.  
  748.         except Exception, e:
  749.             show_error(e)
  750.             sys.exit(1)
  751.  
  752.  
  753. class Mentions:
  754.     """ Get mentions included in tweets """
  755.     # mention = [mention1, mention2, ... ]
  756.     # mentions_count = {mention1: tweets_number1, mention2: tweets_number2, ... ]
  757.     # mentions_firstdate = {mention1: first_date1, mention2: first_date2, ... ]
  758.     # mentions_lastdate = {mention1: last_date1, mention2: last_date2, ... ]
  759.     mentions = []
  760.     mentions_firstdate = {}
  761.     mentions_lastdate = {}
  762.     mentions_count = {}
  763.     mentions_tweet = []
  764.     mentions_rt = {}
  765.     mentions_fv = {}
  766.     mentions_results3 = 0
  767.     mentions_top = {}
  768.  
  769.     # ----------------------------------------------------------------------
  770.     def set_mentions_information(self, tweet):
  771.         try:
  772.             tmp = ""
  773.             for i in tweet.entities['user_mentions']:
  774.                 if i['screen_name'].encode('utf-8'):
  775.                     tmp = tmp + "@" + i['screen_name'].encode('utf-8') + " "
  776.  
  777.                 if i['screen_name'].encode('utf-8').upper() in (name.upper() for name in self.mentions_rt):
  778.                     self.mentions_rt[i['screen_name'].encode('utf-8').upper()] += tweet.retweet_count                        
  779.                 else:
  780.                     self.mentions_rt[i['screen_name'].encode('utf-8').upper()] = tweet.retweet_count
  781.  
  782.                 if i['screen_name'].encode('utf-8').upper() in (name.upper() for name in self.mentions_fv):
  783.                     self.mentions_fv[i['screen_name'].encode('utf-8').upper()] += tweet.favorite_count                        
  784.                 else:
  785.                     self.mentions_fv[i['screen_name'].encode('utf-8').upper()] = tweet.favorite_count
  786.  
  787.             if len(tmp):
  788.                 self.mentions_tweet.append([str(tweet.created_at.strftime('%m/%d/%Y')), str(tweet.created_at.time()), str(tweet.retweet_count), str(tweet.favorite_count), tmp, str(tweet.id)])
  789.  
  790.             for m in tweet.entities['user_mentions']:
  791.                 orig = m['screen_name']
  792.                 upper = m['screen_name'].upper()
  793.                 if upper in (name.upper() for name in self.mentions):
  794.                     self.mentions_count[upper] += 1
  795.                     if tweet.created_at < self.mentions_firstdate[upper]:
  796.                         self.mentions_firstdate[upper] = tweet.created_at
  797.                     if tweet.created_at > self.mentions_lastdate[upper]:
  798.                         self.mentions_lastdate[upper] = tweet.created_at
  799.  
  800.                 else:
  801.                     self.mentions.append(orig)
  802.                     self.mentions_count[upper] = 1
  803.                     self.mentions_firstdate[upper] = tweet.created_at
  804.                     self.mentions_lastdate[upper] = tweet.created_at
  805.  
  806.         except Exception, e:
  807.             show_error(e)
  808.             sys.exit(1)
  809.  
  810.     # ----------------------------------------------------------------------
  811.     def show_mentions_information(self, info_color, header_color, fun_color):
  812.         try:
  813.             string = "USER MENTIONS "
  814.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  815.  
  816.             print_info(info_color, "\n\n\tUSER MENTIONS IN TWEEETS")
  817.             # Show user mentions in tweets
  818.             print_header(header_color, "Date\t\tTime\t\tRTs\tFAVs\tUser Mentions")
  819.             for m in self.mentions_tweet:
  820.                 tmp = m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\t" + m[4]
  821.                 print_info(info_color, tmp)
  822.  
  823.             print_info(info_color, "\n\t" + str(len(self.mentions_tweet)) + " results.")        
  824.  
  825.             print_info(info_color, "\n\n\tUSER MENTION DETAIL")            
  826.             # Show summary for every user mention            
  827.             print_header(header_color, "Date (since)\tDate (until)\tRTs\tFAVs\tCount\tUser Mention")
  828.             for m in self.mentions:
  829.                 print_info(info_color, str(self.mentions_firstdate[m.upper()].strftime('%m/%d/%Y')) + "\t" + str(self.mentions_lastdate[m.upper()].strftime('%m/%d/%Y')) + "\t" + str(self.mentions_rt[m.upper()]) + "\t" + str(self.mentions_fv[m.upper()]) + "\t" + str(self.mentions_count[m.upper()]) + "\t" + "@" + m)
  830.                 self.mentions_top[m] = self.mentions_count[m.upper()]
  831.  
  832.             sort_men = OrderedDict(sorted(self.mentions_top.items(), key=itemgetter(1), reverse=True))
  833.             self.mentions_top = sort_men.items()[0:10]
  834.             self.mentions_results3 = len (self.mentions_top)
  835.  
  836.             print_info(info_color, "\n\t" + str(len(self.mentions)) + " results.")        
  837.  
  838.             print_info(info_color, "\n\n\tTOP MENTIONS")
  839.             # Show top 10 mentions
  840.             print_header(header_color, "Date (since)\tDate (until)\tRTs\tFAVs\tCount\tUser Mention")
  841.             for m in self.mentions_top:                
  842.                 print_info(info_color, str(self.mentions_firstdate[m[0].upper()].strftime('%m/%d/%Y')) + "\t" + str(self.mentions_lastdate[m[0].upper()].strftime('%m/%d/%Y')) + "\t" + str(self.mentions_rt[m[0].upper()]) + "\t" + str(self.mentions_fv[m[0].upper()]) + "\t" + str(self.mentions_count[m[0].upper()]) + "\t" + "@" + m[0])
  843.  
  844.             print_info(info_color, "\n\t" + str(len(self.mentions_top)) + " results.")
  845.  
  846.  
  847.         except Exception, e:
  848.             show_error(e)
  849.             sys.exit(1)
  850.  
  851.  
  852.  
  853. class User_Tweets:
  854.     """ Handle user tweets """
  855.  
  856.     find = "" # Search text in tweets
  857.     tweets_find = [] # [[text, date, time], ...]
  858.  
  859.  
  860.     # ----------------------------------------------------------------------
  861.     def set_find_information(self, find, tweet):
  862.         try:
  863.             self.find = find
  864.  
  865.             if find.lower() in tweet.text.lower(): 
  866.                 self.tweets_find.append([tweet.text, tweet.created_at.strftime('%m/%d/%Y'), tweet.created_at.time(), tweet.id])
  867.  
  868.         except Exception, e:
  869.             show_error(e)
  870.             sys.exit(1)
  871.  
  872.     # ----------------------------------------------------------------------
  873.     def show_find_information(self, info_color, header_color, fun_color):
  874.         try:
  875.             string = "FILTER TWEETS BY TEXT [" + self.find+ "]"
  876.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  877.  
  878.             print_header(header_color, "Date\t\tTime\t\tTweet")
  879.             count = 0
  880.             for tweet in self.tweets_find:
  881.                 print_info(info_color, str(tweet[1]) + "\t" + str(tweet[2]) + "\t" + tweet[0].encode('utf-8')) 
  882.                 count +=1
  883.  
  884.             print_info(info_color, "\n\t" + str(count) + " results.")        
  885.  
  886.         except Exception, e:
  887.             show_error(e)
  888.             sys.exit(1)
  889.  
  890.  
  891.  
  892.  
  893. class User_Images:
  894.     """ Handle user images and metadata information """
  895.     metadata = 0
  896.  
  897.     profile_image_url = ""
  898.     profile_banner_url = ""
  899.     screen_name = ""
  900.  
  901.     pic = [] 
  902.     pics_directory = ""
  903.     pics_result = 0
  904.     username = ""
  905.     images = ""
  906.     meta = ""
  907.     meta_description = {}
  908.     meta_copyright = {}
  909.     meta_date = {}
  910.     meta_make = {}
  911.     meta_model = {}
  912.     meta_software = {}
  913.     meta_distance = {}
  914.     meta_size = {}
  915.     meta_platform = {}
  916.     meta_iccdate = {}
  917.     meta_GPSLatitude = {}
  918.     meta_coordinates = {}
  919.     meta_thumb = {}
  920.     meta_profile_image = []
  921.     meta_profile_banner = []
  922.  
  923.     platforms = {
  924.         "APPL" : "Apple Computer Inc.", 
  925.         "MSFT" : "Microsoft Corporation", 
  926.         "SGI " : "Silicon Graphics Inc.", 
  927.         "SUNW" : "Sun Microsystems Inc.", 
  928.         "TGNT" : "Taligent Inc.",
  929.         }
  930.  
  931.     # ----------------------------------------------------------------------
  932.     def set_images_information(self, tweet):
  933.         try:
  934.             media_url = ""
  935.             image = ""
  936.  
  937.             if tweet.entities.has_key('media') :
  938.                 medias = tweet.entities['media']
  939.                 for m in medias :
  940.                     media_url = m['media_url']
  941.                     if str(media_url).find("video") >= 0:
  942.                         media_url = get_video_url(m['expanded_url'])
  943.                     else:
  944.                         if self.images == "d" or self.meta:
  945.                             if not os.path.isdir(self.username):
  946.                                 os.mkdir(self.username)
  947.                             img = urllib2.urlopen(media_url).read()
  948.                             filename = media_url.split('/')[-1]
  949.                             self.pics_directory = os.path.dirname(os.path.abspath(__file__)) + "/" + self.username
  950.                             image = self.pics_directory + "/" +filename
  951.                             if not os.path.exists(self.username+"/"+filename):
  952.                                 f = open(self.username+"/"+filename, 'wb')
  953.                                 f.write(img)
  954.                                 f.close()            
  955.  
  956.             if media_url:
  957.                 self.pic.append([media_url, image, str(tweet.created_at.strftime('%m/%d/%Y')), str(tweet.created_at.time())])
  958.  
  959.         except Exception, e:
  960.             show_error(e)
  961.             sys.exit(1)
  962.  
  963.  
  964.     # ----------------------------------------------------------------------
  965.     def show_images_information(self, info_color, header_color, fun_color):
  966.         try:
  967.             string = "MEDIA RESOURCES "
  968.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  969.  
  970.             print_header(header_color, "User Images and Videos\t\t\t\t\tDate\t\tTime")
  971.             n = 0
  972.             for p in self.pic:
  973.                 if len(p[0]):
  974.                     n += 1
  975.                     value = get_string_with_padding(str(p[0]), 53)
  976.                     print_info(info_color, value + "\t" + p[2] + "\t" + p[3])             
  977.  
  978.             print_info(info_color, "\n\t" + str(n) + " results.")        
  979.  
  980.         except Exception, e:
  981.             show_error(e)
  982.             sys.exit(1)
  983.  
  984.  
  985.  
  986.     # ----------------------------------------------------------------------
  987.     def set_metadata_information(self, tweet):
  988.         try:
  989.  
  990.             for p in self.pic:
  991.                 path = p[1]
  992.                 self.meta_description[p[0]] = ""
  993.                 self.meta_copyright[p[0]] = ""
  994.                 self.meta_date[p[0]] = ""
  995.                 self.meta_make[p[0]] = ""
  996.                 self.meta_model[p[0]] = ""
  997.                 self.meta_software[p[0]] = ""
  998.                 self.meta_distance[p[0]] = ""
  999.                 self.meta_platform[p[0]] = ""
  1000.                 self.meta_iccdate[p[0]] = ""
  1001.                 self.meta_coordinates[p[0]] = ""
  1002.                 self.meta_thumb[p[0]] = ""
  1003.  
  1004.                 fileName, fileExtension = os.path.splitext(path)                                
  1005.  
  1006.                 if os.path.exists(path):
  1007.                     img = Image.open(path)
  1008.                     if fileExtension in (".jpg", ".jpeg"):            
  1009.                         if img._getexif():
  1010.                             metadata = 1
  1011.                             exif = { ExifTags.TAGS[k]: v for k, v in img._getexif().items() if k in ExifTags.TAGS }
  1012.                             self.meta_description[p[0]] = unicode(exif['ImageDescription'])
  1013.                             self.meta_copyright[p[0]] = unicode(exif['Copyright'])
  1014.                             self.meta_date[p[0]] = unicode(exif['ImageDescription'])
  1015.                             self.meta_make[p[0]] = unicode(exif['Make'])
  1016.                             self.meta_model[p[0]] = unicode(exif['Model'])
  1017.                             self.meta_software[p[0]] = unicode(exif['Software'])
  1018.                             self.meta_distance[p[0]] = unicode(exif['SubjectDistance'][0]/float(exif['SubjectDistance'][1])) + " meters"
  1019.  
  1020.                     self.meta_size[p[0]] = str(img.size[0]) + "x" + str(img.size[1]) + " px"
  1021.                     if 'icc_profile' in img.info:
  1022.                         icc_profile = img.info.get("icc_profile")
  1023.                         if icc_profile:
  1024.                             platform = icc_profile[40:44]
  1025.                             metadata = 1
  1026.                             if platform in ('APPL', 'MSFT', 'SGI ', 'SUNW', 'TGNT'):
  1027.                                 self.meta_platform[p[0]] = self.platforms[platform]
  1028.                             datetime = struct.unpack('>hhhhhh',icc_profile[24:36])
  1029.                             tmp_tuple = (0, 0, 0)
  1030.                             final_tuple = datetime + tmp_tuple
  1031.                             self.meta_iccdate[p[0]] = unicode(time.strftime('%Y/%m/%d %H:%M:%S', final_tuple))
  1032.  
  1033.                     # Checkf for GPS information
  1034.                     try:
  1035.                         latitude = metadata.__getitem__("Exif.GPSInfo.GPSLatitude")
  1036.                         latitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef")
  1037.                         longitude = metadata.__getitem__("Exif.GPSInfo.GPSLongitude")
  1038.                         longitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef")
  1039.  
  1040.                         latitude = str(latitude).split("=")[1][1:-1].split(" ");
  1041.                         latitude = map(lambda f: str(float(Fraction(f))), latitude)
  1042.                         latitude = latitude[0] + u"\u00b0" + latitude[1] + "'" + latitude[2] + '"' + " " + str(latitudeRef).split("=")[1][1:-1]
  1043.  
  1044.                         longitude = str(longitude).split("=")[1][1:-1].split(" ");
  1045.                         longitude = map(lambda f: str(float(Fraction(f))), longitude)
  1046.                         longitude = longitude[0] + u"\u00b0" + longitude[1] + "'" + longitude[2] + '"' + " " + str(longitudeRef).split("=")[1][1:-1]
  1047.  
  1048.                         latitude_value = dms_to_decimal(*metadata.__getitem__("Exif.GPSInfo.GPSLatitude").value + [metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef").value]);
  1049.                         longitude_value = dms_to_decimal(*metadata.__getitem__("Exif.GPSInfo.GPSLongitude").value + [metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef").value]);
  1050.  
  1051.                         self.meta_coordinates[p[0]] = str(latitude_value) + ", " + str(longitude_value)
  1052.                     except Exception, e:
  1053.                         # No GPS information
  1054.                         pass
  1055.  
  1056.         except Exception, e:
  1057.             show_error(e)
  1058.             sys.exit(1)
  1059.  
  1060.     # ----------------------------------------------------------------------
  1061.     def show_metadata_information(self, info_color, header_color, fun_color):
  1062.         try:
  1063.             string = "METADATA "
  1064.             print "\n\n\t" + chr(27) + fun_color + "\t" + string + chr(27) + "[0m"
  1065.  
  1066.             # Extract metadata from profile image
  1067.             self.get_metadata(self.profile_image_url.replace("_normal.", "."), 1, "Profile Image", 1, self.screen_name, header_color, info_color)
  1068.             print
  1069.  
  1070.             print_header(header_color, "User Images")
  1071.  
  1072.             for p in self.pic:
  1073.                 if len(p[0]) and ".mp4" not in (p[0]):
  1074.                     meta = 0
  1075.                     print_info(info_color, p[0])
  1076.  
  1077.                     description = self.meta_description[p[0]]
  1078.                     copyright = self.meta_copyright[p[0]]
  1079.                     date = self.meta_date[p[0]] 
  1080.                     make = self.meta_make[p[0]] 
  1081.                     model = self.meta_model[p[0]] 
  1082.                     software = self.meta_software[p[0]] 
  1083.                     distance = self.meta_distance[p[0]] 
  1084.                     size = self.meta_size[p[0]]
  1085.                     platform = self.meta_platform[p[0]]
  1086.                     iccdate = self.meta_iccdate[p[0]]
  1087.                     coordinates = self.meta_coordinates[p[0]]
  1088.                     thumb = self.meta_thumb[p[0]]
  1089.  
  1090.                     if len(description):
  1091.                         print_info(info_color, "\tDescription: \t" + description)
  1092.                         meta = 1
  1093.                     if len(copyright):
  1094.                         print_info(info_color, "\tCopyright: \t" + copyright)
  1095.                         meta = 1
  1096.                     if len(date):
  1097.                         print_info(info_color, "\tDate: \t" + date)
  1098.                         meta = 1
  1099.                     if len(make):
  1100.                         print_info(info_color, "\tMake: \t" + make)
  1101.                         meta = 1
  1102.                     if len(model):
  1103.                         print_info(info_color, "\tModel: \t" + model)
  1104.                         meta = 1
  1105.                     if len(software):
  1106.                         print_info(info_color, "\tSoftware: \t" + software)
  1107.                         meta = 1
  1108.                     if len(distance):
  1109.                         print_info(info_color, "\tSubject distance: \t" + distance)
  1110.                         meta = 1
  1111.                     if len(size):
  1112.                         print_info(info_color, "\tSize: \t\t" + size)
  1113.                         meta = 1
  1114.                     if len(platform):
  1115.                         print_info(info_color, "\tPlatform: \t" + platform)
  1116.                         meta = 1
  1117.                     if len(iccdate):
  1118.                         print_info(info_color, "\tICC Date: \t" + iccdate)
  1119.                         meta = 1
  1120.                     if thumb:
  1121.                         print_info(info_color, "\tThumbnail: \t" + thumb)
  1122.                         meta = 1
  1123.                     if len(coordinates):
  1124.                         print_info(info_color, "\tCoordinates: \t" + coordinates)
  1125.                         meta = 1
  1126.  
  1127.                     if not meta:
  1128.                         print "\n\t\tNo metadata found."
  1129.  
  1130.         except Exception, e:
  1131.             show_error(e)
  1132.             sys.exit(1)
  1133.  
  1134.     # ----------------------------------------------------------------------            
  1135.     def get_metadata(self, filename, save, desc, header, username, header_color, info_color):
  1136.         try:
  1137.             metadata = 0
  1138.             platforms = {
  1139.                 "APPL" : "Apple Computer Inc.", 
  1140.                 "MSFT" : "Microsoft Corporation", 
  1141.                 "SGI " : "Silicon Graphics Inc.", 
  1142.                 "SUNW" : "Sun Microsystems Inc.", 
  1143.                 "TGNT" : "Taligent Inc.",
  1144.             }
  1145.  
  1146.             if desc == "Profile Image":
  1147.                     self.profile_image_url = filename
  1148.  
  1149.             if header:
  1150.                 print_header(header_color, desc)
  1151.                 print_info(info_color, "Image URL: \t\t\t" + filename)                
  1152.  
  1153.             if save:
  1154.                 save_image(filename, username)
  1155.  
  1156.             pics_directory = os.path.dirname(os.path.abspath(__file__)) + "/" + username
  1157.  
  1158.             filename = filename.split('/')[-1]
  1159.             path = pics_directory + "/" + filename
  1160.             fileName, fileExtension = os.path.splitext(path)                    
  1161.  
  1162.  
  1163.             if os.path.exists(path):            
  1164.                 img = Image.open(path)
  1165.                 if fileExtension in (".jpg", ".jpeg"):            
  1166.                     if img._getexif():
  1167.                         metadata = 1
  1168.                         exif = { ExifTags.TAGS[k]: v for k, v in img._getexif().items() if k in ExifTags.TAGS }
  1169.                         print_info(info_color, "Description: \t\t\t" + unicode(exif['ImageDescription']))
  1170.                         print_info(info_color, "Copyright: \t\t\t" + unicode(exif['Copyright']))
  1171.                         print_info(info_color, "Date: \t\t\t\t" + unicode(exif['DateTimeOriginal']))
  1172.                         print_info(info_color, "Make: \t\t\t\t" + unicode(exif['Make']))
  1173.                         print_info(info_color, "Model: \t\t\t\t" + unicode(exif['Model']))
  1174.                         print_info(info_color, "Software: \t\t\t" + unicode(exif['Software']))
  1175.                         print_info(info_color, "Subject distance: \t\t" + unicode(exif['SubjectDistance'][0]/float(exif['SubjectDistance'][1])) + " meters")
  1176.  
  1177.                         if desc == "Profile Image":
  1178.                             self.meta_profile_image.append(unicode(exif['ImageDescription']))
  1179.                             self.meta_profile_image.append(unicode(exif['Copyright']))
  1180.                             self.meta_profile_image.append(unicode(exif['DateTimeOriginal']))
  1181.                             self.meta_profile_image.append(unicode(exif['Make']))
  1182.                             self.meta_profile_image.append(unicode(exif['Model']))
  1183.                             self.meta_profile_image.append(unicode(exif['Software']))
  1184.                             self.meta_profile_image.append(unicode(exif['SubjectDistance'][0]/float(exif['SubjectDistance'][1])) + " meters")
  1185.  
  1186.                     else:    
  1187.                         self.meta_profile_image.append("")
  1188.                         self.meta_profile_image.append("")
  1189.                         self.meta_profile_image.append("")
  1190.                         self.meta_profile_image.append("")
  1191.                         self.meta_profile_image.append("")
  1192.                         self.meta_profile_image.append("")
  1193.                         self.meta_profile_image.append("")
  1194.  
  1195.  
  1196.                 print_info(info_color, "Size: \t\t\t\t" + str(img.size[0]) + "x" + str(img.size[1]) + " px")
  1197.                 if 'icc_profile' in img.info:
  1198.                     icc_profile = img.info.get("icc_profile")
  1199.                     if icc_profile:
  1200.                         platform = icc_profile[40:44]
  1201.                         metadata = 1
  1202.                         if platform in ('APPL', 'MSFT', 'SGI ', 'SUNW', 'TGNT'):
  1203.                             print_info(info_color, "Platform: \t\t\t" + platforms[platform])
  1204.                             if desc == "Profile Image":
  1205.                                 self.meta_profile_image.append(platforms[platform])
  1206.                             else:
  1207.                                 self.meta_profile_image.append("")
  1208.  
  1209.                         datetime = struct.unpack('>hhhhhh',icc_profile[24:36])
  1210.                         tmp_tuple = (0, 0, 0)
  1211.                         final_tuple = datetime + tmp_tuple
  1212.                         print_info(info_color, "ICC Date: \t\t\t" + time.strftime('%Y/%m/%d %H:%M:%S', final_tuple))
  1213.                         if desc == "Profile Image":
  1214.                             self.meta_profile_image.append(time.strftime('%Y/%m/%d %H:%M:%S', final_tuple))
  1215.                         else:
  1216.                             self.meta_profile_image.append("")
  1217.  
  1218.                 try:
  1219.                     latitude = metadata.__getitem__("Exif.GPSInfo.GPSLatitude")
  1220.                     latitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef")
  1221.                     longitude = metadata.__getitem__("Exif.GPSInfo.GPSLongitude")
  1222.                     longitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef")
  1223.  
  1224.                     latitude = str(latitude).split("=")[1][1:-1].split(" ");
  1225.                     latitude = map(lambda f: str(float(Fraction(f))), latitude)
  1226.                     latitude = latitude[0] + u"\u00b0" + latitude[1] + "'" + latitude[2] + '"' + " " + str(latitudeRef).split("=")[1][1:-1]
  1227.  
  1228.                     longitude = str(longitude).split("=")[1][1:-1].split(" ");
  1229.                     longitude = map(lambda f: str(float(Fraction(f))), longitude)
  1230.                     longitude = longitude[0] + u"\u00b0" + longitude[1] + "'" + longitude[2] + '"' + " " + str(longitudeRef).split("=")[1][1:-1]
  1231.  
  1232.                     latitude_value = dms_to_decimal(*metadata.__getitem__("Exif.GPSInfo.GPSLatitude").value + [metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef").value]);
  1233.                     longitude_value = dms_to_decimal(*metadata.__getitem__("Exif.GPSInfo.GPSLongitude").value + [metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef").value]);
  1234.  
  1235.                     print_info(info_color, "GPS Information:\t\t" + str(latitude_value) + ", " + str(longitude_value))
  1236.                 except Exception, e:
  1237.                     print_info(info_color, "GPS Information:\t\tNot found")
  1238.  
  1239.             print 
  1240.  
  1241.         except Exception, e:
  1242.             show_error(e)
  1243.             sys.exit(1)
  1244.  
  1245.  
  1246. class Parameters:
  1247.     """Global program parameters"""
  1248.     # ----------------------------------------------------------------------
  1249.     def __init__(self, **kwargs):
  1250.         try:
  1251.             config = Configuration()
  1252.             self.api = config.api
  1253.             self.info_color = config.color
  1254.             self.header_color = config.color_hdr
  1255.             self.function_color = config.color_fun
  1256.             self.screen_name= kwargs.get("username")
  1257.             self.tweets = kwargs.get("tweets")
  1258.             self.sdate = kwargs.get("sdate")
  1259.             self.edate = kwargs.get("edate")
  1260.             self.sdate = kwargs.get("stime")
  1261.             self.edate = kwargs.get("etime")
  1262.             self.elapsedtime = kwargs.get("elapsedtime")
  1263.             self.friend = kwargs.get("friend")
  1264.             self.geo = kwargs.get("geo")
  1265.             self.top = kwargs.get("top")
  1266.             self.find = kwargs.get("find")
  1267.             self.output = kwargs.get("output")
  1268.  
  1269.             self.program_name ="Tinfoleak"
  1270.             self.program_version = "v1.5"
  1271.             self.program_date = "03/20/2015"
  1272.             self.program_author_name = "Vicente Aguilera Diaz"
  1273.             self.program_author_twitter = "@VAguileraDiaz"
  1274.             self.program_author_companyname = "Internet Security Auditors"
  1275.  
  1276.         except Exception, e:
  1277.             show_error(e)
  1278.             sys.exit(1)
  1279.  
  1280.  
  1281. # ----------------------------------------------------------------------
  1282. def print_header(color, string):
  1283.     """Print header in the console"""
  1284.     try:
  1285.         print
  1286.         print
  1287.         print chr(27) + color + "\t" + string + chr(27) + "[0m"
  1288.         print chr(27) + color + "\t====================================================================================" + chr(27) + "[0m"
  1289.     except Exception, e:
  1290.         show_error(e)
  1291.         sys.exit(1)
  1292.  
  1293.  
  1294. # ----------------------------------------------------------------------
  1295. def print_info(color, string):
  1296.     """Print info in the console"""
  1297.     try:
  1298.         print chr(27) + color + "\t" + string + chr(27) + "[0m"
  1299.     except Exception, e:
  1300.         show_error(e)
  1301.         sys.exit(1)
  1302.  
  1303.  
  1304. # ----------------------------------------------------------------------
  1305. def is_valid(tweet, args):
  1306.     """Verify if a tweet meets all requirements"""
  1307.     try:
  1308.         valid = 1
  1309.  
  1310.         date = str(tweet.created_at.strftime('%Y/%m/%d'))
  1311.         if date < args.sdate or date > args.edate:
  1312.             valid = 0
  1313.         time = str(tweet.created_at.strftime('%H:%M:%S'))
  1314.         if time< args.stime or time> args.etime:
  1315.             valid = 0
  1316.  
  1317.         return valid
  1318.  
  1319.     except Exception, e:
  1320.         show_error(e)
  1321.         sys.exit(1)
  1322.  
  1323.  
  1324. # ----------------------------------------------------------------------
  1325. def get_video_url(url):
  1326.     """Get video URL from a tweet media URL"""
  1327.     try:
  1328.         video_url = ""
  1329.  
  1330.         response = urllib2.urlopen(str(url))  
  1331.         html = response.read()
  1332.         if html.find(".mp4") >= 0:
  1333.             begin = html.index('video-src="')
  1334.             end = html.index('.mp4"')
  1335.             video_url = html[begin+11:end+4]
  1336.  
  1337.         return video_url
  1338.  
  1339.     except Exception, e:
  1340.         show_error(e)
  1341.         sys.exit(1)
  1342.  
  1343.  
  1344.  
  1345. # ----------------------------------------------------------------------
  1346. def generates_HTML_file(parameters, user, source, hashtag, mention, geolocation, user_images, user_tweets):
  1347.     """Generates a HTML output file"""
  1348.     try:
  1349.         tinfoleak_dir = os.path.dirname(os.path.abspath(__file__))
  1350.         jinja2_env = Environment(loader=FileSystemLoader(tinfoleak_dir), autoescape=True, trim_blocks=True)
  1351.  
  1352.         desc = user.description
  1353.         if user.expanded_description:
  1354.             desc = user.expanded_description
  1355.  
  1356.         url = user.url
  1357.         if user.expanded_url and len(user.expanded_url) < 50:
  1358.             url = user.expanded_url        
  1359.  
  1360.         template_values = {
  1361.             'program': parameters.program_name, 
  1362.             'version': parameters.program_version,
  1363.             'author_name': parameters.program_author_name,
  1364.             'author_twitter': parameters.program_author_twitter,
  1365.             'author_company': parameters.program_author_companyname,
  1366.             'profile_image': user.profile_image_url.replace("_normal.", "."),
  1367.             'screen_name': user.screen_name,
  1368.             'user_name': user.name, 
  1369.             'twitter_id': user.id,
  1370.             'date': user.created_at.strftime('%m/%d/%Y'),
  1371.             'followers': '{:,}'.format(user.followers_count),
  1372.             'friends': '{:,}'.format(user.friends_count),
  1373.             'geo': user.geo_enabled,
  1374.             'tweets': '{:,}'.format(user.statuses_count),
  1375.             'location': user.location,
  1376.             'timezone': user.time_zone,
  1377.             'description': desc, 
  1378.             'url': url,
  1379.             'tweets_average': user.tweets_average,
  1380.  
  1381.             # source
  1382.             'source': source.sources,
  1383.             'sources_count': source.sources_count,
  1384.             'sources_percent': source.sources_percent,
  1385.             'sources_firstdate': source.sources_firstdate,
  1386.             'sources_lastdate': source.sources_lastdate,
  1387.             'sources_results': len(source.sources),
  1388.  
  1389.             # hashtag
  1390.             'hashtags_tweet': hashtag.hashtags_tweet,
  1391.             'hashtags_results1': hashtag.hashtags_results1,
  1392.             'hashtags_results2': hashtag.hashtags_results2,
  1393.             'hashtags_results3': hashtag.hashtags_results3,
  1394.             'hashtags_firstdate': hashtag.hashtags_firstdate,
  1395.             'hashtags_lastdate': hashtag.hashtags_lastdate,
  1396.             'hashtag': hashtag.hashtags,
  1397.             'hashtags_rt': hashtag.hashtags_rt,
  1398.             'hashtags_fv': hashtag.hashtags_fv,
  1399.             'hashtags_count': hashtag.hashtags_count,
  1400.             'hashtags_top': hashtag.hashtags_top,
  1401.  
  1402.             # mention
  1403.             'mentions_tweet': mention.mentions_tweet,
  1404.             'mentions_results1': len(mention.mentions_tweet),
  1405.             'mentions_results2': len(mention.mentions_count),
  1406.             'mentions_results3': mention.mentions_results3,
  1407.             'mentions_firstdate': mention.mentions_firstdate,
  1408.             'mentions_lastdate': mention.mentions_lastdate,
  1409.             'mention': mention.mentions,
  1410.             'mentions_rt': mention.mentions_rt,
  1411.             'mentions_fv': mention.mentions_fv,
  1412.             'mentions_count': mention.mentions_count,
  1413.             'mentions_top': mention.mentions_top,
  1414.  
  1415.             # find text 
  1416.             'find': user_tweets.find,
  1417.             'tweet_find': user_tweets.tweets_find,
  1418.             'find_count': len(user_tweets.tweets_find),
  1419.  
  1420.             # media
  1421.             'media': user_images.pic,
  1422.             'media_directory': user_images.pics_directory,
  1423.             'media_count': len(user_images.pic),
  1424.  
  1425.             #meta
  1426.             'meta_size': user_images.meta_size,
  1427.             'meta_description': user_images.meta_description,
  1428.             'meta_copyright': user_images.meta_copyright,
  1429.             'meta_date': user_images.meta_date,
  1430.             'meta_make': user_images.meta_make,
  1431.             'meta_model': user_images.meta_model,
  1432.             'meta_software': user_images.meta_software,
  1433.             'meta_distance': user_images.meta_distance,
  1434.             'meta_platform': user_images.meta_platform,
  1435.             'meta_iccdate': user_images.meta_iccdate,
  1436.             'meta_coordinates': user_images.meta_coordinates,
  1437.             'meta_thumb': user_images.meta_thumb,
  1438.             'meta_profile_image': user_images.meta_profile_image,
  1439.             'meta_profile_banner': user_images.meta_profile_banner,
  1440.             'meta_profile_image_url': user_images.profile_image_url,
  1441.             'meta_profile_banner_url': user_images.profile_banner_url,
  1442.  
  1443.             # geolocation
  1444.             'geo_info': geolocation.geo_info,
  1445.             'geo_count': len(geolocation.geo_info),
  1446.             'geo_media': geolocation.media_info,            
  1447.             'geo_info_count': len(geolocation.geo_info),
  1448.             'geo_visited_locations': geolocation.visited_locations,
  1449.             'geo_visited_locations_count': len(geolocation.visited_locations),    
  1450.             'geo_toplocations_tweets': geolocation.toplocations_tweets,    
  1451.             'geo_toplocations': geolocation.toploc,
  1452.             'geo_toplocations_count': len(geolocation.toploc)
  1453.         }
  1454.  
  1455.         html_content = jinja2_env.get_template('ReportTemplate/tinfoleak-theme.html').render(template_values)
  1456.  
  1457.         f = open("ReportTemplate/"+parameters.output, "w")
  1458.         f.write(html_content.encode('utf-8'))
  1459.         f.close()
  1460.  
  1461.     except Exception, e:
  1462.         show_error(e)
  1463.         sys.exit(1)
  1464.  
  1465.  
  1466.  
  1467. # ----------------------------------------------------------------------
  1468. def save_image(url, username):
  1469.     try:
  1470.         if not os.path.isdir(username):
  1471.             os.mkdir(username)
  1472.  
  1473.         img = urllib2.urlopen(url).read()
  1474.         filename = url.split('/')[-1]
  1475.         pics_directory = os.path.dirname(os.path.abspath(__file__)) + "/" + username
  1476.         image = pics_directory + "/" +filename
  1477.         if not os.path.exists(username+"/"+filename):
  1478.             f = open(username+"/"+filename, 'wb')
  1479.             f.write(img)
  1480.             f.close()
  1481.  
  1482.     except Exception, e:
  1483.         show_error(e)
  1484.         sys.exit(1)
  1485.  
  1486.  
  1487. # ----------------------------------------------------------------------
  1488. def get_information(args, parameters):
  1489.     """Get information about a Twitter user"""
  1490.     try:
  1491.  
  1492.         api = parameters.api.get_user(args.username)
  1493.         source = Sources()
  1494.         hashtag = Hashtags()
  1495.         mentions = Mentions()
  1496.         user_images = User_Images()
  1497.         geolocation = Geolocation()
  1498.         user = User()
  1499.         user.set_user_information(api)
  1500.         user.meta = args.meta
  1501.  
  1502.         if args.information:
  1503.             user.show_user_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1504.             print "\n" 
  1505.  
  1506.         user_tweets = User_Tweets()
  1507.  
  1508.         if args.sources or args.hashtags or args.mentions or args.d or args.file or args.number or args.text:
  1509.  
  1510.             page = 1
  1511.             tweets_count = 0    
  1512.             while True:
  1513.                 timeline = parameters.api.user_timeline(screen_name=args.username, include_rts=True, count=args.tweets, page=page)
  1514.  
  1515.                 if timeline:
  1516.                     for tweet in timeline:
  1517.                         tweets_count += 1
  1518.                         if is_valid(tweet, args):
  1519.                             if args.sources:
  1520.                                 # Get information about the sources applications used to publish tweets
  1521.                                 source.set_sources_information(tweet)
  1522.                             if args.hashtags:
  1523.                                 # Get hashtags included in tweets
  1524.                                 hashtag.set_hashtags_information(tweet)
  1525.                             if args.mentions:
  1526.                                 # Get mentions included in tweets
  1527.                                 mentions.set_mentions_information(tweet)
  1528.                             if args.d:
  1529.                                 # Get images included in tweets
  1530.                                 user_images.username = args.username
  1531.                                 user_images.images = args.d
  1532.                                 user_images.meta = args.meta
  1533.                                 user_images.set_images_information(tweet)
  1534.                             if args.meta:
  1535.                                 # Get metadata information from user images
  1536.                                 user_images.set_metadata_information(tweet)
  1537.                             if args.file or args.number:
  1538.                                 # Get geolocation information from user tweets
  1539.                                 geolocation.set_geolocation_information(tweet)
  1540.                                 geolocation.set_geofile_information(tweet, user)
  1541.                             if args.text:
  1542.                                 # Search text in tweets
  1543.                                 user_tweets.find = args.text
  1544.                                 user_tweets.set_find_information(args.text, tweet)
  1545.  
  1546.                         sys.stdout.write("\r\t" + str(tweets_count) + " tweets analyzed")
  1547.                         sys.stdout.flush()                                        
  1548.                         if tweets_count >= int(args.tweets):
  1549.                             print
  1550.                             break
  1551.                 else:
  1552.                     print
  1553.                     break
  1554.                 page += 1
  1555.                 if tweets_count >= int(args.tweets):
  1556.                     print
  1557.                     break
  1558.  
  1559.             print
  1560.  
  1561.             if args.sources:
  1562.                 source.show_sources_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1563.  
  1564.             if args.hashtags:
  1565.                 hashtag.show_hashtags_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1566.  
  1567.             if args.mentions:
  1568.                 mentions.show_mentions_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1569.  
  1570.             if args.d:
  1571.                 user_images.show_images_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1572.  
  1573.             if args.meta and args.d:
  1574.                 user_images.profile_image_url = user.profile_image_url
  1575.                 user_images.profile_banner_url = user.profile_banner_url
  1576.                 user_images.screen_name = user.screen_name
  1577.                 user_images.show_metadata_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1578.  
  1579.             if args.file:
  1580.                 # Show geolocation information from user tweets
  1581.                 geolocation.show_geolocation_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1582.                 geolocation.generates_geofile(args.file, parameters)
  1583.  
  1584.             if args.number:
  1585.                 # Show top N geolocation information 
  1586.                 geolocation.show_top_locations(parameters.info_color, parameters.header_color, parameters.top, parameters.function_color)
  1587.  
  1588.             if args.text:
  1589.                 # Show results for search text in tweets
  1590.                 user_tweets.show_find_information(parameters.info_color, parameters.header_color, parameters.function_color)
  1591.  
  1592.         if args.friendname:
  1593.             # Get friendship information
  1594.             friend = parameters.api.show_friendship(source_screen_name=args.username, target_screen_name=args.friendname)
  1595.             user.set_friendship(friend)
  1596.             user.show_friendship(parameters.info_color, parameters.header_color, parameters.function_color)
  1597.  
  1598.         if not args.information and not args.friendname and not args.file and not args.number and not args.d and not args.sources and not args.hashtags and not args.mentions and not args.text and not args.meta:
  1599.                 print "\tYou need to specify an operation. Execute './tinfoleak.py -h' to see the available operations."
  1600.         else:
  1601.             if args.output:
  1602.                 generates_HTML_file(parameters, user, source, hashtag, mentions, geolocation, user_images, user_tweets)
  1603.  
  1604.     except Exception as e:
  1605.         show_error(e)
  1606.         sys.exit(1)
  1607.  
  1608.  
  1609. # ----------------------------------------------------------------------
  1610. def show_error(error):
  1611.     """ Show error message """
  1612.     try:
  1613.         print "\tOops! Something went wrong:"
  1614.  
  1615.         if str(error).find("Name or service not known") >= 0:
  1616.             print "\n\tDo you have Internet connection?"
  1617.         else:
  1618.             if str(error).find("Could not authenticate you") >= 0:
  1619.                 print "\n\tYou need to assign value to OAuth tokens. Please, read the README.txt file for more information."
  1620.             else:                
  1621.                 print "\n\t" + str(sys.exc_info()[1][0][0]['message'])        
  1622.         print 
  1623.  
  1624.     except Exception, e:
  1625.         print "\n\t" + str(error) + "\n"
  1626.         sys.exit(1)
  1627.  
  1628.  
  1629. # ----------------------------------------------------------------------
  1630. def get_string_with_padding(string, lon):
  1631.     """ Return a string with the specified length """
  1632.  
  1633.     try:
  1634.         padding = " " * lon
  1635.         if len(string) < lon:
  1636.             string_tmp = string + padding[0:len(padding)-len(string)]
  1637.             string = string_tmp[0:len(padding)]
  1638.         else:
  1639.             string_tmp = string
  1640.             string = string_tmp[0:len(padding)]
  1641.  
  1642.         return string
  1643.  
  1644.     except Exception as e:
  1645.         show_error(e)
  1646.         sys.exit(1)
  1647.  
  1648.  
  1649. # ----------------------------------------------------------------------
  1650. def main():
  1651.     """ Main function"""
  1652.     try:
  1653.         parameters = Parameters() 
  1654.         credits(parameters)
  1655.  
  1656.         parser = argparse.ArgumentParser(
  1657.             version='Tinfoleak v1.5',
  1658.             description='Tinfoleak')
  1659.         parser.add_argument('-t', '--tweets', dest='tweets', default=200, help='number of tweets to be analysed (default: 200)')
  1660.         parser.add_argument('username', default='twitter', help='Twitter user name')
  1661.         parser.add_argument('-i', '--info', action='store_true', dest='information', help='general information about a user')
  1662.         parser.add_argument('-s', '--sources', action='store_true', dest='sources', help='show the client applications used to publish the tweets')
  1663.         parser.add_argument('--sdate', dest='sdate', default='1900/01/01', help='filter the results for this start date (format: yyyy/mm/dd)')
  1664.         parser.add_argument('--edate', dest='edate', default='2100/01/01', help='filter the results for this end date (format: yyyy/mm/dd)')
  1665.         parser.add_argument('--stime', dest='stime', default='00:00:00', help='filter the results for this start time (format: HH:MM:SS)')
  1666.         parser.add_argument('--etime', dest='etime', default='23:59:59', help='filter the results for this end date (format: HH:MM:SS)')
  1667.         parser.add_argument('--hashtags', action='store_true', dest='hashtags', help='show info about hashtags included in tweets')
  1668.         parser.add_argument('--mentions', action='store_true', dest='mentions', help='show info about user mentions')
  1669.         parser.add_argument('--meta', action='store_true', dest='meta', help='show metadata information from user images')
  1670.         parser.add_argument('--media', dest='d', const='*', help='[no value]: show user images and videos, [d]: download user images to \"username\" directory', type=str, nargs='?')
  1671.         parser.add_argument('--friend', dest='friendname', default='', help='Show friendship with the FRIENDNAME user')
  1672.         parser.add_argument('--geo', dest='file', default='', help='show geolocation info and generates a output FILE (KML format)')
  1673.         parser.add_argument('--top', dest='number', default='', help='show top NUMBER locations visited by the user')
  1674.         parser.add_argument('--find', dest='text', default='', help='search TEXT in user tweets')
  1675.         parser.add_argument('-o', '--output', dest='output', default='', help='generates a OUTPUT file (HTML format)')
  1676.  
  1677.         args = parser.parse_args()
  1678.  
  1679.         if args.sdate:
  1680.             parameters.sdate = args.sdate
  1681.         else:
  1682.             parameters.sdate = "1900/01/01"
  1683.  
  1684.         if args.edate:
  1685.             parameters.edate = args.edate
  1686.         else:
  1687.             parameters.edate = "2100/01/01"
  1688.  
  1689.         if args.stime:
  1690.             parameters.stime = args.stime
  1691.         else:
  1692.             parameters.stime = "00:00:00"
  1693.  
  1694.         if args.etime:
  1695.             parameters.etime= args.etime
  1696.         else:
  1697.             parameters.etime = "23:59:59"
  1698.  
  1699.         if args.friendname:
  1700.             parameters.etime= args.friendname
  1701.         else:
  1702.             parameters.etime = ""
  1703.  
  1704.         if args.file:
  1705.             parameters.geo = args.file
  1706.         else:
  1707.             parameters.geo = ""
  1708.  
  1709.         if args.number:
  1710.             parameters.top = args.number
  1711.         else:
  1712.             parameters.top = ""
  1713.  
  1714.         if args.text:
  1715.             parameters.find = args.text
  1716.         else:
  1717.             parameters.find = ""
  1718.  
  1719.         if args.output:
  1720.             parameters.output= args.output
  1721.         else:
  1722.             parameters.output = ""
  1723.  
  1724.         print "Looking info for @"  + args.username
  1725.         print "\n"
  1726.  
  1727.         # Get the current time
  1728.         sdatetime = datetime.datetime.now()
  1729.  
  1730.         # Obtain the information requested
  1731.         get_information(args, parameters)
  1732.  
  1733.         # Show the elapsed time
  1734.         tdelta = datetime.datetime.now() - sdatetime
  1735.         hours, remainder = divmod(tdelta.seconds, 3600)
  1736.         minutes, seconds = divmod(remainder, 60)
  1737.         print "\n\n\tElapsed time: %02d:%02d:%02d" % (hours, minutes, seconds)
  1738.         print "\nSee you soon!\n"
  1739.  
  1740.         parameters.elapsedtime = (hours, minutes, seconds)
  1741.  
  1742.     except Exception, e:
  1743.         show_error(e)
  1744.         sys.exit(1)
  1745.  
  1746.  
  1747. if __name__ == '__main__':
  1748.     main()
Apr 28 '16 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 618
Please include the entire trackback error message so we know where the error occurs. There is nothing in the 748 lines posted like 'and here is my number of consumer key, so i can't write'.
Apr 29 '16 #2

P: 2
Hi, the only message I receive is this

May 1 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.