コード例 #1
0
ファイル: views.py プロジェクト: gokultg1612/xbeewificloudkit
def monitor_devicecore_setup(request):
    """
    View to handle DeviceCore monitor setup for an user

    Will query for existing monitors, create a new one if none found, else
    kickstart existing monitor.

    Returns the monitor information from Device Cloud
    ------------------------------------------
    """
    username, password, cloud_fqdn = get_credentials(request)

    if not username or not password or not cloud_fqdn:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    conn = DeviceCloudConnector(username, password, cloud_fqdn)

    endpoint_url = reverse(monitor_receiver, request=request)
    # Device cloud won't allow monitors pointing to localhost, etc,
    # so don't even try
    if 'localhost' in endpoint_url or '127.0.0.1' in endpoint_url:
        logger.error('Rejecting attempt to create monitor to ' + endpoint_url)
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        monitors = conn.get_devicecore_monitor(endpoint_url)

        if monitors['resultSize'] == "0":
            # No existing monitors found for this device on this account,
            # create a new one
            # NOTE: The full url is generated by information passed in the
            # request. If the same backend is being routed to from multiple
            # places (reverse proxies, etc), each will generate a different
            # url.
            logger.info('Creating a new DeviceCore monitor for user %s'
                        % username)
            resp = conn.create_devicecore_monitor(
                endpoint_url,
                settings.SECRET_DEVICE_CLOUD_MONITOR_AUTH_USER,
                settings.SECRET_DEVICE_CLOUD_MONITOR_AUTH_PASS,
                description="XBee Wi-Fi Cloud Kit Monitor")
        else:
            # Should only have one monitor for a given device/topic
            if len(monitors['items']) > 1:
                logger.warning("Found multiple monitors for user %s! " +
                               "This should not happen!" % username)

            monitor = monitors['items'][0]
            logger.info(
                'Found an existing DeviceCore monitor for user, kicking it')
            conn.kick_monitor(
                monitor['monId'],
                settings.SECRET_DEVICE_CLOUD_MONITOR_AUTH_USER,
                settings.SECRET_DEVICE_CLOUD_MONITOR_AUTH_PASS)
            # Return the original info
            resp = monitors

    except HTTPError, e:
        return Response(status=e.response.status_code, data=e.response.text)