lnk.googl package¶
lnk.googl.cli module¶
lnk.googl.command module¶
Contains the base-class for all goo.gl commands.
-
class
lnk.googl.command.Command(which, credentials_path=None)[source]¶ Bases:
lnk.abstract.AbstractCommandBase-class for all goo.gl commands.
Configures the AbstractCommand base class for all commands in the entire application, which needs information about the service being used. Moreover fetches the oauth2 credentials for any HTTP request.
-
credentials¶ oauth2client.file.Storage
An object from Google’s API-library used to interact with the oauth2 credentials file.
Handles the authorization and re-authorization procedure.
Normally, this method will return an HTTP object from Google’s httplib2 library, authorized to fetch user-specifc data by using the credentials that were configured for the user. There are two other cases: The oauth2 access-token used to make oauth2 requests expires around-about every hour, so if that is the case this method will first refresh the token; if there are no credentials at all (i.e. the user did not run the ‘key’ command yet), this method throws an exception.
Returns: If all goes well, an oauth2-authorized httplib2.HTTP object. Raises: errors.AuthorizationError– If there are no credentials for this user yet (the initial authorization-procedure was not yet performed).
-
static
execute(request, what=None)[source]¶ Execute an HTTP request.
The main point of this method is to catch HTTP errors raised by Google’s API-library and re-raise them as lnk.errorrs.HTTPErrors.
-
get(url, projection=None, what=None)[source]¶ Base method to perform an HTTP request with the GET method.
Parameters: - url (str) – The short goo.gl URL for which to perform a data-request.
- projection (str|None) – Controls the amount of data returned for the url (values should be either None, such as for url-expansion, or ‘FULL’ to get statistics or information about a link).
- what (str) – A human-readable string representing what the request was for, such that if there is an error in the response, an errors.HTTPError is raised with the message ‘Could not <what>.’ (NOT: ‘even’).
Returns: The requested data.
-
lnk.googl.history module¶
Link-history-retrieval for the goo.gl client.
-
class
lnk.googl.history.History(raw=False)[source]¶ Bases:
lnk.googl.command.CommandClass to retrieve goo.gl link history for a user.
The sole purpose of this class is to fetch and return a list of urls the user has shortened using goo.gl in the past. This list may, of course, be properly prettified if necessary. A nice feature is that if the history is fetched with the ‘plain’ flag set to true its output can be piped into other lnk commands, such as ‘stat’ or ‘info’.
-
raw¶ bool
Whether to prettify the output or return it raw, for internal use.
-
delta¶ dict
A mapping between string representations of time and equivalent datetime.timedelta objects.
-
Url¶ namedtuple
Class-attribute namedtuple to represent a link with a short, long/expanded url and a creation date.
Note
The datetime.timedelta objects store time-offsets as floating-point values (e.g. 1 year = 365.242199 days) to account for time-weirdness such as shift-years, but they will nevertheless not be absolutely precise, but good enough.
-
class
Url(short, long, created) Bases:
tuple-
__getnewargs__()¶ Return self as a plain tuple. Used by copy and pickle.
-
__getstate__()¶ Exclude the OrderedDict from pickling
-
__repr__()¶ Return a nicely formatted representation string
-
created¶ Alias for field number 2
-
long¶ Alias for field number 1
-
short¶ Alias for field number 0
-
-
History.fetch(last, ranges, forever, limit, expanded, both, pretty)[source]¶ Fetches the link history and returns a string for output.
Parameters: - last (tuple) – A tuple of time_points to retrieve history for, without an upper bound (i.e. all links after a given time_point, up to now).
- ranges (tuple) – A tuple of time_point-ranges to retrieve history for (with a lowe and upper bound).
- forever (bool) – Whether or not to include data for all time_points (since forever).
- limit (int) – A limit on the number of datapoints fetched per time_point.
- expanded (bool) – Whether or not to show expanded rather than short links.
- both (bool) – Whether or not to show both short and expanded links (takes precedence over ‘expanded’).
- pretty (bool) – Whether or not to prettify the output.
Returns: A plain list of the raw lines if the ‘raw’ attribute is true, else a boxified, pretty string if the pretty flag is set, else the same plain list as for the first case, but joined to a string.
-
static
History.filter(urls, begin, end)[source]¶ Filters a list of urls according to a lower and upper-bound time-point.
Parameters: - urls (list|tuple) – A list/tuple of urls to filter.
- begin (int) – The lower-bound datetime object (all links mus be created at or after this point in time).
- end (int) – The upper-bound datetime object (all links mus be created at or before this point in time).
Returns: A list of filtered urls.
Note
The passed list of urls is not modified directly, i.e. the filtered list is a new list.
-
History.forever(urls, limit, expanded, both, pretty)[source]¶ Formats history for all possible time-ranges.
Parameters: - urls (list|tuple) – The original/full list of urls.
- limit (int) – A limit to the number of links to pick.
- expanded (bool) – Whether to show expanded or short links.
- both (bool) – Whether to show both expanded and short links.
- pretty (bool) – Whether to prettify the output.
Returns: A plain list of lines ready if pretty is false, else the same list of lines with a header (‘Since forever:’) plus an empty line for padding.
-
History.get_boundaries(time_range, base=None)[source]¶ Gets a lower and upper-bound timestamp for a given time_range.
Also checks whether the starting point is before the end point, and throws a UsageError if not (the user passed the range in the wrong format, e.g. -r 5 day 7 weeks).
Parameters: - time_range (tuple) – The time-range following the schema (span1, unit1, span2, unit2).
- base (int) – The base timestamp to pass to get_date().
Raises: errors.UsageError– if the starting point is after the end point.Returns: The begin and end timestamps (datetime objects).
-
History.get_date(time_point, base=None)[source]¶ Returns a UNIX timestamp for a given time-point.
The timestamp is base timestamp (either supplied to the function call or time.time()) minus the time_point, parsed into seconds.
Parameters: - time_point (tuple) – A time_point tuple of the schema (span, unit).
- base (int) – The base time-value from which to subtract the offset, defaults to time.time().
Returns: A UNIX timestamp, in seconds, as an integer (!).
-
History.last(urls, last, limit, expanded, both, pretty)[source]¶ Fetches and formats history after a given time-point.
Parameters: - urls (list|tuple) – The original/full list of urls.
- last (tuple) – The open-ended time-ranges of schema (span, unit).
- limit (int) – A limit to the number of links to pick for each time-range.
- expanded (bool) – Whether to show exapanded or short links.
- both (bool) – Whether to show both expanded and short links.
- pretty (bool) – Whether to prettify the output.
Returns: A plain list of lines ready if pretty is false, else the same list of lines with a header (e.g. ‘Last 4 weeks:’), plus an empty line for padding.
-
History.last_header(time_point, urls)[source]¶ Returns a header for an open-ended time-range.
Parameters: - time_point (tuple) – The lower-bound time-point.
- urls (list|tuple) – The urls, to check if empty.
Returns: A header of the schema ‘Last [<span>] <unit>’. The span is only shown if it is greater 1, such that ‘Last 1 day’ will be displayed as ‘Last day’. If the urls are empty, ‘ None’ is appended to the header.
-
History.lineify(url, expanded, both, pretty)[source]¶ Returns an output-ready line for a given url.
The line may include only the short url, only the long/expanded url or both, depending on the parameters passed.
Parameters: - url (str) – The short url.
- expanded (bool) – Whether or not to show the expanded link.
- both (bool) – Whether or not to show both the short and the expanded link (takes precedence over ‘expanded’).
- pretty (bool) – Whether or not to make the output pretty.
Returns: The short url if neither ‘expanded’ nor ‘both’ is set, both the short and the expanded url, in the schema ‘<short> => <expanded>’ if ‘both’ is set, else only the expanded link if ‘expanded’ is set. If ‘pretty’ is True, the line is returned in a formatted fashion (with color), else in plain format.
-
History.listify(urls, limit, expanded, both, pretty)[source]¶ Returns a list of lines for a list of urls.
Also performs limiting according to the ‘limit’ parameter.
Parameters: - urls (tuple|list) – The urls to listify.
- limit (int) – A limit to the number of urls to listify.
- expanded (bool) – Whether to show expanded or short links.
- both (bool) – Whether to show both short and expanded links.
- pretty (bool) – Whether to format the output.
Returns: A list of lines, ready for input. The length of the returned list will always be at most equal to the limit, if the limit is not None.
-
static
History.process(data)[source]¶ Processes data retrieved from the API.
Given a url, this method returns a History.Url object constisting of the short url, the expanded url and a datetime.datetime object for its date of creation.
Parameters: data (list) – The data from the HTTP request sent in the request() method. Returns: A list of History.Url objects.
-
History.ranges(urls, ranges, limit, expanded, both, pretty)[source]¶ Formats and filters history for certain time ranges.
Parameters: - urls (list|tuple) – The original/full list of urls.
- ranges (tuple) – The time-ranges of schema (span1, unit1, span2, unit2).
- limit (int) – A limit to the number of links to pick for each time-range.
- expanded (bool) – Whether to show expanded or short links.
- both (bool) – Whether to show both expanded and short links.
- pretty (bool) – Whether to prettify the output.
Returns: A plain list of lines ready if pretty is false, else the same list of lines with a header (e.g. ‘Between 7 months and 5 days ago:’), plus an empty line for padding.
-
History.ranges_header(time_range, urls)[source]¶ Returns a header for a time-range.
Parameters: - time_range (tuple) – The time-range following the schema (span1, unit1, span2, unit2).
- urls (list|tuple) – The urls, to check if empty.
Returns: A header of the schema ‘Between <span1> [<unit1>] and <span2> <unit2>’, where <unit1> is only included if it not equal to <unit2>, i.e. ‘Between 3 days and 2 days ago’ is transformed to ‘Between 3 and 2 days ago’. If the urls are empty, ‘ None’ is appended to the header.
-
lnk.googl.info module¶
Information-retrieval for goo.gl link.
-
class
lnk.googl.info.Info(raw=False)[source]¶ Bases:
lnk.googl.command.CommandClass to retrieve information about a goo.gl link.
Information about a link may include when it was created, its expanded url and its status. This information is returned in a pretty list. The list can be put into a box for terminal output, or can be returned raw for internal use (such as by the stats command).
Note
A ‘goo.gl link’ is a link shortened with bit.ly.
-
raw¶ bool
Whether or not to return the output as a raw list, or as a string, in a box.
-
sets¶ dict
A complete dictionary of the available sets of information.
-
reverse¶ dict
A reverse mapping of the above-mentioned sets.
-
fetch(only, hide, urls)[source]¶ Fetches the link information.
Parameters: - only (tuple) – A tuple of strings representing the sets to include in the response (‘only’ these will be included).
- hide (tuple) – A tuple of strings representing the sets to hide from the response (either from all possible sets if only is empty, or else from those selected).
- urls (tuple) – A tuple of urls to fetch information for.
Returns: A plain list of the raw lines if the ‘raw’ attribute is True, else a boxified, pretty string.
-
format(key, value)[source]¶ Handles formatting of a data-point.
Handles parsing of the ISO-8601-formatted timestamp from Google’s API into a proper string-representation (ctime). Also formats the key-value pair.
Parameters: - key (str) – The key of the data-point.
- value (str) – The value of the data-point.
Returns: <value>’.
Return type: A formatted string of the schema ‘<key>
-
get_info(sets, result)[source]¶ Requests all information about a url.
This method is run in a separate thread for each URL, and as such uses a queue to get a URL and then appends the information to the list supplied in the argument. This is done in a thread-safe, locked way.
Parameters: - sets (dict) – The sets of information to include in the data.
- result (list) – The list of results for each URL, to which to append the data requested.
-
lineify(url, data)[source]¶ Returns a list of lines for given (information) data.
The lines returned include a header with the relevant URL, followed by string-formatted key/value pairs.
Parameters: - url (str) – The URL of which the data should be formatted.
- data (dict) – The data (information) for the url.
Returns: A list of lines, ready for output.
-
lnk.googl.key module¶
Handles the oauth2 authorization procedure for the goo.gl API.
-
class
lnk.googl.key.Key(raw=False)[source]¶ Bases:
lnk.googl.command.CommandHandles oauth2 authorization for the goo.gl API.
The authorization procedure involves exchaning a temporary authorization code for an oauth2 token. When executing this command, the user will be redirected to a web-page where he or she can authorize lnk to access his or her private goo.gl information. Once done the user gets an authorization-code which he or she must then paste into the command-line, where it is fetched by lnk and stored for authorization during HTTP requests.
-
raw¶ bool
Whether or not to return the raw output for internal use or the prettified output for outside representation.
-
flow¶ oauth2client.client.OAuth2WebServerFlow
An object from Google’s API-library that is used for the entire authorization-code-to-oauth2-token exchange procedure.
-
credentials_path¶ str
The path to the credentials file in the config folder.
-
lnk.googl.link module¶
lnk.googl.stats module¶
Statistics and metrics retrieval for goo.gl.
-
class
lnk.googl.stats.Stats(raw=False)[source]¶ Bases:
lnk.googl.command.CommandClass to retrieve statistics and info for one or more goo.gl links.
The statistics for a link include its referrers (i.e. from where the link was opened), the countries from where the link was opened, the browsers in which the link was opened, the platforms (operating systems) from which the link was opened and of course the number of clicks. These statistics can be retrieved ‘since-forever’, but also for specific (possibly open-ended) time-ranges, such as for ‘the last 5 months’ or ‘between 4 days and 2 minute ago’. Additionally, these statistics can be paired with information about each link, retrieved from the ‘info’ command, thereby making the stats command the ultimate destination for link statistics and information. Output may, as always, be in raw format for internal use or in a pretty box. Multiple URLs are fully supported.
-
raw¶ bool
Whether to return the output in raw format for internal use, or in a pretty string-representation for outside-display.
-
fetch(only, hide, times, forever, limit, add_info, full, urls)[source]¶ Fetches statistics for one or more URLs.
Parameters: - only (tuple) – A tuple of strings representing the sets to include in the response (‘only’ these will be included).
- hide (tuple) – A tuple of strings representing the sets to hide from the response (either from all possible sets if only is empty, or else from those selected).
- times (tuple) – A tuple of tuples of the schema (<span>, <unit>), representing the timespans for which to fetch statistics.
- forever (bool) – Whether to include the statistics ‘since forever’.
- limit (int) – A limit on the number of items fetched per timespan.
- add_info (bool) – Whether or not to add additional information for each link.
- full (bool) – Whether to show full country names, or short ISO abbreviations.
- urls (tuple) – A tuple of urls to fetch statistics for.
Returns: A plain list of the raw lines if the ‘raw’ attribute is True, else a boxified, pretty string.
-
static
format(key, value)[source]¶ Formats a key/value pair for output.
Handles special cases for key-names and formats the key-value pair.
Parameters: - key (str) – The key of the data-point.
- value (str) – The value of the data-point.
Returns: A pretty key-value string-representation.
-
get_header(timespan)[source]¶ Formats timespan headers.
Among other things, this method takes care of the ‘forever’ timespan, whose name to the goo.gl API is ‘allTime’. Before returning a header, it is formatted using ecstasy into a proper, pretty list-item.
-
get_stats(results, sets, timespans, add_info, full, limit)[source]¶ Retrieves the statistics for a single url.
The statistics returned are for all timespans supplied, filtered according to the sets of statistics wanted.
Parameters: - results (list) – The list of results to which to append the retreived data.
- sets (tuple) – The sets of statistics wanted in the response (others are discarded).
- timespans (tuple) – A tuple of tuples of the schema (<span>, <unit>), representing the timespans for which to fetch statistics.
- add_info (bool) – Whether to add information about each url alongside statistics.
- full (bool) – Whether to show full country names or short ISO abbreviations.
- limit (int) – A limit to the number of data-points selected for each timespan.
-
get_timespans(times, forever)[source]¶ Parses timespans.
The timespans passed to the command-line interface and ultimately to the fetch() method are of the schema ‘(<span>, <unit>)’. These are parsed such that special cases are handled, e.g. if the ‘forever’ flag is set, the timespan ‘allTime’ is added for the goo.gl API. If no timespans were passed to the method, the default timespan is retrieved from the command’s configuration settings.
Parameters: - times (tuple) – The timespans of the schema ‘(<span>, <unit>)’.
- forever (bool) – Whether to include the ‘since forever’ timespan.
Returns: A set of timespans (string-representations thereof).
-
lineify(data, sets, timespans, full, limit)[source]¶ Turns the data retrieved for a link into a list of lines.
Information about the URL is formatted and turned into header-lines here, the statistics are entirely parsed in the listify() method.
Parameters: - data (dictionary) – The data (statistics) to lineify.
- sets (tuple) – The names of the sets to include in the output.
- timespans (tuple) – The timespans for which to include data.
- full (bool) – Whether to show full country names or short ISO abbreviations (e.g. ‘Germany’ or ‘DE’).
- limit (int) – A limit on the number of data-points retrieved per timespan.
Returns: A list of lines, ready for output.
-
listify(data, sets, timespans, full, limit)[source]¶ Formats data with multiple data-points into a pretty list.
Each category is formatted into a header. For each timespan of a given category, a list is created if the category holds multiple data-points. Lines containing timespans and data-points are formatted into list-items using ecstasy.
Parameters: - data (dictionary) – The data (statistics) to lineify.
- sets (tuple) – The names of the sets to include in the output.
- timespans (tuple) – The timespans for which to include data.
- full (bool) – Whether to show full country names or short ISO abbreviations (e.g. ‘Germany’ or ‘DE’).
- limit (int) – A limit on the number of data-points retrieved per timespan.
Returns: A list of lines, ready for output.
-
request(add_info)[source]¶ Requests statistics for a given configuration.
The url for which to retrieve statistics is fetched from the queue attribute (thread-safe).
Parameters: add_info (bool) – Whether to add information about the URL as well. Returns: The dictionary containing the retrieved data. The format of this dictionary is that it contains a ‘URL’ key, as well as all key/value pairs connected to information. It also contains an ‘analytics’ key, whose value are the actual statistics for the URL. These statistics are a dictionary where the keys are the timespans and the values the data for each timespan. This data is then furthermore a dictionary which maps the category/set names to list of data-points. Each data-point’s key is contained in the ‘id’ key (e.g. the name of a country) and the value (always the number of clicks) is found with the ‘count’ key.
-
sub_listify(category, points, limit, full)[source]¶ Handles transforming data for a category into a level-2 list.
While listify handles all data and takes care of formatting timespans, this method handles only data for a single category. Because this data is on the second level of each list (0th level is the category, 1st is the timespan and 2nd are the data-points), it is formatted differently than the data on level-1 (the level-1 bullet is a ‘+’, the level-2 bullet a ‘-‘). This method also handles special cases for key-names and also country-name expansion.
Parameters: - category (str) – The name of the category of this data.
- points (list) – The data points for this category (the list contains dictionaries with the keys ‘id’ and ‘count’).
- limit (int) – A limit on the number of data-points retrieved per timespan.
- full (bool) – Whether to show full country names or short ISO abbreviations (e.g. ‘Germany’ or ‘DE’).
-