Beispiel #1
0
def _prefsFail():
    'Determines course of action, after a user has input an invalid NIM URL'
    msg = 'Sorry, specified NIM URL is invalid.'
    P.error(msg)
    msg += '\n    Would you like to enter another one?'
    result = Win.popup(title='NIM - URL Error', msg=msg, type='okCancel')
    #P.info( 'WINDOW RESULT: %s' % result)
    if result == 'OK':
        url = _inputURL()
        test = _verifyURL(url)
        P.info('NIM URL Verified: %s' % test)
        if test: return [result, url]
    return [result, False]
Beispiel #2
0
def _inputURL():
    'Gets the NIM API URL from the user, via a popup'
    global nim_URL, version

    isGUI = False
    try:
        #Validate Against DCC Environment
        if F.get_app() is not None:
            isGUI = True
    except:
        pass

    #  Prompt user to input URL :
    msg = 'Please input the NIM API URL :'
    if isGUI:
        url = Win.popup(title=winTitle + ' - Get URL',
                        msg=msg,
                        type='input',
                        defaultInput=nim_URL)
    else:
        url = raw_input(msg)
    #P.info( 'NIM URL Set to: %s' % url )
    if url:
        # Check for '/nimAPI.php?' at end of URL

        if url.endswith('nimAPI.php'):
            url = url + "?"
        '''
        if not url.endswith('/nimAPI.php?'):
            if not url.endswith('/'):
                url = url+"/nimAPI.php?"
            else :
                url = url+"nimAPI.php?"
        '''

        return url

    else:
        return False
Beispiel #3
0
def mk_default(recreatePrefs=False, notify_success=True):
    'Makes default preferences'

    global apps
    global nim_api
    global nim_user, nim_userID
    global nim_URL

    isGUI = False
    try:
        #Validate Against DCC Environment
        if F.get_app() is not None:
            isGUI = True
    except:
        pass

    nimHome = mk_home()
    prefsFile = get_path()
    apps = F.get_apps()
    #nim_user=F.get_user()
    url, userID = 1, ''

    #  Create home dir, if necessary :
    mk_home()

    #  Check to see if preferences need to be re-created :
    if os.path.exists(prefsFile):
        #  If preferences have missing attributes, add those attributes to prefs file:
        prefs_check = check()
        if prefs_check:
            #  Open NIM prefs file for appending :
            _prefFile = open(prefsFile, 'a')
            _prefFile.write('\n')
            #  Write NIM preferences :
            nim_prefs = _nimPrefs()
            missing_at_least_one_nim_pref = False
            for key in prefs_check:
                if key in nim_prefs:
                    missing_at_least_one_nim_pref = True
                    _prefFile.write(key + '=' + nim_prefs[key] + '\n')
            if missing_at_least_one_nim_pref:
                _prefFile.write('\n')
            #  Write Application Preferences :
            for app in apps:
                app_prefs = _appPrefs(app)
                for key in prefs_check:
                    if key in app_prefs:
                        _prefFile.write(key + '=' + app_prefs[key] + '\n')
                _prefFile.write('\n')
            #  Close file :
            _prefFile.close()
        else:
            #  Ask to recreate existing preferences :
            if recreatePrefs:
                if isGUI:
                    recreate=Win.popup( title=winTitle+' - Prefs Exist', \
                        msg='Preferences already exist.\nWould you like to re-create your preferences?', \
                        type='okCancel' )
                else:
                    recreate = raw_input(
                        "Preferences already exist. Would you like to re-create your preferences? (Y\N) "
                    )
                    if recreate == 'Y' or recreate == 'y':
                        recreate = 'OK'

                if recreate == 'OK':
                    P.info('Deleting previous preferences file...')
                    try:
                        os.remove(prefsFile)
                    except Exception, e:
                        P.error('Unable to delete preferences')
                        P.error('    %s' % traceback.print_exc())
                        return False
                else:
                    return prefsFile
            else:
                return prefsFile
Beispiel #4
0
        search_for_url = True
        search_for_user = False
        while search_for_url:
            url = _inputURL()
            result = _verifyURL(url)
            if result:
                P.info('URL Valid')
                nim_URL = url
                search_for_url = False
                search_for_user = True
                break
            else:
                msg = 'The NIM API URL entered is invalid :\n %s \nTry Again?' % url
                if isGUI:
                    keepGoing = Win.popup(title=winTitle + ' - Get URL',
                                          msg=msg,
                                          type='okCancel')
                else:
                    keepGoing = raw_input(
                        'The NIM API URL entered is invalid. Try Again? (Y/N):'
                    )
                    if keepGoing == 'Y' or keepGoing == 'y':
                        keepGoing = 'OK'

                if keepGoing != 'OK':
                    P.error('Exiting without setting NIM Preferences.')
                    search_for_url = False
                    search_for_user = False
                    return False

        #  Verify User :
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}