def nimProjectChangeUser():
	try:
		nimUI.GUI().update_user()
	except Exception, e :
		print 'Sorry, there was a problem choosing NIM user...'
		print '    %s' % traceback.print_exc()
Example #2
0
        def __init__(self, selection, selectedPresets, parent=None):
            super(NimHieroExport.NimExportDialog, self).__init__(parent)

            self.app = nimFile.get_app()
            self.prefs = nimPrefs.read()
            try:
                self.user = self.prefs['NIM_User']
                self.pref_job = self.prefs[self.app + '_Job']
                self.pref_show = self.prefs[self.app + '_Show']
                self.pref_server = self.prefs[self.app + '_ServerPath']
            except:
                #return False
                pass

            self.nim_OS = platform.system()

            self.nim_userID = nimAPI.get_userID(self.user)
            if not self.nim_userID:
                nimUI.GUI().update_user()
                userInfo = nim.NIM().userInfo()
                self.user = userInfo['name']
                self.nim_userID = userInfo['ID']

            print "NIM: user=%s" % self.user
            print "NIM: userID=%s" % self.nim_userID
            print "NIM: default job=%s" % self.pref_job

            self.nim_jobPaths = {}
            self.nim_showPaths = {}
            self.nim_shotPaths = {}
            self.nim_showFolder = ''
            self.nim_servers = {}
            self.nim_serverID = None
            self.nim_serverOSPath = ''

            #Get NIM Jobs
            self.nim_jobID = None
            self.nim_jobs = nimAPI.get_jobs(self.nim_userID)
            if not self.nim_jobs:
                print "No Jobs Found"
                self.nim_jobs["None"] = "0"

            self.nim_shows = []
            self.nim_showDict = {}
            self.nim_showID = None

            self.setWindowTitle("NIM Update Selected Shots")
            self.setSizeGripEnabled(True)

            self._exportTemplate = None

            tag_jobID = None
            tag_showID = None

            nimConnect = nimHieroConnector.NimHieroConnector()

            # Check Sequence for existing showID
            for trackItem in selection:
                sequence = trackItem.parentSequence()
                nim_sequence_tag = nimConnect.getNimTag(sequence)
                if (nim_sequence_tag != False):
                    tag_showID = nim_sequence_tag.metadata().value(
                        "tag.showID")
                    print "NIM: Sequence showID=%s" % tag_showID
                    if (tag_showID != ''):
                        showInfo = nimAPI.get_showInfo(tag_showID)
                        if len(showInfo) > 0:
                            for showInfoDetails in showInfo:
                                tag_jobID = showInfoDetails['jobID']
                                print "NIM: Sequence jobID=%s" % tag_jobID
                break

            layout = QVBoxLayout()
            formLayout = QFormLayout()
            groupBox = QGroupBox()
            groupLayout = QFormLayout()
            groupBox.setLayout(groupLayout)

            # JOBS: List box for job selection
            horizontalLayout = QHBoxLayout()
            horizontalLayout.setSpacing(-1)
            horizontalLayout.setSizeConstraint(QLayout.SetDefaultConstraint)
            horizontalLayout.setObjectName("HorizontalLayout")
            self.nimJobLabel = QLabel()
            self.nimJobLabel.setFixedWidth(40)
            self.nimJobLabel.setText("Job:")
            horizontalLayout.addWidget(self.nimJobLabel)
            self.nim_jobChooser = QComboBox()
            self.nim_jobChooser.setToolTip(
                "Choose the job you wish to export shots to.")
            horizontalLayout.addWidget(self.nim_jobChooser)
            horizontalLayout.setStretch(1, 40)
            groupLayout.setLayout(0, QFormLayout.SpanningRole,
                                  horizontalLayout)

            # JOBS: Add dictionary in ordered list
            jobIndex = 0
            jobIter = 0
            if len(self.nim_jobs) > 0:
                for key, value in sorted(self.nim_jobs.items(), reverse=True):
                    self.nim_jobChooser.addItem(key)
                    if nimHieroConnector.g_nim_jobID:
                        if nimHieroConnector.g_nim_jobID == value:
                            print "Found matching jobID, job=", key
                            self.pref_job = key
                            jobIndex = jobIter
                    else:
                        if self.pref_job == key:
                            print "Found matching Job Name, job=", key
                            jobIndex = jobIter
                    jobIter += 1

                if self.pref_job != '':
                    self.nim_jobChooser.setCurrentIndex(jobIndex)

            self.nim_jobChooser.currentIndexChanged.connect(
                self.nim_jobChanged)
            #self.nim_jobChanged() #trigger job changed to load choosers
            '''
			# SERVERS: List box for server selection
			horizontalLayout2 = QHBoxLayout()
			horizontalLayout2.setSpacing(-1)
			horizontalLayout2.setSizeConstraint(QLayout.SetDefaultConstraint)
			horizontalLayout2.setObjectName("HorizontalLayout2")
			self.nimServerLabel = QLabel()
			self.nimServerLabel.setFixedWidth(40)
			self.nimServerLabel.setText("Server:")
			horizontalLayout2.addWidget(self.nimServerLabel)
			self.nim_serverChooser = QComboBox()
			self.nim_serverChooser.setToolTip("Choose the server you wish to export shots to.")
			horizontalLayout2.addWidget(self.nim_serverChooser)
			horizontalLayout2.setStretch(1, 40)
			groupLayout.setLayout(1, QFormLayout.SpanningRole, horizontalLayout2)

			# SERVERS: Add dictionary in ordered list
			serverIndex = 0
			serverIter=0
			if len(self.nim_servers)>0:
				for server in self.nim_servers:
					self.nim_serverDict[server['server']] = server['ID']
      
				for key, value in sorted(self.nim_serverDict.items(), reverse=False):
					self.nim_serverChooser.addItem(key)
					if nimHieroConnector.g_nim_serverID == value:
						self.pref_server = key
						serverIndex = serverIter
						#print "Found matching serverID, server=", key
						#print "serverIndex=",serverIndex

					serverIter +=1

				if self.pref_server != '':
					#print "self.pref_server=",self.pref_server
					self.nim_serverChooser.setCurrentIndex(serverIndex)

			self.nim_serverChooser.currentIndexChanged.connect(self.nim_serverChanged)
			self.nim_serverChanged()
			'''

            # SHOWS: List box for show selection
            horizontalLayout3 = QHBoxLayout()
            horizontalLayout3.setSpacing(-1)
            horizontalLayout3.setSizeConstraint(QLayout.SetDefaultConstraint)
            horizontalLayout3.setObjectName("HorizontalLayout3")
            self.nimShowLabel = QLabel()
            self.nimShowLabel.setFixedWidth(40)
            self.nimShowLabel.setText("Show:")
            horizontalLayout3.addWidget(self.nimShowLabel)
            self.nim_showChooser = QComboBox()
            self.nim_showChooser.setToolTip(
                "Choose the show you wish to export shots to.")
            horizontalLayout3.addWidget(self.nim_showChooser)
            horizontalLayout3.setStretch(1, 40)
            groupLayout.setLayout(1, QFormLayout.SpanningRole,
                                  horizontalLayout3)
            self.nim_showChooser.currentIndexChanged.connect(
                self.nim_showChanged)

            # Add the standard ok/cancel buttons, default to ok.
            self._buttonbox = QDialogButtonBox(
                QDialogButtonBox.StandardButton.Ok
                | QDialogButtonBox.StandardButton.Cancel)
            self._buttonbox.button(
                QDialogButtonBox.StandardButton.Ok).setText("Update")
            self._buttonbox.button(
                QDialogButtonBox.StandardButton.Ok).setDefault(True)
            self._buttonbox.button(
                QDialogButtonBox.StandardButton.Ok).setToolTip(
                    "Executes exports on selection for each selected preset")
            self._buttonbox.accepted.connect(self.acceptTest)
            self._buttonbox.rejected.connect(self.reject)
            horizontalLayout4 = QHBoxLayout()
            horizontalLayout4.setSpacing(-1)
            horizontalLayout4.setSizeConstraint(QLayout.SetDefaultConstraint)
            horizontalLayout4.setObjectName("HorizontalLayout4")
            spacerItem4 = QSpacerItem(175, 20, QSizePolicy.Expanding,
                                      QSizePolicy.Minimum)
            horizontalLayout4.addItem(spacerItem4)
            horizontalLayout4.addWidget(self._buttonbox)
            horizontalLayout4.setStretch(1, 40)
            groupLayout.setLayout(2, QFormLayout.SpanningRole,
                                  horizontalLayout4)

            self.setLayout(groupLayout)
            layout.addWidget(groupBox)

            self.nim_jobChanged()  #trigger job changed to load choosers
Example #3
0
  def startProcessing(self, exportItems):
    hiero.core.log.debug( "NimShotProcessor::startProcessing(" + str(exportItems) + ")" )

    sequences = []
    selectedTrackItems = set()
    selectedSubTrackItems = set()
    ignoredTrackItems = set()
    excludedTracks = []
    
    # Build Tags data from selection
    self._tags = buildTagsData(exportItems)
    
    # Filter the include/exclude tags incase the previous tag selection is not included in the current selection
    included_tag_names = [ tag.name() for tag, objectType in self._tags if tag.name() in self._preset.properties()["includeTags"] ]
    excluded_tag_names = [ tag.name() for tag, objectType in self._tags if tag.name() in self._preset.properties()["excludeTags"] ]

    # This flag controls whether items which havent been explicitly included in the export, 
    # should be removed from the copied sequence. This primarily affects the collate functionality in nuke script generation.
    exclusiveCopy = False


    if exportItems[0].trackItem():
      sequences.append( exportItems[0].trackItem().parent().parent() )
      for item in exportItems:
        trackItem = item.trackItem()
        if isinstance(trackItem, hiero.core.TrackItem):
          selectedTrackItems.add( trackItem )
          if item.ignore():
            ignoredTrackItems.add( trackItem )
        elif isinstance(trackItem, hiero.core.SubTrackItem):
          selectedSubTrackItems.add( trackItem )
    else:
      sequences = [ item.sequence() for item in exportItems ]
      
    if ignoredTrackItems:
      # A set of track items have been explicitly marked as ignored. 
      # This track items are to be included in the copy, but not exported.
      # Thus any shot which isnt in the selected list, should be excluded from the copy.
      exclusiveCopy = True

    for sequence in sequences:
      excludedTracks.extend( [track for track in sequence if track.guid() in self._preset._excludedTrackIDs] )
      
    localtime = time.localtime(time.time())

    path = self._exportTemplate.exportRootPath()
    versionIndex = self._preset.properties()["versionIndex"]
    versionPadding = self._preset.properties()["versionPadding"]
    retime = self._preset.properties()["includeRetimes"]

    cutHandles = None
    startFrame = None

    if self._preset.properties()["startFrameSource"] == NimShotProcessor.kStartFrameCustom:
      startFrame = self._preset.properties()["startFrameIndex"]

    # If we are exporting the shot using the cut length (rather than the (shared) clip length)
    if self._preset.properties()["cutLength"]:
      # Either use the specified number of handles or zero
      if self._preset.properties()["cutUseHandles"]:
        cutHandles = int(self._preset.properties()["cutHandles"])
      else:
        cutHandles = 0


    # Create a resolver from the preset (specific to this type of processor)
    resolver = self._preset.createResolver()

    self._submission.setFormatDescription( self._preset.name() )

    exportTrackItems = []

    copiedSequences = []

    project = None

    for sequence in sequences:
      sequenceCopy = sequence.copy()
      copiedSequences.append( sequenceCopy )
      self._tagCopiedSequence(sequence, sequenceCopy)

      # Copied effect items create their nodes lazily, but this has to happen on
      # the main thread, force it to be done here.
      ensureEffectsNodesCreated(sequenceCopy)

      # The export items should all come from the same project
      if not project:
        project = sequence.project()

      presetId = hiero.core.taskRegistry.addPresetToProjectExportHistory(project, self._preset)

      # For each video track
      for track, trackCopy in zip(sequence.videoTracks(), sequenceCopy.videoTracks()) + zip(sequence.audioTracks(), sequenceCopy.audioTracks()):

        # Unlock copied track so that items may be removed
        trackCopy.setLocked(False)

        if track in excludedTracks or not track.isEnabled():
          # remove unselected track from copied sequence
          sequenceCopy.removeTrack(trackCopy)
          continue

        # Used to store the track items to be removed from trackCopy, this is to
        # avoid removing items whilst we are iterating over them.
        trackItemsToRemove = []

        # For each track item on track
        for trackitem, trackitemCopy in zip(track.items(), trackCopy.items()):

          trackitemCopy.unlinkAll() # Unlink to prevent accidental removal of items we want to keep

          # If we're processing the whole sequence, or this shot has been selected
          if not selectedTrackItems or trackitem in selectedTrackItems:

            if trackitem in ignoredTrackItems:
              hiero.core.log.debug( "%s marked as ignore, skipping. Selection : %s" % (str(trackitemCopy), str(exportTrackItems)) )
              continue
              
            # Check tags for excluded tags
            excludedTags = [tag for tag in trackitem.tags() if tag.name() in excluded_tag_names]
            includedTags = [tag for tag in trackitem.tags() if tag.name() in included_tag_names]

            if included_tag_names:
              # If not included, or explictly excluded
              if not includedTags or excludedTags:
                hiero.core.log.debug( "%s does not contain include tag %s, skipping." % (str(trackitemCopy), str(included_tag_names)) )
                ignoredTrackItems.add(trackitem)
                continue
              else:
                hiero.core.log.debug( "%s has include tag %s." % (str(trackitemCopy), str(included_tag_names)) )
              
            elif excludedTags:
              hiero.core.log.debug( "%s contains excluded tag %s, skipping." % (str(trackitemCopy), str(excluded_tag_names)) )
              ignoredTrackItems.add(trackitem)
              continue

            if trackitem.isMediaPresent() or not self.skipOffline():

              exportTrackItems.append((trackitem, trackitemCopy))  

            else:
              hiero.core.log.debug( "%s is offline. Removing." % str(trackitem) )
              trackItemsToRemove.append(trackitemCopy)
          else:
            # Either remove the track item entirely, or mark it as ignored, so that no tasks are spawned to export it.
            if exclusiveCopy:
              hiero.core.log.debug( "%s is not selected. Removing." % str(trackitem) )
              trackItemsToRemove.append(trackitemCopy)
            else:
              hiero.core.log.debug( "%s is not selected. Ignoring." % str(trackitem) )
              ignoredTrackItems.add(trackitem)


        for item in trackItemsToRemove:
          trackCopy.removeItem(item)

    ''' ****************** NIM START CHECK ONLINE STATUS AND VBPS ****************** '''
    # Iterate through track items and find NIM associations
    # Check for any shots that can not be brought online due to a variable based project structure

    print 'NIM: Checking for variable based project structure items'
    is_vbps = 0
    is_vbps = nimAPI.can_bringOnline(item='shot',showID=nimHieroConnector.g_nim_showID)
    if is_vbps == 0 :
      # The show uses project variables so check the shots  
      for trackitem, trackitemCopy in exportTrackItems:
        if trackitem in ignoredTrackItems:
         continue

        #Test for video track
        exportTrackItem = False
        trackItem_mediaType = trackitem.mediaType()
        if trackItem_mediaType == hiero.core.TrackItem.MediaType.kVideo:
          exportTrackItem = True

        #Skip if not video track item
        if exportTrackItem:
          nim_shotID = None

          nimConnect = nimHieroConnector.NimHieroConnector()
          nim_tag = nimConnect.getNimTag(trackitem)
          if nim_tag != False:
            #NIM Tag Found
            nim_shotID = nim_tag.metadata().value("tag.shotID")
            is_vbps = nimAPI.can_bringOnline(item='shot',shotID=nim_shotID)
            if is_vbps == 0 :
              # If any shot requires variable break
              break


    if is_vbps == 0 :
      message = 'NIM Warning:\n\n'
      message += 'The NIM job selected uses a variable based project structure which requires '
      message += 'specific fields on each shot to be set prior to being brought online. \n\n'
      message += 'Shots can be made using the "Update Selected Shots in NIM" context menu in the timeline. '
      message += 'After making shots go to the NIM Job\'s Production/Config/Offline tab to resolve any required fields.'
      nimWin.popup( title='NIM Error', msg=message)
      return False

    ''' ****************** NIM END CHECK ONLINE STATUS AND VBPS ****************** '''

    allTasks = []

    for trackitem, trackitemCopy in exportTrackItems:
      
      if trackitem in ignoredTrackItems:
       continue

      # Check if a task is already exporting this item and if so, skip it.
      # This is primarily to handle the case of collating shots by name, where we only 
      # want one script containing all the items with that name.
      createTasks = True
      for existingTask in allTasks:

        if existingTask.isExportingItem(trackitemCopy):
          createTasks = False
          break

      if not createTasks:
        continue
      
      taskGroup = hiero.core.TaskGroup()
      taskGroup.setTaskDescription( trackitem.name() )

      # Track items may end up with different versions if they're being re-exported.  Determine
      # the version for each item.
      trackItemVersionIndex = self._getTrackItemExportVersionIndex(trackitem, versionIndex, findTrackItemExportTag(self._preset, trackitem))
      trackItemVersion = "v%s" % format(int(trackItemVersionIndex), "0%id" % int(versionPadding))

      ''' ****************** NIM START UPDATE TRACKITEM ****************** '''
      print "exporting trackItem: %s" % trackitem.name()

      #Test for video track
      exportTrackItem = False
      trackItem_mediaType = trackitem.mediaType()
      if trackItem_mediaType == hiero.core.TrackItem.MediaType.kVideo:
        print "Processing Video TrackItem"
        exportTrackItem = True

      #SKIP IF NOT VIDEO TRACK ITEM
      if exportTrackItem:
        nim_shotID = None
        nim_shotPaths = {}
        nim_platesPath = 'PLATES'
        updateThumbnail = True

        #global g_nim_showID
        nim_showID = nimHieroConnector.g_nim_showID
        print 'NIM: showID=%s' % nim_showID

        name = trackitem.name()

        nimConnect = nimHieroConnector.NimHieroConnector()
        nim_tag = nimConnect.getNimTag(trackitem)

        if nim_tag != False:
          #print "NIM: Tag Found"
          #print         nim_tag

          #update existing shot in NIM
          nim_shotID = nim_tag.metadata().value("tag.shotID")
          print 'NIM: shotID=%s' % nim_shotID

          success = nimConnect.updateTrackItem(nim_showID, trackitem)
          if success:
            print "NIM: Successfully updated trackitem %s in NIM" % name
            if updateThumbnail:
              success = nimConnect.updateShotIcon(trackitem)
              if success == False:
                print 'NIM: Failed to upload icon'
          else:
            print "NIM: Failed to update trackitem %s in NIM" % name

        else:
          #NO TAG found so create new shot in NIM... if shot exists with same name in NIM, link to this trackitem
          print 'NIM: Tag Not Found  Exporting as new trackitem'
          nim_shotID = nimConnect.exportTrackItem(nim_showID, trackitem)
          if nim_shotID == False:
            print 'NIM: Failed to export trackitem %s' % name
          else:
            if updateThumbnail:
              success = nimConnect.updateShotIcon(trackitem)
              if success == False:
                print 'NIM: Failed to upload icon for trackitem %s' % name

        #BRING SHOT ONLINE AND CREATE PROJECT STRUCTURE FOLDERS
        bringOnline_result = nimAPI.bring_online( item='shot', shotID=nim_shotID )
        if bringOnline_result['success'] == 'false':
          print 'NIM: Failed to bring shot online'
          print 'NIM: %s' % bringOnline_result['error']
        elif bringOnline_result['success'] == 'true':
          print 'NIM: Shot brought online %s' % name
        else :
          print 'NIM: bringOnline returned and invalid status'

        #GET UPDATED NIM TAG AND COPY TO CLONE
        nim_tag = nimConnect.getNimTag(trackitem)
        if nim_tag != False:
          print 'NIM: Copying nim_tag to clone'
          trackitemCopy.addTag(nim_tag)
        else:
          print 'NIM: Could not copy nim_tag to copy.. tag not found'


      ''' ****************** NIM END UPDATE TRACKITEM ****************** '''

      # If processor is flagged as Synchronous, flag tasks too
      if self._synchronous:
        self._submission.setSynchronous()

      # For each entry in the shot template
      for (exportPath, preset) in self._exportTemplate.flatten():

        # Build TaskData seed
        taskData = hiero.core.TaskData( preset,
                                        trackitemCopy,
                                        path,
                                        exportPath,
                                        trackItemVersion,
                                        self._exportTemplate,
                                        project=project,
                                        cutHandles=cutHandles,
                                        retime=retime,
                                        startFrame=startFrame,
                                        startFrameSource = self._preset.properties()["startFrameSource"],
                                        resolver=resolver,
                                        submission=self._submission,
                                        skipOffline=self.skipOffline(),
                                        presetId=presetId,
                                        shotNameIndex = getShotNameIndex(trackitem) )

        # Spawn task
        task = hiero.core.taskRegistry.createTaskFromPreset(preset, taskData)

        # Add task to export queue
        if task and task.hasValidItem():

          # Give the task an opportunity to modify the original (not the copy) track item
          if not task.error():
            task.updateItem(trackitem, localtime)

          taskGroup.addChild(task)
          allTasks.append(task)
          hiero.core.log.debug( "Added to Queue " + trackitem.name() )


          ''' ****************** NIM START PUBLISH ELEMENT ****************** '''

          #resolvedFullPath = os.path.join(resolver.resolve(task, path),resolver.resolve(task, exportPath))
          resolvedFullPath = "/".join([resolver.resolve(task, path),resolver.resolve(task, exportPath)])
          trackitem_clip = trackitem.source()

          ''''''
          #print "NIM:   2.0"
          print "NIM:   resolved fulPath=", resolvedFullPath
          print "NIM:   path=",path
          print "NIM:   exportPath=",exportPath
          #print "NIM:   version=",version
          print "NIM:   cutHandles=",cutHandles
          print "NIM:   retime=",retime
          print "NIM:   startFrame=",startFrame
          print "       trackItem:"
          print "       trackitem.name=", trackitem.name()
          print "       trackitem.duration=", trackitem.duration()
          print "       trackitem.eventNumber=", trackitem.eventNumber()
          print "       trackitem.handleInLength=", trackitem.handleInLength()
          print "       trackitem.handleInTime=", trackitem.handleInTime()
          print "       trackitem.handleOutLength=", trackitem.handleOutLength()
          print "       trackitem.handleOutTime=", trackitem.handleOutTime()
          print "       trackitem.playbackSpeed=", trackitem.playbackSpeed()
          print "       trackitem.timelineIn=", trackitem.timelineIn()
          print "       trackitem.timelineOut=", trackitem.timelineOut()
          print "       trackitem.sourceIn=", trackitem.sourceIn()
          print "       trackitem.sourceOut=", trackitem.sourceOut()
          print "       clip:"
          print "       clip.sourceIn=", trackitem_clip.sourceIn()
          print "       clip.sourceOut=", trackitem_clip.sourceOut()
          
          if cutHandles == None:
            cutHandles = 0

          element_startFrame = trackitem_clip.sourceIn() + (trackitem.sourceIn() - cutHandles)
          element_endFrame =  trackitem_clip.sourceIn() + (trackitem.sourceOut() + cutHandles)
          element_filePath = ntpath.dirname(resolvedFullPath)
          element_fileName = ntpath.basename(resolvedFullPath)

          print "nimHieroConnector.g_nim_publishElement=",nimHieroConnector.g_nim_publishElement
          print "nimHieroConnector.g_nim_element=",nimHieroConnector.g_nim_element
          print "nimHieroConnector.g_nim_elementTypeID=",nimHieroConnector.g_nim_elementTypeID

          #Determine Export Preset
          presetName = preset.name()
          presetExportName = type(preset).__name__
          print "preset name: %s" % presetName
          #print "export name: %s" % presetExportName

          nim_prefInfo = nimPrefs.read()
          user = nim_prefInfo['NIM_User']
          userID = nimAPI.get_userID(user)
          if not userID :
            nimUI.GUI().update_user()
            userInfo=nim.NIM().userInfo()
            user = userInfo['name']
            userID = userInfo['ID']
          print "NIM: user=%s" % user
          print "NIM: userID: %s" % userID

          if presetName == 'hiero.exporters.FnTranscodeExporter.TranscodeExporter' \
            or presetName == 'hiero.exporters.FnCopyExporter.CopyExporter' \
            or presetName == 'hiero.exporters.FnSymLinkExporter.SymLinkExporter' :
            if nimHieroConnector.g_nim_publishElement == True:
              print "NIM: Publish Element"
              print "     shotID=", nim_shotID
              print "     name=", trackitem.name()
              print "     type=", nimHieroConnector.g_nim_element
              print "     filePath=", element_filePath
              print "     fileName=", element_fileName
              print "     startFrame=", element_startFrame 
              print "     endFrame=", element_endFrame
              print "     cutHandles=", cutHandles
            
              element_result = nimAPI.add_element( parent='shot', parentID=nim_shotID, userID=userID, typeID=nimHieroConnector.g_nim_elementTypeID, \
                                                    path=element_filePath, name=element_fileName, startFrame=element_startFrame, endFrame=element_endFrame, \
                                                    handles=cutHandles, isPublished=nimHieroConnector.g_nim_publishElement )

          elif presetName == 'hiero.exporters.FnNukeShotExporter.NukeShotExporter':
            if nimHieroConnector.g_nim_publishComp == True:
              print "NIM: Publish Comp"
              print "     shotID=", nim_shotID
              print "     name=", trackitem.name()
              print "     filePath=", element_filePath
              print "     fileName=", element_fileName
            
              nim_doSave = True
              #check to ensure valid task is selected
              print "nimHieroConnector.g_nim_expTaskTypeID=",nimHieroConnector.g_nim_expTaskTypeID
              print "nimHieroConnector.g_nim_expTaskFolder=",nimHieroConnector.g_nim_expTaskFolder
              task_type_ID = nimHieroConnector.g_nim_expTaskTypeID
              task_folder = nimHieroConnector.g_nim_expTaskFolder
              if task_type_ID == 0:
                print "No Task selected for Nuke Comp Export.\n \
                       The Nuke comp will be created but not logged into NIM."
                nim_doSave = False

              #Derive basename from file ( TODO: give option to use shot_task_tag_ver.nk method )
              #Using filename entered in Export window
              #ext = '.nk'
              basename = element_fileName
              version = 0

              basenameFull, ext = os.path.splitext(element_fileName)
              basenameMatch = re.search(r'v[0-9]+$', basenameFull, re.I)
              if basenameMatch:
                matchIndex = basenameMatch.start(0)
                basename = basenameFull[:matchIndex]    #returns basename without v#: shot_comp_ (test for trailing _ and remove to be NIM compliant)
                lastCharMatch = re.search(r'_+$', basename)
                if lastCharMatch:
                  basename = basename[:lastCharMatch.start(0)]

                version = basenameFull[matchIndex:][1:].lstrip('0') #returns version without v and leading 0s: '1'
              else:
                print "Version information was either not found in Nuke Project export name or has incorrect placement to be NIM compatible.\n \
                       Please include the version in the comp name at the end of the name by using the {version} keyword or manually adding 'v#' to the Nuke Project File name.\n \
                       example: {shot}_comp_{version}.nk\n \
                       The Nuke comp will be created but not logged into NIM."
                nim_doSave = False
              
              filename = element_fileName
              filepath = element_filePath
              
              print "basename: %s" % basename
              print "filename: %s" % filename
              print "version: %s" % version

              #TODO: verify entry is not duplicate of existing version
              nim_doUpdate = False

              # Get versions for basename
              nim_versions = {}
              nim_versionID = 0
              nim_versions = nimAPI.get_vers(shotID=nim_shotID, basename=basename)
              print "Versions Returned: %s" % nim_versions

              # if file matching class / basename / filename / version
              try:
                if len(nim_versions)>0:
                  print "Existing versions found" 
                  for versionItem in nim_versions:
                    if versionItem['filename'] == filename:
                      print "Existing Version Found"
                      nim_versionID = versionItem['fileID']
                      print "versionID: %s" % nim_versionID
                      nim_doUpdate = True
                else:
                  print "No existing versions found"
              except:
                print "Failed to load existing versions from NIM"
                pass
              
              comment = 'Nuke Project File exported from NukeStudio'
              
              serverID = nimHieroConnector.g_nim_serverID
              if not serverID:
                print "NIM Sever information is missing.\n \
                       Please select a NIM Project Server from the Server dropdown list.\n \
                       The Nuke comp will be created but not logged into NIM."
                nim_doSave = False

              pub = nimHieroConnector.g_nim_publishComp
              forceLink = 0 # lazy symlink as files wont exist yet
              work = True # set comp as working file

              if nim_doSave is True:
                if nim_doUpdate is True:
                  print "Updating file data in NIM"
                  file_apiResult = nimAPI.update_file( ID=nim_versionID, task_type_ID=task_type_ID, task_folder=task_folder, userID=userID, basename=basename, filename=filename, path=filepath, ext=ext, version=version, comment=comment, serverID=serverID, pub=pub, forceLink=forceLink, work=work )
                  print file_apiResult
                else:
                  print "Saving file data to NIM"
                  file_apiResult = nimAPI.save_file( parent='shot', parentID=nim_shotID, task_type_ID=task_type_ID, task_folder=task_folder, userID=userID, basename=basename, filename=filename, path=filepath, ext=ext, version=version, comment=comment, serverID=serverID, pub=pub, forceLink=forceLink, work=work )
                  print file_apiResult
          elif presetName == 'hiero.exporters.FnExternalRender.NukeRenderTask':
            #Skip - user to publish element at comp render time
            pass

          else:
            pass
          
          ''' ****************** NIM END PUBLISH ELEMENT ****************** '''
      
      # Dont add empty groups
      if len(taskGroup.children()) > 0:
        self._submission.addChild( taskGroup )
            
    # If processor is flagged as Synchronous, flag tasks too
    if self._synchronous:
      self._submission.setSynchronous()

    if self._submission.children():
    
      # Detect any duplicates
      self.processTaskPreQueue()

      self._submission.addToQueue()

    NimShotProcessor._versionUpPreviousExports = False # Reset this after export
Example #4
0
    def __init__(self, preset, itemTypes):
        IProcessorUI.__init__(self)

        self._preset = None
        self._exportTemplate = None
        self._exportStructureViewer = None
        self._contentElement = None
        self._contentScrollArea = None
        self._contentUI = None
        self._editMode = IProcessorUI.ReadOnly
        self._itemTypes = itemTypes
        self._tags = []
        self._project = None
        self._exportItems = []

        self.setPreset(preset)
        '''
    #######################################################
    # NIM VARS
    '''
        self.app = nimFile.get_app()
        self.prefs = nimPrefs.read()
        try:
            self.user = self.prefs['NIM_User']
            self.pref_job = self.prefs[self.app + '_Job']
            self.pref_show = self.prefs[self.app + '_Show']
            self.pref_server = self.prefs[self.app + '_ServerPath']
        except:
            #return False
            pass

        self.nim_OS = platform.system()

        self.nim_userID = nimAPI.get_userID(self.user)
        if not self.nim_userID:
            nimUI.GUI().update_user()
            userInfo = nim.NIM().userInfo()
            self.user = userInfo['name']
            self.nim_userID = userInfo['ID']

        print "NIM: user=%s" % self.user
        print "NIM: userID=%s" % self.nim_userID
        print "NIM: default job=%s" % self.pref_job

        #Get NIM Jobs
        self.nim_jobID = None
        self.nim_jobs = nimAPI.get_jobs(self.nim_userID)
        if not self.nim_jobs:
            print "No Jobs Found"
            self.nim_jobs["None"] = "0"

        #self.nim_shows = []
        self.nim_servers = {}

        self.nim_shows = {}
        self.nim_showDict = {}
        self.nim_showChooser = QtWidgets.QComboBox()
        self.nim_serverChooser = QtWidgets.QComboBox()

        self.nim_jobPaths = {}
        self.nim_showPaths = {}
        self.nim_showFolder = ''
        self.nim_serverOSPath = ''

        #Get NIM Element Types
        self.pref_elementType = ''
        self.element = ''
        self.elementID = None
        self.nim_elementTypes = []
        self.nim_elementTypesDict = {}
        self.nim_elementTypes = nimAPI.get_elementTypes()

        #Get NIM Task Types
        self.pref_taskType = ''
        self.task = ''
        self.taskID = None
        self.nim_taskTypes = []
        self.nim_taskTypesDict = {}
        self.nim_taskFolderDict = {}
        self.nim_taskTypes = nimAPI.get_tasks(app='NUKE', userType='all')

        self.nim_publishElementCheckbox = QtWidgets.QCheckBox()
        self.nim_publishElement = False

        self.nim_publishCompCheckbox = QtWidgets.QCheckBox()
        self.nim_publishComp = False

        self.loadingNimUI = False
        '''