2012-10-18 14:47:30 +02:00
|
|
|
from apiclient.discovery import build
|
2017-02-08 14:06:52 +01:00
|
|
|
from oauth2client.service_account import ServiceAccountCredentials
|
2012-10-18 14:47:30 +02:00
|
|
|
|
2022-05-07 00:59:15 +02:00
|
|
|
from . import utils
|
2012-10-18 14:47:30 +02:00
|
|
|
|
|
|
|
|
2022-05-07 00:59:15 +02:00
|
|
|
def init_service(credentials_file):
|
|
|
|
"""Get a service that communicates to a Google API."""
|
2019-11-22 15:59:22 +01:00
|
|
|
scope = ["https://www.googleapis.com/auth/analytics.readonly"]
|
2017-02-08 14:06:52 +01:00
|
|
|
credentials = ServiceAccountCredentials.from_json_keyfile_name(
|
2022-05-07 00:59:15 +02:00
|
|
|
credentials_file, scopes=scope
|
2017-02-08 14:06:52 +01:00
|
|
|
)
|
2012-10-18 14:47:30 +02:00
|
|
|
|
2022-05-07 00:59:15 +02:00
|
|
|
return build("analytics", "v3", credentials=credentials)
|
2012-10-18 14:47:30 +02:00
|
|
|
|
|
|
|
|
|
|
|
def get_profile_id(service):
|
2022-05-07 00:59:15 +02:00
|
|
|
"""Get static profile ID or fetch one from the service.
|
|
|
|
|
2012-10-18 14:47:30 +02:00
|
|
|
Get the profile ID for this user and the service specified by the
|
|
|
|
'googleanalytics.id' configuration option. This function iterates
|
|
|
|
over all of the accounts available to the user who invoked the
|
|
|
|
service to find one where the account name matches (in case the
|
|
|
|
user has several).
|
2022-05-07 00:59:15 +02:00
|
|
|
|
|
|
|
If not user configured, the first account is used
|
2012-10-18 14:47:30 +02:00
|
|
|
"""
|
2022-05-07 00:59:15 +02:00
|
|
|
|
|
|
|
profile_id = utils.config_profile_id()
|
|
|
|
if profile_id:
|
|
|
|
return profile_id
|
|
|
|
|
2012-10-18 14:47:30 +02:00
|
|
|
accounts = service.management().accounts().list().execute()
|
|
|
|
|
2019-11-22 15:59:22 +01:00
|
|
|
if not accounts.get("items"):
|
2012-10-18 14:47:30 +02:00
|
|
|
return None
|
2022-05-06 18:01:29 +02:00
|
|
|
accountName = utils.config_account()
|
|
|
|
webPropertyId = utils.config_id()
|
2019-11-22 15:59:22 +01:00
|
|
|
for acc in accounts.get("items"):
|
2022-05-07 00:59:15 +02:00
|
|
|
if not accountName or acc.get("name") == accountName:
|
2019-11-22 15:59:22 +01:00
|
|
|
accountId = acc.get("id")
|
2012-10-18 14:47:30 +02:00
|
|
|
|
2019-11-22 15:59:22 +01:00
|
|
|
profiles = (
|
|
|
|
service.management()
|
|
|
|
.profiles()
|
|
|
|
.list(accountId=accountId, webPropertyId=webPropertyId)
|
|
|
|
.execute()
|
|
|
|
)
|
2012-10-18 14:47:30 +02:00
|
|
|
|
2019-11-22 15:59:22 +01:00
|
|
|
if profiles.get("items"):
|
|
|
|
return profiles.get("items")[0].get("id")
|
2012-10-18 14:47:30 +02:00
|
|
|
|
|
|
|
return None
|