<commit_before>"""Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


A class to hold device attributes.

This class is used by the Cloud Print Logo Certification tool, to hold the
attributes of a device. Before the device attributes are fully populated,
the methods GetDeviceDetails and GetDeviceCDD must be run.
"""

import json

from _cloudprintmgr import CloudPrintMgr
from _common import Extract
from _config import Constants
from _jsonparser import JsonParser
import _log
from _privet import Privet
from _transport import Transport


class Device(object):
  """The basic device object."""

  def __init__(self, chromedriver, model=None):
    """Initialize a device object.

    Args:
      chromedriver: an initialized chromedriver object.
      model: string, unique model or name of device.
    """
    if model:
      self.model = model
    else:
      self.model = Constants.PRINTER['MODEL']
    self.logger = _log.GetLogger('LogoCert')
    self.cd = chromedriver
    self.cloudprintmgr = CloudPrintMgr(chromedriver)
    self.ipv4 = Constants.PRINTER['IP']
    self.port = Constants.PRINTER['PORT']
    self.name = None
    self.status = None
    self.messages = []
    self.details = {}
    self.error_state = False
    self.cdd = {}
    self.info = None

    self.url = 'http://%s:%s' % (self.ipv4, self.port)
    self.logger.info('Device URL: %s', self.url)
    self.transport = Transport()
    self.jparser = JsonParser()
    self.headers = None
    self.privet = Privet()
    self.privet_url = self.privet.SetPrivetUrls(self.ipv4, self.port)
    self.GetPrivetInfo()

  def GetPrivetInfo(self):
    self.privet_info = {}
    response = self.transport.HTTPReq(self.privet_url['info'],
                                      headers=self.privet.headers_empty)
    info = self.jparser.Read(response['data'])
    if info['json']:
      for key in info:
        self.privet_info[key] = info[key]
        self.logger.debug('Privet Key: %s', key)
        self.logger.debug('Value: %s', info[key])
        self.logger.debug('--------------------------')
      if 'x-privet-token' in info:
        self.headers = {'X-Privet-Token': str(info['x-privet-token'])}
    else:
      if response['code']:
        self.logger.info('HTTP device return code: %s', response['code'])
      if response['headers']:
        self.logger.debug('HTTP Headers:  ')
        for key in response['headers']:
          self.logger.debug('%s: %s', key, response['headers'][key])
      if response['data']:
        self.logger.info('Data from response: %s', response['data'])

  def GetDeviceDetails(self):
    """Get the device details from our management page.

    This will populate a Device object with device name, status, state messages,
    and device details.
    """
    self.name = self.cloudprintmgr.GetPrinterName(self.model)
    self.status = self.cloudprintmgr.GetPrinterState(self.model)
    self.messages = self.cloudprintmgr.GetPrinterStateMessages(self.model)
    self.details = self.cloudprintmgr.GetPrinterDetails(self.model)
    self.error_state = self.cloudprintmgr.GetPrinterErrorState(self.model)

  def GetDeviceCDD(self, device_id):
    """Get device cdd and populate device object with the details.

    Args:
      device_id: string, Cloud Print device id.
    Returns:
      boolean: True = cdd details populated, False = cdd details not populated.
    """
    self.cd.driver.get(Constants.GCP['SIMULATE'])

    printer_lookup = self.cd.FindID('printer_printerid')
    if not printer_lookup:
      return False
    if not self.cd.SendKeys(device_id, printer_lookup):
      return False
    printer_submit = self.cd.FindID('printer_submit')
    if not self.cd.ClickElement(printer_submit):
      return False
    printer_info = self.cd.FindXPath('html')
    if not printer_info:
      return False
    self.info = printer_info.text
    self.ParseCDD()
    return True

  def ParseCDD(self):
    """Parse the CDD json string into a logical dictionary.

    Returns:
      boolean: True = CDD parsed, False = CDD not parsed.
    """

    cdd = {}
    if self.info:
      cdd = json.loads(self.info)
    else:
      self.logger.warning('Device info is empty.')
      return False
    if 'printers' in cdd:
      for k in cdd['printers'][0]:
        if k == 'capabilities':
          self.cdd['caps'] = {}
        else:
          self.cdd[k] = cdd['printers'][0][k]
    else:
      self.logger.error('Could not find printers in cdd.')
      return False
    for k in cdd['printers'][0]['capabilities']['printer']:
      self.cdd['caps'][k] = cdd['printers'][0]['capabilities']['printer'][k]
    return True

  def CancelRegistration(self):
    """Cancel Privet Registration that is in progress.

    Returns:
      return code from HTTP request.
    """
    cancel_url = self.privet_url['register']['cancel']
    self.logger.debug('Sending request to cancel Privet Registration.')
    response = self.transport.HTTPReq(cancel_url, data='',
                                      headers=self.privet.headers_empty)
    return response['code']

  def StartPrivetRegister(self):
    """Start a device registration using the Privet protocol.

    Returns:
      boolean: True = success, False = errors.
    """

    self.logger.debug('Registering device %s with Privet', self.ipv4)
    response = self.transport.HTTPReq(
        self.privet_url['register']['start'], data='',
        headers=self.headers, user=Constants.USER['EMAIL'])
    return self.transport.LogData(response)

  def GetPrivetClaimToken(self):
    """Attempt to get a Privet Claim Token.

    Returns:
      boolean: True = success, False = errors.
    """<commit_msg>Fixed parameters for canceling Privet registration.<commit_after>"""Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


A class to hold device attributes.

This class is used by the Cloud Print Logo Certification tool, to hold the
attributes of a device. Before the device attributes are fully populated,
the methods GetDeviceDetails and GetDeviceCDD must be run.
"""

import json

from _cloudprintmgr import CloudPrintMgr
from _common import Extract
from _config import Constants
from _jsonparser import JsonParser
import _log
from _privet import Privet
from _transport import Transport


class Device(object):
  """The basic device object."""

  def __init__(self, chromedriver, model=None):
    """Initialize a device object.

    Args:
      chromedriver: an initialized chromedriver object.
      model: string, unique model or name of device.
    """
    if model:
      self.model = model
    else:
      self.model = Constants.PRINTER['MODEL']
    self.logger = _log.GetLogger('LogoCert')
    self.cd = chromedriver
    self.cloudprintmgr = CloudPrintMgr(chromedriver)
    self.ipv4 = Constants.PRINTER['IP']
    self.port = Constants.PRINTER['PORT']
    self.name = None
    self.status = None
    self.messages = []
    self.details = {}
    self.error_state = False
    self.cdd = {}
    self.info = None

    self.url = 'http://%s:%s' % (self.ipv4, self.port)
    self.logger.info('Device URL: %s', self.url)
    self.transport = Transport()
    self.jparser = JsonParser()
    self.headers = None
    self.privet = Privet()
    self.privet_url = self.privet.SetPrivetUrls(self.ipv4, self.port)
    self.GetPrivetInfo()

  def GetPrivetInfo(self):
    self.privet_info = {}
    response = self.transport.HTTPReq(self.privet_url['info'],
                                      headers=self.privet.headers_empty)
    info = self.jparser.Read(response['data'])
    if info['json']:
      for key in info:
        self.privet_info[key] = info[key]
        self.logger.debug('Privet Key: %s', key)
        self.logger.debug('Value: %s', info[key])
        self.logger.debug('--------------------------')
      if 'x-privet-token' in info:
        self.headers = {'X-Privet-Token': str(info['x-privet-token'])}
    else:
      if response['code']:
        self.logger.info('HTTP device return code: %s', response['code'])
      if response['headers']:
        self.logger.debug('HTTP Headers:  ')
        for key in response['headers']:
          self.logger.debug('%s: %s', key, response['headers'][key])
      if response['data']:
        self.logger.info('Data from response: %s', response['data'])

  def GetDeviceDetails(self):
    """Get the device details from our management page.

    This will populate a Device object with device name, status, state messages,
    and device details.
    """
    self.name = self.cloudprintmgr.GetPrinterName(self.model)
    self.status = self.cloudprintmgr.GetPrinterState(self.model)
    self.messages = self.cloudprintmgr.GetPrinterStateMessages(self.model)
    self.details = self.cloudprintmgr.GetPrinterDetails(self.model)
    self.error_state = self.cloudprintmgr.GetPrinterErrorState(self.model)

  def GetDeviceCDD(self, device_id):
    """Get device cdd and populate device object with the details.

    Args:
      device_id: string, Cloud Print device id.
    Returns:
      boolean: True = cdd details populated, False = cdd details not populated.
    """
    self.cd.driver.get(Constants.GCP['SIMULATE'])

    printer_lookup = self.cd.FindID('printer_printerid')
    if not printer_lookup:
      return False
    if not self.cd.SendKeys(device_id, printer_lookup):
      return False
    printer_submit = self.cd.FindID('printer_submit')
    if not self.cd.ClickElement(printer_submit):
      return False
    printer_info = self.cd.FindXPath('html')
    if not printer_info:
      return False
    self.info = printer_info.text
    self.ParseCDD()
    return True

  def ParseCDD(self):
    """Parse the CDD json string into a logical dictionary.

    Returns:
      boolean: True = CDD parsed, False = CDD not parsed.
    """

    cdd = {}
    if self.info:
      cdd = json.loads(self.info)
    else:
      self.logger.warning('Device info is empty.')
      return False
    if 'printers' in cdd:
      for k in cdd['printers'][0]:
        if k == 'capabilities':
          self.cdd['caps'] = {}
        else:
          self.cdd[k] = cdd['printers'][0][k]
    else:
      self.logger.error('Could not find printers in cdd.')
      return False
    for k in cdd['printers'][0]['capabilities']['printer']:
      self.cdd['caps'][k] = cdd['printers'][0]['capabilities']['printer'][k]
    return True

  def CancelRegistration(self):
    """Cancel Privet Registration that is in progress.

    Returns:
      return code from HTTP request.
    """
    cancel_url = self.privet_url['register']['cancel']
    self.logger.debug('Sending request to cancel Privet Registration.')
    response = self.transport.HTTPReq(cancel_url, data='',
                                      headers=self.headers, user=Constants.USER['EMAIL'])
    return response['code']

  def StartPrivetRegister(self):
    """Start a device registration using the Privet protocol.

    Returns:
      boolean: True = success, False = errors.
    """

    self.logger.debug('Registering device %s with Privet', self.ipv4)
    response = self.transport.HTTPReq(
        self.privet_url['register']['start'], data='',
        headers=self.headers, user=Constants.USER['EMAIL'])
    return self.transport.LogData(response)

  def GetPrivetClaimToken(self):
    """Attempt to get a Privet Claim Token.

    Returns:
      boolean: True = success, False = errors.
    """
{'fraction_non_alphanumeric': 0.11721463769286695, 'fraction_numerical': 0.002585023022861297, 'mean_word_length': 3.059016393442623, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2514177', 'n_tokens_mistral': 3700, 'n_tokens_neox': 3647, 'n_words': 1054}