Skip to content
Permalink
Browse files

Ran autopep8 on code

  • Loading branch information
simoncadman committed Mar 23, 2014
1 parent da4ec54 commit dd042037ef100d3f3b74a3aa672c003220c6167e
61 auth.py
@@ -14,12 +14,15 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import json, os, sys
import json
import os
import sys
from oauth2client import client
from oauth2client import multistore_file
from cloudprintrequestor import cloudprintrequestor
from ccputils import Utils


class Auth:

clientid = "843805314553.apps.googleusercontent.com"
@@ -37,15 +40,16 @@ def DeleteAccount(userid=None):
deleted: boolean , true on success
"""
storage = multistore_file.get_credential_storage(
Auth.config,
Auth.clientid,
userid,
['https://www.googleapis.com/auth/cloudprint'])
Auth.config,
Auth.clientid,
userid,
['https://www.googleapis.com/auth/cloudprint'])
return storage.delete()

DeleteAccount = staticmethod(DeleteAccount)

def AddAccount(storage, userid=None, permissions=['https://www.googleapis.com/auth/cloudprint']):
def AddAccount(storage, userid=None,
permissions=['https://www.googleapis.com/auth/cloudprint']):
"""Adds an account to the configuration file
Args:
@@ -55,14 +59,15 @@ def AddAccount(storage, userid=None, permissions=['https://www.googleapis.com/au
Returns:
credentials: A credentials instance with the account details
"""
if userid == None:
userid = raw_input("Name for this user account ( eg something@gmail.com )? ")
if userid is None:
userid = raw_input(
"Name for this user account ( eg something@gmail.com )? ")

while True:
flow = client.OAuth2WebServerFlow(client_id=Auth.clientid,
client_secret=Auth.clientsecret,
scope=permissions,
user_agent=userid)
client_secret=Auth.clientsecret,
scope=permissions,
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: ')
@@ -80,7 +85,8 @@ def AddAccount(storage, userid=None, permissions=['https://www.googleapis.com/au

AddAccount = staticmethod(AddAccount)

def SetupAuth(interactive=False, permissions=['https://www.googleapis.com/auth/cloudprint']):
def SetupAuth(interactive=False,
permissions=['https://www.googleapis.com/auth/cloudprint']):
"""Sets up requestors with authentication tokens
Args:
@@ -91,9 +97,10 @@ def SetupAuth(interactive=False, permissions=['https://www.googleapis.com/auth/c
"""
modifiedconfig = False

# parse config file and extract useragents, which we use for account names
# parse config file and extract useragents, which we use for account
# names
userids = []
if os.path.exists( Auth.config ):
if os.path.exists(Auth.config):
content_file = open(Auth.config, 'r')
content = content_file.read()
data = json.loads(content)
@@ -103,21 +110,21 @@ def SetupAuth(interactive=False, permissions=['https://www.googleapis.com/auth/c
modifiedconfig = True

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

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

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

if credentials:
@@ -129,11 +136,13 @@ def SetupAuth(interactive=False, permissions=['https://www.googleapis.com/auth/c
credentials.refresh(requestor)
except AccessTokenRefreshError as e:
if not interactive:
sys.stderr.write("ERROR: Failed to renew token (error: "+ str(e) +"), please re-run /usr/share/cloudprint-cups/setupcloudprint.py\n")
sys.stderr.write(
"ERROR: Failed to renew token (error: " + str(e) + "), please re-run /usr/share/cloudprint-cups/setupcloudprint.py\n")
sys.exit(1)
else:
sys.stderr.write("Failed to renew token (error: "+ str(e) +"), authentication needs to be setup again:\n")
Auth.AddAccount( storage, userid )
sys.stderr.write(
"Failed to renew token (error: " + str(e) + "), authentication needs to be setup again:\n")
Auth.AddAccount(storage, userid)
credentials = storage.get()

requestor = credentials.authorize(requestor)
@@ -151,10 +160,10 @@ def SetupAuth(interactive=False, permissions=['https://www.googleapis.com/auth/c

SetupAuth = staticmethod(SetupAuth)

def GetAccountNames ( requestors ):
def GetAccountNames(requestors):
requestorAccounts = []
for requestor in requestors:
requestorAccounts.append(requestor.getAccount())
return requestorAccounts
GetAccountNames = staticmethod(GetAccountNames)

GetAccountNames = staticmethod(GetAccountNames)
@@ -15,30 +15,34 @@
# 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, os, subprocess, mimetypes, logging
if __name__ == '__main__': # pragma: no cover
import sys
import os
import subprocess
import mimetypes
import logging

progname = 'cloudprint'

libpath = "/usr/local/share/cloudprint-cups/"
if not os.path.exists( libpath ):
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()

# line below is replaced on commit
CCPVersion = "20140316 143822"
CCPVersion = "20140323 134450"
Utils.ShowVersion(CCPVersion)

requestors, storage = Auth.SetupAuth(False)
if requestors == False:
if not requestors:
sys.stderr.write("ERROR: config is invalid or missing\n")
logging.error("backend tried to run with invalid config");
logging.error("backend tried to run with invalid config")
sys.exit(1)
printer = Printer(requestors)
printers = printer.getPrinters()
@@ -47,17 +51,18 @@
print printer.getBackendDescription()

try:
if printers != None:
if printers is not None:
for foundprinter in printers:
print printer.getBackendDescriptionForPrinter( foundprinter )
print printer.getBackendDescriptionForPrinter(foundprinter)
except Exception as error:
sys.stderr.write( "ERROR: " + error )
logging.error(error);
sys.stderr.write("ERROR: " + error)
logging.error(error)
pass
sys.exit(0)

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

printFile = None
@@ -68,20 +73,21 @@

if sys.argv[3] == "Set Default Options":
print "ERROR: Unimplemented command: " + sys.argv[3]
logging.error("Unimplemented command: " + sys.argv[3]);
logging.error("Unimplemented command: " + sys.argv[3])
sys.exit(0)
else:
# if no printfile, put stdin to a temp file
tempFile = None
if printFile == None:
if printFile is None:
tmpDir = os.getenv('TMPDIR')
if not tmpDir:
tmpDir = "/tmp"
tempFile = tmpDir + '/' + jobID + '-' + userName + '-cupsjob-' + str(os.getpid())
tempFile = tmpDir + '/' + jobID + '-' + \
userName + '-cupsjob-' + str(os.getpid())

OUT = open (tempFile, 'w')
OUT = open(tempFile, 'w')

if OUT == False:
if not OUT:
print "ERROR: Cannot write " + tempFile
sys.exit(1)

@@ -98,62 +104,65 @@

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

logging.info("Printing file " + printFile)
optionsstring = ""
for option in sys.argv:
optionsstring += " '" + option + "'"
logging.info("Device is " + uri + " , printername is " + printername + ", Params are: " + optionsstring)
logging.info("Device is " + uri + " , printername is " +
printername + ", Params are: " + optionsstring)

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

result = 0
if 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")

if 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")
result = 1
else:
logging.info("Converted to PDF as "+ pdfFile)
logging.info("Converted to PDF as " + pdfFile)
else:
pdfFile = printFile + '.pdf'
os.rename(printFile,pdfFile)
logging.info("Using " + pdfFile + " as is already PDF")
os.rename(printFile, pdfFile)
logging.info("Using " + pdfFile + " as is already PDF")

if result == 0:
sys.stderr.write( "INFO: Sending document to Cloud Print\n")
logging.info("Sending "+ pdfFile + " to cloud")
sys.stderr.write("INFO: Sending document to Cloud Print\n")
logging.info("Sending " + pdfFile + " to cloud")

printerid, requestor = printer.getPrinterIDByURI(uri)
printer.requestor = requestor
if printerid == None:
if printerid is None:
print "ERROR: Printer '" + uri + "' not found"
result = 1
else:
if printer.submitJob(printerid, 'pdf', pdfFile, jobTitle, printername, printOptions ):
if printer.submitJob(printerid, 'pdf', pdfFile, jobTitle, printername, printOptions):
print "INFO: Successfully printed"
result = 0
else:
print "ERROR: Failed to submit job to cloud print"
result = 1

logging.info(pdfFile + " sent to cloud print, deleting")
if os.path.exists( printFile ):
os.unlink( printFile )
if os.path.exists(printFile):
os.unlink(printFile)
sys.stderr.write("INFO: Cleaning up temporary files\n")
logging.info("Deleted "+ printFile)
if os.path.exists( pdfFile ):
os.unlink( pdfFile )
logging.info("Deleted "+ pdfFile)
logging.info("Deleted " + printFile)
if os.path.exists(pdfFile):
os.unlink(pdfFile)
logging.info("Deleted " + pdfFile)
if result != 0:
sys.stderr.write("INFO: Printing Failed\n")
logging.info("Failed printing")
@@ -162,4 +171,4 @@
logging.info("Completed printing")
sys.exit(result)
else:
sys.exit(result)
sys.exit(result)

0 comments on commit dd04203

Please sign in to comment.
You can’t perform that action at this time.