Beispiel #1
0
def userInfo( url='', apiUser='', newUser=False ) :
    'Retrieves the User ID to use for the window'
    
    user, userID, userList='', '', []
    
    isGUI = False
    try :
        #Validate Against DCC Environment
        if F.get_app() is not None :
            isGUI = True
    except :
        pass

    if isGUI :
        user=popup( title='Enter NIM Login', msg='Please enter your NIM username:'******'input', defaultInput=apiUser )
    else :
        user=raw_input('Please enter your NIM username: '******'q': 'getUserID', 'u': user}, debug=False, nimURL=url )
            print("userID: %s" % userID)
        else :
            userID=Api.get( sqlCmd={ 'q': 'getUserID', 'u': user}, debug=False )
            print("userID: %s" % userID)

        if type(userID)==type(list()) and len(userID)==1 :
            try :
                userID=userID[0]['ID']
                P.info( 'User set to "%s" (ID #%s)' % (user, userID) )
                if newUser == False:
                    #  Update Preferences :
                    Prefs.update( attr='NIM_User', value=user )
                    if isGUI :
                        popup( title='NIM User Set', msg='The NIM user has been set to %s.' % user)
                    else :
                        print('The NIM user has been set to %s.' % user)
                return (user, userID)
            except :
                return False
        else :
            P.error( 'Failed to find NIM user.' )
            if isGUI :
                response = popup( title='User Not Found', msg='The username entered is not a valid NIM user.\n\n Would you like to enter a new username?', type='okCancel')
            else :
                response=raw_input('The username entered is not a valid NIM user. Would you like to enter a new username? (Y/N)')
                if response == 'Y' or response == 'y' :
                    response = 'OK'

            if(response=='OK'):
                userInfo( url=url, newUser=newUser )
            else :
                return False
Beispiel #2
0
def get_userInfo(url=''):
    'Retrieves the User ID to use for the window'
    #print "get_userInfo(%s)" % url
    #user=Api.get_user()
    #userID=Api.get( sqlCmd={ 'q': 'getUserID', 'u': user}, debug=False, nimURL=url )
    user = None
    userID = None
    '''
    users=Api.get( sqlCmd={'q': 'getUsers'}, debug=False, nimURL=url )
        
    if not userID and users :
        
        userList=[]
        for u in users : 
            userList.append( u['username'] )
                
        #  Create window to get user name from :
        if F.get_app() !='C4D' :
            user=Win.popup( title='User Name Error', msg='Pick a username to use', type='comboBox', pyside=True, _list=userList )
        else :
            import nim4d_userWin as W
            userWin=W.GetUser()
            userWin.Open( dlgtype=W.c4d.DLG_TYPE_MODAL )
            user=userWin.get_user()
            print 'User = "******"' % user
    '''
    if not userID:
        userInfo = Win.userInfo(url=url, newUser=True)
        if userInfo:
            #  Get user ID :
            print(userInfo)
            user = userInfo[0]
            userID = userInfo[1]

            if not userID:
                userResult = Api.get(sqlCmd={
                    'q': 'getUserID',
                    'u': user
                },
                                     debug=False,
                                     nimURL=url)

                if type(userResult) == type(list()) and len(userResult) == 1:
                    userID = userResult[0]['ID']
                    return (user, userID)
                else:
                    return False
            else:
                return (user, userID)
    else:
        return (user, userID)
Beispiel #3
0
    def ingest_prefs(self):
        'Sets NIM dictionary from preferences'
        self.app = F.get_app()
        self.prefs = Prefs.read()

        if not self.prefs:
            return False

        P.info('Preferences being read...')

        #  Set User Information :
        user = self.prefs['NIM_User']
        userID = Api.get(sqlCmd={'q': 'getUserID', 'u': user}, debug=False)
        if userID:
            if type(userID) == type(list()) and len(userID) == 1:
                userID = userID[0]['ID']
            try:
                self.nim['user'] = {'name': user, 'ID': str(userID)}
            except:
                self.nim['user'] = {'name': '', 'ID': ''}
                P.warning('Unable to set User information in NIM!')

            #  Get Show/Shot Prefs :
            try:
                self.set_name(elem='job', name=self.prefs[self.app + '_Job'])
                self.set_name(elem='asset',
                              name=self.prefs[self.app + '_Asset'])
                self.set_tab(_type=self.prefs[self.app + '_Tab'])
                self.set_name(elem='show', name=self.prefs[self.app + '_Show'])
                self.set_name(elem='shot', name=self.prefs[self.app + '_Shot'])
                self.set_name(elem='filter',
                              name=self.prefs[self.app + '_Filter'])
                self.set_name(elem='task', name=self.prefs[self.app + '_Task'])
                self.set_name(elem='base',
                              name=self.prefs[self.app + '_Basename'])
                self.set_name(elem='ver',
                              name=self.prefs[self.app + '_Version'])
            except:
                P.error(
                    'Sorry, unable to get NIM preferences, cannot run NIM GUI')
                P.error('    %s' % traceback.print_exc())
                win.popup(
                    title='NIM Error',
                    msg=
                    'Sorry, unable to get NIM preferences, cannot run NIM GUI')
                return False
            return self
        else:
            return False
Beispiel #4
0
def _verifyURL(url=''):
    'Verifies a given URL as valid'
    #  Verify URL :
    if not url: return False

    # Validate URL Pattern
    parsedURL = urlparse.urlparse(url)
    min_attributes = ('scheme', 'netloc')
    if not all([getattr(parsedURL, attr) for attr in min_attributes]):
        #error = "'{url}' string has no scheme or netloc.".format(url=parsedURL.geturl())
        #print(error)
        print("URL Format is invalid")
        return False
    else:
        print("Valid URL Format Entered")

    result = Api.get(sqlCmd={'q': 'testAPI'}, debug=False, nimURL=url)
    P.info('Validating API: %s' % result)
    if result:
        #setting global variable
        return url
    else:
        return False
Beispiel #5
0
def verUp(nim=None,
          padding=2,
          selected=False,
          win_launch=False,
          pub=False,
          symLink=True):
    'Versions up a file - Does NOT add it to the NIM API'

    #  Variables :
    cur_filePath, cur_fileDir, cur_fileName = '', '', ''
    scenePath, assetName, shotName = '', '', ''
    server, fileBase, nimDir, fileDir, ext, verNum = '', '', '', '', '', None
    renDir, compPath = '', ''

    #  Get current file information :
    if not nim:
        #  Initialize NIM dictionary :
        nim = Nim.NIM()
        nim.ingest_prefs()
        if pub: nim.set_name(elem='filter', name='Published')
        else: nim.set_name(elem='filter', name='Work')

    #P.info("SERVER ID: %s" % str(nim.server(get='ID')))
    # Get Server OS Path from server ID
    serverOsPathInfo = Api.get_serverOSPath(nim.server(get='ID'),
                                            platform.system())
    P.info("Server OS Path: %s" % serverOsPathInfo)
    serverOSPath = serverOsPathInfo[0]['serverOSPath']
    nim.set_server(path=serverOSPath)

    #  Attempt to get current file information :
    if nim.filePath():
        cur_filePath = nim.filePath()
        cur_fileDir = nim.fileDir()
        cur_fileName = nim.fileName()

    #  Basename :
    nim.set_name(elem='base', name=Api.to_basename(nim=nim))
    basename = nim.name('base')

    #  Directory to save to :
    api_fileDir = Api.to_fileDir(nim)
    if api_fileDir and not cur_fileDir:
        fileDir = api_fileDir
    elif not api_fileDir and cur_fileDir:
        fileDir = cur_fileDir
    elif api_fileDir and cur_fileDir:
        fileDir = api_fileDir

    #  Project Directory :
    if fileDir[-6:] == 'scenes': projDir = fileDir[:-6]
    else: projDir = fileDir

    #  Convert file directory :
    #P.info("fileDir: %s" % fileDir)
    fileDir = os_filePath(path=fileDir, nim=nim)
    P.info('File Directory = %s' % fileDir)
    projDir = os_filePath(path=projDir, nim=nim)
    P.info('Project Directory = %s' % projDir)

    #  Version Number :
    baseInfo = ''
    if nim.tab() == 'SHOT':
        baseInfo = Api.get_baseVer(shotID=nim.ID('shot'),
                                   basename=nim.name('base'))
    elif nim.tab() == 'ASSET':
        baseInfo = Api.get_baseVer(assetID=nim.ID('asset'),
                                   basename=nim.name('base'))
    if baseInfo:
        ver_baseInfo = baseInfo[0]['version']
        verNum = int(ver_baseInfo) + 1
    else:
        verNum = 1
    try:
        for f in [
                f for f in os.listdir(fileDir)
                if os.path.isfile(os.path.join(fileDir, f))
        ]:
            verSrch = re.search(basename + '_v[0-9]+', f)
            if verSrch:
                numSrch = re.search('[0-9]+$', verSrch.group())
                if numSrch:
                    if int(numSrch.group()) > verNum:
                        verNum = int(numSrch.group())
    except:
        pass
    nim.set_version(version=str(verNum))

    #  Set Extension :
    ext = nim.name('fileExt')
    if not ext:
        P.debug('Getting Extension')
        ext = get_ext()

    P.debug('Extension = %s' % ext)

    #  Error Checking :
    if not fileDir or not basename:
        msg='Sorry, you must either: Save the file from the NIM File GUI, or\n'+\
            '    save the file in the appropriate folders, with the correct name.\n\n'+\
            'File NOT saved.'
        P.error(msg)
        Win.popup(title='NIM - Version Up Error', msg=msg)
        return False

    #  Construct new File Name :
    if not pub:
        new_fileName = '%s_v%s%s' % (basename, str(verNum).zfill(
            int(padding)), ext)
    elif pub:
        verNum -= 1
        new_fileName = '%s_v%s_PUB%s' % (basename, str(verNum).zfill(
            int(padding)), ext)

    #  Construct new File Path :
    temp_filePath = os.path.normpath(os.path.join(fileDir, new_fileName))
    new_filePath = os_filePath(path=temp_filePath, nim=nim)

    #  Construct Render Directory :
    if nim.tab() == 'SHOT' and nim.ID('shot'):
        pathInfo = Api.get({
            'q': 'getPaths',
            'type': 'shot',
            'ID': str(nim.ID('shot'))
        })
    elif nim.tab() == 'ASSET' and nim.ID('asset'):
        pathInfo = Api.get({
            'q': 'getPaths',
            'type': 'asset',
            'ID': str(nim.ID('asset'))
        })
    if pathInfo and type(pathInfo) == type(dict()) and 'renders' in pathInfo:
        renDir = os.path.normpath(
            os.path.join(nim.server(), pathInfo['renders']))
    else:
        #  Use old method, if path information can't be derived :
        renDir = Api.to_renPath(nim)
    renDir = os_filePath(path=renDir, nim=nim)

    #  Comp Path :
    if pathInfo and type(pathInfo) == type(dict()) and 'comps' in pathInfo:
        compPath = os.path.normpath(
            os.path.join(nim.server(), pathInfo['comps']))
        nim.set_compPath(compPath=compPath)
    compPath = os_filePath(path=compPath, nim=nim)

    P.info('\nVariables:')
    P.info('  Initial File Path = %s' % cur_filePath)
    P.info('  Basename = %s' % basename)
    P.info('  Project Directory = %s' % projDir)
    P.info('  New File Path = %s' % new_filePath)
    P.info('  Render Directory = %s' % renDir)
    P.info('  Comp Directory = %s\n' % compPath)

    #  Directories :
    #===---------------

    #  Make basename directory :
    if projDir and not os.path.isdir(projDir):
        P.info('Creating basename directory within...\n    %s' % projDir)
        og_umask = os.umask(0)
        os.makedirs(projDir)
        os.umask(og_umask)
        if os.path.isdir(projDir):
            P.info('  Successfully created the basename directory!')
        else:
            P.warning('  Unable to create basename directory')

    #  Make render directory :
    if renDir and not os.path.isdir(renDir):
        P.info('Creating render directory...\n      %s' % renDir)

        og_umask = os.umask(0)
        os.makedirs(renDir)
        os.umask(og_umask)

        if os.path.isdir(renDir):
            P.info('    Successfully created the render directory!')
        else:
            P.warning('    Unable to create project directories.')
    elif renDir:
        P.debug('Render directory already exists.\n')

    #  Make Maya Project directory :
    if os.path.isdir(projDir) and nim.app() == 'Maya':
        import nim_maya as M
        if M.makeProject(projectLocation=projDir, renderPath=renDir):
            P.info('Created Maya project directorires within...\n    %s' %
                   projDir)
        else:
            P.warning('    Unable to create Maya project directories.')
    elif nim.app() == 'Maya':
        P.warning('Didn\'t create Maya project directories.')

    #  Make 3dsMax Project directory :
    if os.path.isdir(projDir) and nim.app() == '3dsMax':
        import nim_3dsmax as Max
        if Max.mk_proj(path=projDir, renPath=renDir):
            P.info('Created 3dsMax project directorires within...\n    %s' %
                   projDir)
        else:
            P.warning('    Unable to create 3dsMax project directories.')
    elif nim.app() == '3dsMax':
        P.warning('Didn\'t create 3dsMax project directories.')

    #  Make Houdini Project directory :
    if os.path.isdir(projDir) and nim.app() == 'Houdini':
        import nim_houdini as Houdini
        if Houdini.mk_proj(path=projDir, renPath=renDir):
            P.info('Created Houdini project directorires within...\n    %s' %
                   projDir)
        else:
            P.warning('    Unable to create Houdini project directories.')
    elif nim.app() == 'Houdini':
        P.warning('Didn\'t create Houdini project directories.')

    #  Save :
    #===------
    P.info('APP = %s' % nim.app())

    #  Maya :
    if nim.app() == 'Maya':
        import maya.cmds as mc

        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_maya as M
            M.set_vars(nim=nim)

            P.info('Saving file as %s \n' % new_filePath)
            mc.file(rename=new_filePath)
            if ext == '.mb':
                mc.file(save=True, type='mayaBinary')
            elif ext == '.ma':
                mc.file(save=True, type='mayaAscii')
        else:
            P.info('Saving selected items as %s \n' % new_filePath)
            if ext == '.mb':
                mc.file(new_filePath, exportSelected=True, type='mayaBinary')
            elif ext == '.ma':
                mc.file(new_filePath, exportSelected=True, type='mayaAscii')

    #  Nuke :
    elif nim.app() == 'Nuke':

        import nuke

        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_nuke as N
            N.set_vars(nim=nim)
            P.info('Saving file as %s \n' % new_filePath)
            nuke.scriptSaveAs(new_filePath)
        elif selected:
            P.info('Saving selected items as %s \n' % new_filePath)
            try:
                nuke.nodeCopy(new_filePath)
            except RuntimeError:
                P.info(
                    'Failed to selected items... Possibly no items selected.')
                return False

    #  Cinema 4D :
    elif nim.app() == 'C4D':
        import c4d

        #  Set Vars :
        nim_plugin_ID = 1032427

        #  Save File :
        if not selected:
            P.info('Saving file as %s \n' % new_filePath)
            import nim_c4d as C
            C.set_vars(nim=nim, ID=nim_plugin_ID)
            doc = c4d.documents.GetActiveDocument()
            doc.SetDocumentName(new_fileName)
            doc.SetDocumentPath(fileDir)
            c4d.documents.SaveDocument(doc, str(new_filePath),
                                       c4d.SAVEDOCUMENTFLAGS_DIALOGSALLOWED,
                                       c4d.FORMAT_C4DEXPORT)
            P.info('Saving File Complete')
        #  Save Selected :
        else:
            P.info('Saving selected items as %s \n' % new_filePath)
            doc = c4d.documents.GetActiveDocument()
            sel = doc.GetActiveObjects(False)
            baseDoc = c4d.documents.IsolateObjects(doc, sel)
            c4d.documents.SaveDocument(baseDoc, str(new_filePath),
                                       c4d.SAVEDOCUMENTFLAGS_DIALOGSALLOWED,
                                       c4d.FORMAT_C4DEXPORT)

    #  Hiero :
    elif nim.app() == 'Hiero':
        import hiero.core
        projects = hiero.core.projects()
        proj = projects[0]
        curFilePath = proj.path()
        proj.saveAs(new_filePath)
        #proj=hiero.core.project( projName )
        #proj=hiero.core.Project
        #proj=self._get_current_project()

    #  3dsMax :
    if nim.app() == '3dsMax':
        import MaxPlus
        maxFM = MaxPlus.FileManager
        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_3dsmax as Max
            Max.set_vars(nim=nim)
            #Save File
            P.info('Saving file as %s \n' % new_filePath)
            maxFM.Save(new_filePath)
        else:
            #Save Selected Items
            P.info('Saving selected items as %s \n' % new_filePath)
            maxFM.SaveSelected(new_filePath)

    #  Houdini :
    if nim.app() == 'Houdini':
        import hou
        #  Save File :
        if not selected:
            #  Set Vars :
            import nim_houdini as Houdini
            Houdini.set_vars(nim=nim)

            #Save File
            if _os.lower() in ['windows', 'win32']:
                new_filePath = new_filePath.replace('\\', '/')

            P.info('Saving file as %s \n' % new_filePath)
            try:
                hou.hipFile.save(file_name=str(new_filePath))
                P.info('Houdini successfully save the file.')
            except hou.OperationFailed:
                P.info('Houdini failed to save the file.')
                P.info(hou.OperationFailed.description())

            #Set $HIP var to location of current file
            if _os.lower() in ['windows', 'win32']:
                projDir = projDir.replace('\\', '/')

            hou.hscript("set -g HIP = '" + str(projDir) + "'")

            #Set $HIPNAME var to current file
            hipName = os.path.splitext(new_fileName)[0]
            hou.hscript("set -g HIPNAME = '" + str(hipName) + "'")

        else:
            #Save Selected Items
            if _os.lower() in ['windows', 'win32']:
                new_filePath = new_filePath.replace('\\', '/')
            P.info('Saving selected items as %s \n' % new_filePath)

            try:
                tmp_filePath = new_filePath + "." + time.strftime(
                    '%Y%m%d_%H%M%S') + ".tmp"
                parentNode = "hou.node('/obj/')"
                selected = hou.selectedNodes()
                selectedParent = selected[0].parent()
                selectedParent.saveItemsToFile(selected,
                                               file_name=str(tmp_filePath))
                P.info('Houdini saved items to file.')
            except hou.OperationFailed:
                P.info('Houdini failed to save selected items to file.')
                P.info(hou.OperationFailed.description())

            saveCode = '"' + "import os, time; newParent = " + parentNode + "; newParent.loadChildrenFromFile('" + tmp_filePath + "'); hou.hipFile.save('" + new_filePath + "')" + '"'
            pyCmd = os.environ["HFS"] + '/bin/hython -c ' + saveCode

            try:
                os.system(pyCmd)
            except:
                P.info('Failed to run hython for external Houini save.')

            try:
                os.remove(tmp_filePath)
            except OSError:
                pass

    #  Make a copy of the file, if publishing :
    if pub and not symLink:
        pub_fileName = basename + ext
        pub_fileDir = Api.to_nimDir(nim=nim)
        pub_filePath = os.path.join(pub_fileDir, pub_fileName)
        #  Delete any pre-existing published file :
        if os.path.isfile(pub_filePath):
            os.chmod(pub_filePath, stat.S_IWRITE)
            os.remove(pub_filePath)
        #  Copy file and make it read-only :
        shutil.copyfile(new_filePath, pub_filePath)
        os.chmod(pub_filePath, stat.S_IREAD)

    #  Print save success :
    P.info('\nFile successfully saved to...\n    %s\n' % new_filePath)

    #  [AS]  returning nim object with current dictionary settings
    #return new_filePath
    return {'filepath': new_filePath, 'nim': nim}