示例#1
0
def test_fixConfigOwnerships():
    configfile = open(Auth.config, "w")
    configfile.close()

    assert Utils.GetLPID() != os.stat(Auth.config).st_gid
    assert True == Utils.FixFilePermissions(Auth.config)[1]
    assert Utils.GetLPID() == os.stat(Auth.config).st_gid
示例#2
0
    def AddAccount(storage, userid=None, permissions=None):
        """Adds an account to the configuration file with an interactive dialog.

        Args:
          storage: storage, instance of storage to store credentials in.
          userid: string, reference for the account
          permissions: string or iterable of strings, scope(s) of the credentials being requested

        Returns:
          credentials: A credentials instance with the account details
        """
        if permissions is None:
            permissions = Auth.normal_permissions

        if userid is None:
            userid = raw_input(
                "Name for this user account ( eg [email protected] )? ")

            # setup storage again if just got userid now
            storage = multistore_file.get_credential_storage(
                Auth.config,
                Auth.clientid,
                userid,
                permissions)
        url = None
        while True:
            if Utils.hasGUI():
                url = Auth.SetupHttpReturnServer()
            Auth.code = None
            flow, auth_uri = Auth.AddAccountStep1(userid, permissions, url)
            message = "Open this URL if it doesn't, grant access to CUPS Cloud Print "
            message += "( for the " + userid + " account ), "
            message += "then provide the code displayed : \n\n"
            message += auth_uri + "\n"
            print message
            Utils.openBrowserWithUrl(auth_uri)
            if url is not None:
                from select import select
                print 'Code from Google: '
                while (Auth.code is None):
                    result, _, _ = select([sys.stdin], [], [], 0.5)
                    if result and Auth.code is None:
                        s = sys.stdin.readline()
                        if s != "":
                            Auth.code = s
                Auth.httpd.shutdown()
            else:
                Auth.code = raw_input('Code from Google: ')

            try:
                credentials = Auth.AddAccountStep2(userid, flow, Auth.code, storage, permissions)
                return credentials
            except Exception as e:
                message = "\nThe code does not seem to be valid ( "
                message += str(e) + " ), please try again.\n"
                print message
示例#3
0
    def AddAccount(storage, userid=None, permissions=None):
        """Adds an account to the configuration file with an interactive dialog.

        Args:
          storage: storage, instance of storage to store credentials in.
          userid: string, reference for the account
          permissions: string or iterable of strings, scope(s) of the credentials being requested

        Returns:
          credentials: A credentials instance with the account details
        """
        if permissions is None:
            permissions = Auth.normal_permissions

        if userid is None:
            userid = raw_input(
                "Name for this user account ( eg [email protected] )? ")

            # setup storage again if just got userid now
            storage = multistore_file.get_credential_storage(
                Auth.config, Auth.clientid, userid, permissions)
        url = None
        while True:
            if Utils.hasGUI():
                url = Auth.SetupHttpReturnServer()
            Auth.code = None
            flow, auth_uri = Auth.AddAccountStep1(userid, permissions, url)
            message = "Open this URL if it doesn't, grant access to CUPS Cloud Print "
            message += "( for the " + userid + " account ), "
            message += "then provide the code displayed : \n\n"
            message += auth_uri + "\n"
            print message
            Utils.openBrowserWithUrl(auth_uri)
            if url is not None:
                from select import select
                print 'Code from Google: '
                while (Auth.code is None):
                    result, _, _ = select([sys.stdin], [], [], 0.5)
                    if result and Auth.code is None:
                        s = sys.stdin.readline()
                        if s != "":
                            Auth.code = s
                Auth.httpd.shutdown()
            else:
                Auth.code = raw_input('Code from Google: ')

            try:
                credentials = Auth.AddAccountStep2(userid, flow, Auth.code,
                                                   storage, permissions)
                return credentials
            except Exception as e:
                message = "\nThe code does not seem to be valid ( "
                message += str(e) + " ), please try again.\n"
                print message
def test_StdInToTempFile():
    testdata = 'oux3ooquoideereeng5A'
    mockstdin = open('/tmp/stdintest', 'wb')
    mockstdin.write(testdata)
    mockstdin.close()
    mockstdin = open('/tmp/stdintest', 'r')
    tempfile = Utils.StdInToTempFile(1, 'testuser', stdin=mockstdin)
    assert Utils.ReadFile(tempfile) == testdata
    mockstdin.close()
    os.unlink('/tmp/stdintest')
    os.unlink(tempfile)
def test_GetWindowSize():
    # expect this to fail gracefully if no tty
    assert Utils.GetWindowSize() == None

    # pass in dummy winsize struct
    dummywinsize = struct.pack('HHHH', 800, 600, 0, 0)
    assert Utils.GetWindowSize(dummywinsize) == (800,600)

    # ensure window size of 0x0 returns none
    dummywinsize = struct.pack('HHHH', 0, 0, 0, 0)
    assert Utils.GetWindowSize(dummywinsize) == None
def test_base64encode():
    Utils.WriteFile('/tmp/testfile', 'data') == True
    assert Utils.Base64Encode('/tmp/testfile') == '/tmp/testfile.b64'
    assert Utils.ReadFile(
        '/tmp/testfile.b64') == 'data:application/octet-stream;base64,ZGF0YQ=='
    os.unlink('/tmp/testfile.b64')

    os.mkdir('/tmp/testfile.b64')
    assert Utils.Base64Encode('/tmp/testfile') is None
    os.unlink('/tmp/testfile')
    os.rmdir('/tmp/testfile.b64')

    assert Utils.Base64Encode('/tmp/testfile/dsiahdisa') is None
示例#7
0
def test_fixConfigPermissions():
    configfile = open(Auth.config, "w")
    configfile.close()

    os.chmod(Auth.config, 0000)
    assert '0000' == oct(os.stat(Auth.config)[stat.ST_MODE])[-4:]
    assert True == Utils.FixFilePermissions(Auth.config)[0]
    assert '0660' == oct(os.stat(Auth.config)[stat.ST_MODE])[-4:]

    origconfig = Auth.config
    Auth.config = '/tmp/filethatdoesntexist'
    assert (False, False) == Utils.FixFilePermissions(Auth.config)
    Auth.config = origconfig
示例#8
0
    def AddAccount(storage, userid=None):
        """Adds an account to the configuration file

        Args:
          storage: storage, instance of storage to store credentials in.
          userid: string, reference for the account

        Returns:
          credentials: A credentials instance with the account details
        """
        if userid == None:
            userid = raw_input(
                "Name for this user account ( eg [email protected] )? ")

        while True:
            flow = client.OAuth2WebServerFlow(
                client_id=Auth.clientid,
                client_secret=Auth.clientsecret,
                scope=['https://www.googleapis.com/auth/cloudprint'],
                user_agent=userid)
            auth_uri = flow.step1_get_authorize_url()
            print "Open this URL, grant access to CUPS Cloud Print, then provide the code displayed : \n\n" + auth_uri + "\n"
            code = raw_input('Code from Google: ')
            try:
                print ""
                credentials = flow.step2_exchange(code)
                storage.put(credentials)

                # fix permissions
                Utils.FixFilePermissions(Auth.config)

                return credentials
            except Exception as e:
                print "\nThe code does not seem to be valid ( " + str(
                    e) + " ), please try again.\n"
示例#9
0
def test_submitJobFileCreationFails():
    global printers, printerManagerInstance
    printer = printers[0]
    connection = cups.Connection()
    testprintername = printerManagerInstance.sanitizePrinterName(
        printer['name'])

    # get test ppd
    ppdid = 'MFG:Google;DRV:GCP;CMD:POSTSCRIPT;DES:GoogleCloudPrint;MDL'
    ppds = connection.getPPDs(ppd_device_id=ppdid)
    printerppdname, printerppd = ppds.popitem()

    assert printerManagerInstance.addPrinter(printer['name'], printer,
                                             connection, "test location",
                                             printerppdname) is not None

    # test failure of print job because b64 version of file exists
    Utils.WriteFile('testing/testfiles/Test Page.pdf.b64', 'test')
    os.chmod('testing/testfiles/Test Page.pdf.b64', 0)
    assert printer.submitJob('pdf', 'testing/testfiles/Test Page.pdf',
                             'Test Page', testprintername) == False
    os.unlink('testing/testfiles/Test Page.pdf.b64')

    # delete test printer
    connection.deletePrinter(testprintername)
def test_SetupLogging():
    testLogFile = '/tmp/testccp.log'
    assert os.path.exists(testLogFile) == False
    assert Utils.SetupLogging(testLogFile) == True
    logging.error('test_setupLogging error test')
    assert os.path.exists(testLogFile) == True
    os.unlink(testLogFile)
示例#11
0
    def AddAccountStep2(userid, flow, code, storage=None, permissions=None):
        """Executes step 2 of OAuth2WebServerFlow, without interaction.

        Args:
          userid: string, reference for the account
          permissions: string or iterable of strings, scope(s) of the credentials being requested
          storage: storage, instance of storage to store credentials in.
          flow: OAuth2WebServerFlow, flow instance
          code: string, code representing user granting CCP permission to call GCP API for user

        Returns:
          credentials: A credentials instance with the account details
        """
        if permissions is None:
            permissions = Auth.normal_permissions

        if storage is None:
            storage = multistore_file.get_credential_storage(
                Auth.config, Auth.clientid, userid, permissions)

        credentials = flow.step2_exchange(code)
        storage.put(credentials)

        Utils.FixFilePermissions(Auth.config)

        return credentials
示例#12
0
def test_SetupLoggingDefault():
    testLogFile = '/tmp/testccp.log'
    assert os.path.exists(testLogFile) is False
    Utils.logpath = testLogFile
    assert Utils.SetupLogging() is True
    logging.error('test_setupLogging error test')
    assert os.path.exists(testLogFile) is True
    os.unlink(testLogFile)
示例#13
0
def test_getLPID():
    assert int(Utils.GetLPID()) > 0
    assert Utils.GetLPID() != None

    import grp

    workingPrintGroupName = 'lp'
    try:
        grp.getgrnam(workingPrintGroupName)
    except:
        workingPrintGroupName = 'cups'
        pass

    assert Utils.GetLPID('brokendefault', 'brokenalternative', False) == None
    assert int(Utils.GetLPID('brokendefault', workingPrintGroupName,
                             False)) > 0
    assert Utils.GetLPID('brokendefault', workingPrintGroupName, False) != None
示例#14
0
def test_setupAuthOwnership():
    assert Auth.SetupAuth(False, testUserIds=['test']) == (False, False)

    # ensure ownership is correct after creating config
    assert Utils.GetLPID() == os.stat(Auth.config).st_gid

    # add dummy details
    storage = multistore_file.get_credential_storage(
        Auth.config, Auth.clientid, 'testuseraccount',
        ['https://www.googleapis.com/auth/cloudprint'])

    credentials = client.OAuth2Credentials(
        'test', Auth.clientid, 'testsecret', 'testtoken', 1,
        'https://www.googleapis.com/auth/cloudprint', 'testaccount1')
    storage.put(credentials)

    # ensure ownership is correct after populating config
    assert Utils.GetLPID() == os.stat(Auth.config).st_gid
def test_GetLanguage():
    assert Utils.GetLanguage(['en_GB',]) == "en"
    assert Utils.GetLanguage(['en_US',]) == "en"
    assert Utils.GetLanguage(['fr_CA',]) == "fr"
    assert Utils.GetLanguage(['fr_FR',]) == "fr"
    assert Utils.GetLanguage(['it_IT',]) == "it"
    assert Utils.GetLanguage(['en',]) == "en"
    assert Utils.GetLanguage([None,None]) == "en"
示例#16
0
def test_GetDefaultPaperType():
    assert Utils.GetDefaultPaperType('en_GB') == "A4"
    assert Utils.GetDefaultPaperType('en_US') == "Letter"
    assert Utils.GetDefaultPaperType('en_gb') == "A4"
    assert Utils.GetDefaultPaperType('en_us') == "Letter"
    assert Utils.GetDefaultPaperType('de_DE') == "A4"
    assert Utils.GetDefaultPaperType('es_MX') == "Letter"
    assert Utils.GetDefaultPaperType('') == "Letter"
def test_getLPID():
    assert int(Utils.GetLPID()) > 0
    assert Utils.GetLPID() is not None

    import grp

    workingPrintGroupName = 'lp'
    try:
        grp.getgrnam(workingPrintGroupName)
    except:
        workingPrintGroupName = 'cups'
        pass

    assert Utils.GetLPID('brokendefault', 'brokenalternative', False) is None
    assert int(
        Utils.GetLPID(
            'brokendefault',
            workingPrintGroupName,
            False)) > 0
    assert Utils.GetLPID(
        'brokendefault',
        workingPrintGroupName,
        False) is not None

    # test blacklist works
    assert Utils.GetLPID(
        workingPrintGroupName,
        'brokenalternative',
        True,
        [workingPrintGroupName,
         'brokendefault',
         'adm',
         'wheel',
         'root'],
        True) is None
示例#18
0
def test_setupAuth():
    testUserName = '******'

    # ensure setup with no details doesnt create file
    assert os.path.exists(Auth.config) is False
    assert Auth.SetupAuth(False) == (False, False)
    assert os.path.exists(Auth.config) is True
    assert Utils.ReadFile(Auth.config) == "{}"

    os.unlink(Auth.config)

    # create initial file
    assert os.path.exists(Auth.config) is False
    assert Auth.SetupAuth(False, testUserIds=['test']) == (False, False)
    assert os.path.exists(Auth.config) is True

    # ensure permissions are correct after creating config
    assert '0660' == oct(os.stat(Auth.config)[stat.ST_MODE])[-4:]

    # add dummy details
    storage = multistore_file.get_credential_storage(
        Auth.config, Auth.clientid, 'testuseraccount',
        ['https://www.googleapis.com/auth/cloudprint'])

    credentials = client.OAuth2Credentials(
        'test', Auth.clientid, 'testsecret', 'testtoken', 1,
        'https://www.googleapis.com/auth/cloudprint', testUserName)
    storage.put(credentials)

    # ensure permissions are correct after populating config
    assert '0660' == oct(os.stat(Auth.config)[stat.ST_MODE])[-4:]

    # re-run to test getting credentials
    requestors, storage = Auth.SetupAuth(False)
    assert requestors is not None
    assert storage is not None

    # check deleting account
    assert Auth.DeleteAccount(testUserName) is None
    requestors, storage = Auth.SetupAuth(False)
    assert requestors is False
    assert storage is False
示例#19
0
    def submitJob(self, jobtype, jobfile, jobname, cupsprintername, options=""):
        """Submits a job to printerid with content of dataUrl.

        Args:
          jobtype: string, must match the dictionary keys in content and content_type.
          jobfile: string, points to source for job. Could be a pathname or id string.
          jobname: string, name of the print job ( usually page name ).
          options: string, key-value pair of options from print job.

        Returns:
          True if submitted, False otherwise
        """
        rotate = 0

        for optiontext in options.split(' '):

            # landscape
            if optiontext == 'landscape':
                # landscape
                rotate = 90

            # nolandscape - already rotates
            if optiontext == 'nolandscape':
                # rotate back
                rotate = 270

        if jobtype == 'pdf':
            if not os.path.exists(jobfile):
                print "ERROR: PDF doesnt exist"
                return False
            if rotate > 0:
                command = [self._CONVERTCOMMAND, '-density', '300x300', jobfile.lstrip('-'),
                           '-rotate', str(rotate), jobfile.lstrip('-')]
                p = subprocess.Popen(command, stdout=subprocess.PIPE)
                output = p.communicate()[0]
                if not Utils.fileIsPDF(jobfile):
                    print "ERROR: Failed to rotate PDF"
                    logging.error("Rotated PDF, but resulting file was not a PDF")
                    logging.error(output)
                    return False
            b64file = Utils.Base64Encode(jobfile)
            if b64file is None:
                print "ERROR: Cannot write to file: " + jobfile + ".b64"
                return False
            fdata = Utils.ReadFile(b64file)
            os.unlink(b64file)
        elif jobtype in ['png', 'jpeg']:
            if not os.path.exists(jobfile):
                print "ERROR: File doesnt exist"
                return False
            fdata = Utils.ReadFile(jobfile)
        else:
            print "ERROR: Unknown job type"
            return False

        if jobname == "":
            title = "Untitled page"
        else:
            title = jobname

        content = {'pdf': fdata,
                   'jpeg': jobfile,
                   'png': jobfile}
        content_type = {'pdf': 'dataUrl',
                        'jpeg': 'image/jpeg',
                        'png': 'image/png'}
        headers = [
            ('printerid', self['id']),
            ('title', title),
            ('content', content[jobtype]),
            ('contentType', content_type[jobtype]),
            ('capabilities', json.dumps(self._getCapabilities(cupsprintername, options)))
        ]
        logging.info('Capability headers are: %s', headers[4])
        data = self._encodeMultiPart(headers)

        try:
            responseobj = self.getRequestor().submit(data, self._getMimeBoundary())
            if responseobj['success']:
                return True
            else:
                print 'ERROR: Error response from Cloud Print for type %s: %s' %\
                    (jobtype, responseobj['message'])
                return False

        except Exception as error_msg:
            print 'ERROR: Print job %s failed with %s' % (jobtype, error_msg)
            return False
示例#20
0
    if len(sys.argv) == 2 and sys.argv[1] == 'version':
        # line below is replaced on commit
        CCPVersion = "20140223 234321"
        print "CUPS Cloud Print CUPS Backend Version " + CCPVersion
        sys.exit(0)

    libpath = "/usr/local/share/cloudprint-cups/"
    if not os.path.exists( libpath  ):
        libpath = "/usr/share/cloudprint-cups"
    sys.path.insert(0, libpath)

    from auth import Auth
    from printer import Printer
    from ccputils import Utils
    
    Utils.SetupLogging()
    
    requestors, storage = Auth.SetupAuth(False)
    if requestors == False:
        sys.stderr.write("ERROR: config is invalid or missing\n")
        logging.error("backend tried to run with invalid config");
        sys.exit(1)
    printer = Printer(requestors)
    printers = printer.getPrinters()

    if len(sys.argv) == 1:
        print printer.getBackendDescription()

        try:
            if printers != None:
                for foundprinter in printers:
示例#21
0
def test_whichFails():
    assert Utils.which("dsaph9oaghd9ahdsadsadsadsadasd") == None
def test_fileIsPDFErrors():
    assert Utils.fileIsPDF("testdata") is False
示例#23
0
    def SetupAuth(interactive=False,
                  permissions=['https://www.googleapis.com/auth/cloudprint']):
        """Sets up requestors with authentication tokens

        Args:
          interactive: boolean, when set to true can prompt user, otherwise returns False if authentication fails

        Returns:
          requestor, storage: Authenticated requestors and an instance of storage
        """
        modifiedconfig = False

        # parse config file and extract useragents, which we use for account names
        userids = []
        if os.path.exists(Auth.config):
            content_file = open(Auth.config, 'r')
            content = content_file.read()
            data = json.loads(content)
            for user in data['data']:
                userids.append(str(user['credential']['user_agent']))
        else:
            modifiedconfig = True

        if len(userids) == 0:
            userids = [None]

        requestors = []
        for userid in userids:
            storage = multistore_file.get_credential_storage(
                Auth.config, Auth.clientid, userid, permissions)
            credentials = storage.get()

            if not credentials and interactive:
                credentials = Auth.AddAccount(storage, userid)
                modifiedconfig = True
                if userid == None:
                    userid = credentials.user_agent

            if credentials:
                # renew if expired
                requestor = cloudprintrequestor()
                if credentials.access_token_expired:
                    from oauth2client.client import AccessTokenRefreshError
                    try:
                        credentials.refresh(requestor)
                    except AccessTokenRefreshError as e:
                        sys.stderr.write(
                            "Failed to renew token (error: " + str(e) +
                            "), if you have revoked access to CUPS Cloud Print in your Google Account, please delete /etc/cloudprint.conf and re-run /usr/share/cloudprint-cups/setupcloudprint.py\n"
                        )
                        sys.exit(1)

                requestor = credentials.authorize(requestor)
                requestor.setAccount(userid)
                requestors.append(requestor)

        # fix permissions
        if modifiedconfig:
            Utils.FixFilePermissions(Auth.config)

        if not credentials:
            return False, False
        else:
            return requestors, storage
示例#24
0
    def generatePPD(self):
        """Generates a PPD string for this printer."""
        defaultlocale = locale.getdefaultlocale()
        language, newlocale = Utils.GetLanguage(defaultlocale,
                                                self._cupsHelper)
        defaultpapertype = Utils.GetDefaultPaperType(newlocale)
        ppd = self._PPD_TEMPLATE_HEAD % {
            'language': language,
            'defaultpapertype': defaultpapertype,
            'ieee1284': self.getIEEE1284(),
            'ppdname': self.getPPDName()
        }
        if self['capabilities'] is not None:
            addedCapabilities = []
            for capability in self['capabilities']:
                originCapabilityName = None
                internalCapabilityName = \
                    self._getInternalName(capability, 'capability', None, addedCapabilities)
                addedCapabilities.append(internalCapabilityName)
                if 'displayName' in capability and len(
                        capability['displayName']) > 0:
                    originCapabilityName = self._sanitizeText(
                        capability['displayName'])
                elif 'psk:DisplayName' in capability and len(
                        capability['psk:DisplayName']) > 0:
                    originCapabilityName = self._sanitizeText(
                        capability['psk:DisplayName'])
                else:
                    originCapabilityName = self._sanitizeText(
                        capability['name'])
                if capability['type'] == 'Feature':
                    ppd += '*OpenUI *%s/%s: PickOne\n' % \
                        (internalCapabilityName, internalCapabilityName)
                    # translation of capability, allows use of 8
                    # bit chars
                    ppd += '*%s.Translation %s/%s: ""\n' % \
                        (language, internalCapabilityName, originCapabilityName)
                    addedOptions = []
                    for option in capability['options']:
                        originOptionName = None
                        if 'displayName' in option and len(
                                option['displayName']) > 0:
                            originOptionName = self._sanitizeText(
                                option['displayName'])
                        elif 'psk:DisplayName' in option and len(
                                option['psk:DisplayName']) > 0:
                            originOptionName = self._sanitizeText(
                                option['psk:DisplayName'])
                        else:
                            originOptionName = self._sanitizeText(
                                option['name'])
                        internalOptionName = self._getInternalName(
                            option, 'option', capability['name'], addedOptions)
                        addedOptions.append(internalOptionName)
                        if 'default' in option and option['default']:
                            ppd += '*Default%s: %s\n' % (
                                internalCapabilityName, internalOptionName)
                        ppd += '*%s %s:%s\n' % \
                            (internalCapabilityName, internalOptionName, internalOptionName)
                        # translation of option, allows use of 8
                        # bit chars
                        value = ''
                        if 'ppd:value' in option:
                            value = option['ppd:value']
                        ppd += '*%s.%s %s/%s: "%s"\n' % (
                            language, internalCapabilityName,
                            internalOptionName, originOptionName, value)

                    ppd += '*CloseUI: *%s\n' % internalCapabilityName

        ppd += self._PPD_TEMPLATE_FOOT
        return ppd
def test_whichSucceeds():
    assert Utils.which(
        'bash') in (
        '/bin/bash',
        '/usr/bin/bash',
        '/usr/sbin/bash')
示例#26
0
        Utils.FixFilePermissions(Auth.config)

        try:
            content_file = open(Auth.config, 'r')
            content = content_file.read()
            data = json.loads(content)
        except Exception, e:
            sys.stderr.write("Unable to read config file: " + e.message +"\n\n")
            sys.exit(0)

    else:
        sys.stderr.write("\nRun: /usr/share/cloudprint-cups/setupcloudprint.py to setup your Google Credentials and add your printers to CUPS\n\n")
        sys.exit(0)

    from ccputils import Utils
    if Utils.which('lpadmin') == None:
        sys.stderr.write("lpadmin command not found, you may need to run this script as root\n")
        sys.exit(1)

    try:
        print "Fetching list of available ppds..."
        allppds = connection.getPPDs()
        print "List retrieved successfully"
    except Exception, e:
        sys.stderr.write("Error connecting to CUPS: " + str(e) + "\n")
        sys.exit(1)

    for device in cupsprinters:
        try:
            if ( cupsprinters[device]["device-uri"].find("cloudprint://") == 0 ):
                printername, account, printerid = printerItem.parseURI(cupsprinters[device]["device-uri"])
示例#27
0
def test_fileIsPDFSucceeds():
    assert Utils.fileIsPDF("testfiles/Test Page.pdf") == True
示例#28
0
def test_whichFails():
    assert Utils.which('dsaph9oaghd9ahdsadsadsadsadasd') is None
示例#29
0
    if len(sys.argv) == 2 and sys.argv[1] == 'version':
        # line below is replaced on commit
        CCPVersion = "20140223 234321"
        print "CUPS Cloud Print Issue Reporting Script Version " + CCPVersion
        sys.exit(0)

    libpath = "/usr/local/share/cloudprint-cups/"
    if not os.path.exists(libpath):
        libpath = "/usr/share/cloudprint-cups"
    sys.path.insert(0, libpath)

    from auth import Auth
    from printer import Printer
    from ccputils import Utils
    Utils.SetupLogging()

    requestors, storage = Auth.SetupAuth(True)
    printer = Printer(requestors)
    printers = printer.getPrinters(True)
    if printers == None:
        print "ERROR: No Printers Found"
        sys.exit(1)

    for foundprinter in printers:
        print '"cupscloudprint:' + foundprinter['account'].encode(
            'ascii', 'replace'
        ).replace(' ', '-') + ':' + foundprinter['name'].encode(
            'ascii', 'replace'
        ).replace(
            ' ', '-'
def test_fileIsPDFFails():
    assert Utils.fileIsPDF(open('testing/testfiles/NotPdf.txt').read()) is False
def test_fileIsPDFSucceeds():
    assert Utils.fileIsPDF(open('testing/testfiles/Test Page.pdf').read(128)) is True
示例#32
0
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

if __name__ == '__main__':  # pragma: no cover

    import sys, cups, subprocess, os, json, logging, urllib
    from oauth2client import client
    from oauth2client import multistore_file
    from auth import Auth

    from ccputils import Utils
    from printer import Printer
    Utils.SetupLogging()

    if not os.path.exists("/etc/cloudprint.conf"):
        sys.stderr.write(
            "Config is invalid or missing, not running on fresh install\n")
        logging.error("Upgrade tried to run on fresh install")
        sys.exit(0)

    requestors, storage = Auth.SetupAuth(False)
    if requestors == False:
        sys.stderr.write("Config is invalid or missing\n")
        logging.error("Upgrade tried to run with invalid config")
        sys.exit(0)
    printerItem = Printer(requestors)

    # line below is replaced on commit
def test_isExeSucceeds():
    if os.path.exists('/usr/bin/sh'):
        assert Utils.is_exe("/usr/bin/sh") == True
    else:
        assert Utils.is_exe("/bin/sh") == True
示例#34
0
            sys.stderr.write(
                "Unable to read config file: " +
                e.message +
                "\n\n")
            sys.exit(0)

    else:
        errormessage = "\nRun: /usr/share/cloudprint-cups/"
        errormessage += "setupcloudprint.py to"
        errormessage += " setup your Google Credentials"
        errormessage += " and add your printers to CUPS\n\n"
        sys.stderr.write(errormessage)
        sys.exit(0)

    from ccputils import Utils
    if Utils.which('lpadmin') is None:
        errormessage = "lpadmin command not found"
        errormessage += ", you may need to run this script as root\n"
        sys.stderr.write(errormessage)
        sys.exit(1)

    try:
        print "Fetching list of available ppds..."
        allppds = connection.getPPDs()
        print "List retrieved successfully"
    except Exception as e:
        sys.stderr.write("Error connecting to CUPS: " + str(e) + "\n")
        sys.exit(1)

    for device in cupsprinters:
        try:
def test_isExeFails():
    assert Utils.is_exe("/dev/null") == False
示例#36
0
def test_whichSucceeds():
    assert Utils.which("bash") in ("/bin/bash", "/usr/bin/bash", "/usr/sbin/bash")
示例#37
0
        copies = 1

    uri = os.getenv('DEVICE_URI')
    cupsprintername = os.getenv('PRINTER')
    if uri is None:
        message = 'URI must be "' + Utils.PROTOCOL + '<account name>/<cloud printer id>"!\n'
        sys.stdout.write(message)
        sys.exit(255)

    logging.info("Printing file %s", printFile)
    optionsstring = ' '.join(["'%s'" % option for option in sys.argv])
    logging.info("Device is %s , printername is %s, params are: %s",
                 uri, cupsprintername, optionsstring)

    pdfFile = printFile + ".pdf"
    if Utils.which("ps2pdf") is None:
        convertToPDFParams = ["pstopdf", printFile, pdfFile]
    else:
        convertToPDFParams = ["ps2pdf", "-dPDFSETTINGS=/printer",
                              "-dUseCIEColor", printFile, pdfFile]

    result = 0

    logging.debug('is this a pdf? %s', printFile)
    if not os.path.exists(printFile):
        sys.stderr.write('ERROR: file "%s" not found\n', printFile)
        result = 1
    elif not Utils.fileIsPDF(printFile):
        sys.stderr.write("INFO: Converting print job to PDF\n")
        if subprocess.call(convertToPDFParams) != 0:
            sys.stderr.write("ERROR: Failed to convert file to pdf\n")
示例#38
0
if __name__ == '__main__':  # pragma: no cover
    import sys
    import os
    import subprocess
    import logging

    libpath = "/usr/local/share/cloudprint-cups/"
    if not os.path.exists(libpath):
        libpath = "/usr/share/cloudprint-cups"
    sys.path.insert(0, libpath)

    from auth import Auth
    from printermanager import PrinterManager
    from ccputils import Utils

    Utils.SetupLogging()

    # line below is replaced on commit
    CCPVersion = "20140814.2 000000"
    Utils.ShowVersion(CCPVersion)

    copies = 1

    if len(sys.argv) != 1 and len(sys.argv) < 6 or len(sys.argv) > 7:
        sys.stderr.write(
            "ERROR: Usage: %s job-id user title copies options [file]\n" %
            sys.argv[0])
        sys.exit(0)

    if len(sys.argv) >= 4 and sys.argv[3] == "Set Default Options":
        sys.stderr.write("ERROR: Unimplemented command: " + sys.argv[3] + "\n")
示例#39
0
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

if __name__ == '__main__':  # pragma: no cover

    import sys
    import cups
    import subprocess
    import os
    import json
    import logging
    import urllib
    from auth import Auth
    from ccputils import Utils
    from printermanager import PrinterManager
    Utils.SetupLogging()

    # line below is replaced on commit
    CCPVersion = "20140705 161213"
    Utils.ShowVersion(CCPVersion)

    if not os.path.exists("/etc/cloudprint.conf"):
        sys.stderr.write(
            "Config is invalid or missing, not running on fresh install\n")
        logging.warning("Upgrade tried to run on fresh install")
        sys.exit(0)

    requestors, storage = Auth.SetupAuth(False)
    if not requestors:
        sys.stderr.write("Config is invalid or missing\n")
        logging.error("Upgrade tried to run with invalid config")
示例#40
0
    def submitJob(self,
                  jobtype,
                  jobfile,
                  jobdata,
                  jobname,
                  cupsprintername,
                  options=""):
        """Submits a job to printerid with content of dataUrl.

        Args:
          jobtype: string, must match the dictionary keys in content and content_type.
          jobfile: string, points to source for job. Could be a pathname or id string.
          jobdata: string, data for print job
          jobname: string, name of the print job ( usually page name ).
          options: string, key-value pair of options from print job.

        Returns:
          True if submitted, False otherwise
        """
        rotate = 0

        # refuse to submit empty jobdata
        if len(jobdata) == 0:
            sys.stderr.write("ERROR: Job data is empty\n")
            return False

        if jobfile is None or jobfile == "":
            jobfile = "Unknown"

        for optiontext in options.split(' '):

            # landscape
            if optiontext == 'landscape':
                # landscape
                rotate = 90

            # nolandscape - already rotates
            if optiontext == 'nolandscape':
                # rotate back
                rotate = 270

        if jobtype not in ['png', 'jpeg', 'pdf']:
            sys.stderr.write("ERROR: Unknown job type: %s\n" % jobtype)
            return False
        else:
            if rotate != 0:
                command = [
                    self._CONVERTCOMMAND, '-density', '300x300', '-',
                    '-rotate',
                    str(rotate), '-'
                ]
                p = subprocess.Popen(command,
                                     stdout=subprocess.PIPE,
                                     stdin=subprocess.PIPE)
                newjobdata = p.communicate(jobdata)[0]
                if p.returncode == 0:
                    jobdata = newjobdata
                else:
                    logging.error("Failed to rotate")
                    return False

        if jobname == "":
            title = "Untitled page"
        else:
            title = jobname
        headers = [('printerid', self['id']), ('title', title),
                   ('content', Utils.Base64Encode(jobdata, jobtype)),
                   ('contentType', 'dataUrl'),
                   ('capabilities',
                    json.dumps(self._getCapabilities(cupsprintername,
                                                     options)))]
        logging.info('Capability headers are: %s', headers[4])
        data = self._encodeMultiPart(headers)

        try:
            responseobj = self.getRequestor().submit(data,
                                                     self._getMimeBoundary())
            if responseobj['success']:
                return True
            else:
                sys.stderr.write(
                    "ERROR: Error response from Cloud Print for type %s: %s\n"
                    % (jobtype, responseobj['message']))
                return False

        except Exception as error_msg:
            sys.stderr.write("ERROR: Print job %s failed with %s\n" %
                             (jobtype, error_msg))
            return False
示例#41
0
if __name__ == '__main__':  # pragma: no cover
    import sys
    import os
    import subprocess
    import logging

    libpath = "/usr/local/share/cloudprint-cups/"
    if not os.path.exists(libpath):
        libpath = "/usr/share/cloudprint-cups"
    sys.path.insert(0, libpath)

    from auth import Auth
    from printermanager import PrinterManager
    from ccputils import Utils

    Utils.SetupLogging()

    # line below is replaced on commit
    CCPVersion = "20140713 215426"
    Utils.ShowVersion(CCPVersion)

    if len(sys.argv) != 1 and len(sys.argv) < 6 or len(sys.argv) > 7:
        sys.stderr.write(
            "ERROR: Usage: %s job-id user title copies options [file]\n" %
            sys.argv[0])
        sys.exit(0)

    if len(sys.argv) >= 4 and sys.argv[3] == "Set Default Options":
        print "ERROR: Unimplemented command: " + sys.argv[3]
        logging.error("Unimplemented command: %s", sys.argv[3])
        sys.exit(0)
示例#42
0
def test_fileIsPDFFails():
    assert Utils.fileIsPDF('testing/testfiles/NotPdf.txt') == False
示例#43
0
    uri = os.getenv('DEVICE_URI')
    cupsprintername = os.getenv('PRINTER')
    if uri is None:
        message = 'URI must be "' + Utils.PROTOCOL + '<account name>/<cloud printer id>"!\n'
        sys.stdout.write(message)
        sys.exit(255)

    logging.info("Printing file %s", str(printFile))
    optionsstring = ' '.join(["'%s'" % option for option in sys.argv])
    logging.info("Device is %s , printername is %s, params are: %s",
                 uri, cupsprintername, optionsstring)

    # setup
    convertToPDFParams = ["ps2pdf", "-dPDFSETTINGS=/printer",
                          "-dUseCIEColor", "-", "-"]
    if Utils.which("ps2pdf") is None:
        convertToPDFParams = ["pstopdf", "-", "-"]

    logging.debug('is this a pdf? ' + str(printFile))
    result = 0

    if not Utils.fileIsPDF(filedata):
        # read file as pdf
        sys.stderr.write("INFO: Converting print job to PDF\n")
        p = subprocess.Popen(convertToPDFParams, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
        filedata = p.communicate(filedata)[0]
        if p.returncode != 0:
            sys.stderr.write("ERROR: Failed to convert file to pdf\n")
            result = 1
        else:
            logging.info("Converted to PDF - %s bytes", str(len(filedata)))
示例#44
0
def test_fileIsPDFSucceeds():
    assert Utils.fileIsPDF('testing/testfiles/Test Page.pdf') == True
示例#45
0
def test_fileIsPDFErrors():
    assert Utils.fileIsPDF("-dsadsa") == False
示例#46
0
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

if __name__ == '__main__':  # pragma: no cover

    import sys
    from auth import Auth
    from printermanager import PrinterManager
    from ccputils import Utils
    Utils.SetupLogging()

    # line below is replaced on commit
    CCPVersion = "20140501 203545"
    Utils.ShowVersion(CCPVersion)

    requestors, storage = Auth.SetupAuth(True)
    printer_manager = PrinterManager(requestors)
    printers = printer_manager.getPrinters()
    if printers is None:
        print "No Printers Found"
        sys.exit(1)

    for printer in printers:
        print printer.getListDescription()
示例#47
0
def test_fileIsPDFFails():
    assert Utils.fileIsPDF("testfiles/NotPdf.txt") == False