Пример #1
0
    def markConversationAsSeen(self, conversationId, resourceId):
        '''Asyncrounous mark conversations as seen.

        *conversationId* should be the id of the conversation and *participantId*
        the id of the participant in that conversation.

        '''
        participant = self._session.query(
            'select last_visit from Participant where resource_id is '
            '"{0}" and conversation_id is "{1}"'.format(
                resourceId, conversationId
            )
        ).first()

        self._conversations[conversationId] = []

        if participant:
            participant['last_visit'] = datetime.datetime.now()
            participant.session.commit()

            event = ftrack.Event(
                topic='ftrack.conversation.seen',
                data=dict(
                    conversation=conversationId,
                    user_id=resourceId,
                    session_id=self._session_id
                )
            )

            ftrack.EVENT_HUB.publish(event)
            self._onConversationSeen(event)
Пример #2
0
    def _reload(self):
        '''Return events based on current context.'''
        events = []
        response = ftrack.EVENT_HUB.publish(ftrack.Event(
            'ftrack.crew.notification.get-events',
            data=dict(context=self._context)),
                                            synchronous=True)

        if len(response):
            events = response[0]

        return events
Пример #3
0
    def showAbout(self):
        '''Display window with about information.'''
        self.focus()

        aboutDialog = _about.AboutDialog(self)

        environmentData = os.environ.copy()
        environmentData.update({
            'PLATFORM': platform.platform(),
            'PYTHON_VERSION': platform.python_version()
        })

        versionData = [{
            'name': 'ftrack connect',
            'version': ftrack_connect.__version__,
            'core': True,
            'debug_information': environmentData
        }]

        # Import ftrack module and and try to get API version and
        # to load information from other plugins using hook.
        try:
            import ftrack
            apiVersion = ftrack.api.version_data.ftrackVersion
            environmentData['FTRACK_API_VERSION'] = apiVersion

            responses = ftrack.EVENT_HUB.publish(
                ftrack.Event(
                    'ftrack.connect.plugin.debug-information'
                ),
                synchronous=True
            )

            for response in responses:
                if isinstance(response, dict):
                    versionData.append(response)
                elif isinstance(response, list):
                    versionData = versionData + response

        except Exception:
            pass

        aboutDialog.setInformation(
            versionData=versionData,
            server=os.environ.get('FTRACK_SERVER', 'Not set'),
            user=getpass.getuser(),
        )

        aboutDialog.exec_()
Пример #4
0
    def _loadActionsForContext(self, context):
        '''Obtain new actions synchronously for *context*.'''
        discoveredActions = []

        results = ftrack.EVENT_HUB.publish(ftrack.Event(
            topic='ftrack.action.discover', data=dict(selection=context)),
                                           synchronous=True)

        for result in results:
            if result:
                for action in result.get('items', []):
                    discoveredActions.append(
                        ActionBase(action, is_new_api=False))

        session = ftrack_connect.session.get_shared_session()
        results = session.event_hub.publish(ftrack_api.event.base.Event(
            topic='ftrack.action.discover', data=dict(selection=context)),
                                            synchronous=True)

        for result in results:
            if result:
                for action in result.get('items', []):
                    discoveredActions.append(
                        ActionBase(action, is_new_api=True))

        # Sort actions by label
        groupedActions = []
        for action in discoveredActions:
            action['selection'] = context
            added = False
            for groupedAction in groupedActions:
                if action['label'] == groupedAction[0]['label']:
                    groupedAction.append(action)
                    added = True

            if not added:
                groupedActions.append([action])

        # Sort actions by label
        groupedActions = sorted(
            groupedActions,
            key=lambda groupedAction: groupedAction[0]['label'].lower())

        self.logger.debug('Discovered actions: {0}'.format(groupedActions))
        self._actions = groupedActions
        self._updateRecentSection()
        self._updateAllSection()
Пример #5
0
    def sendMessage(self, receiverId, text, conversationId=None):
        '''Send *text* to subscribers.'''
        data = dict(
            sender=self.sender,
            text=text,
            receiver=receiverId,
            conversation=conversationId,
            date=str(datetime.datetime.utcnow()),
            id=str(uuid.uuid1())
        )
        ftrack.EVENT_HUB.publish(
            ftrack.Event(
                topic='ftrack.chat.message',
                data=data
            )
        )

        return data
Пример #6
0
    def _sendHeartbeat(self):
        '''Send out heartbeats every 30 seconds.'''
        while True:

            event = ftrack.Event(
                topic='ftrack.crew.presence-heartbeat',
                target='session_id={0}'.format(self._data['session_id']),
                data=self.data
            )

            ftrack.EVENT_HUB.publish(event)

            for key, value in self._subscriptions.items():
                if time.time() > value['time'] + self.PRUNE_TIMEOUT:
                    ftrack.EVENT_HUB.unsubscribe(value['subscription'])

                    self._onExit(value['data'])

                    del self._subscriptions[key]

            time.sleep(self.HEARTBEAT_INTERVAL)
Пример #7
0
    def _publishLaunchActionEvent(self, action):
        '''Launch *action* asynchronously and emit *actionLaunched* when completed.'''
        try:
            if action.is_new_api:
                session = ftrack_connect.session.get_shared_session()
                results = session.event_hub.publish(
                    ftrack_api.event.base.Event(topic='ftrack.action.launch',
                                                data=action),
                    synchronous=True)
            else:
                results = ftrack.EVENT_HUB.publish(ftrack.Event(
                    topic='ftrack.action.launch', data=action),
                                                   synchronous=True)

        except Exception as error:
            results = [{
                'success': False,
                'message': 'Failed to launch action'
            }]
            self.logger.warning(
                u'Action launch failed with exception: {0}'.format(error))

        self.logger.debug('Launched action with result: {0}'.format(results))
        self.actionLaunched.emit(action, results)
Пример #8
0
    def enter(self, data=None):
        '''Broadcast presence with *data* and start sending out heartbeats.'''

        if not data:
            data = dict()

        self._data.update(data)

        # Set last activity when logging in the first time.
        # This will give the other user an indication on how long you've
        # been online.
        # TODO: Update this value when user is active in host application.
        self._last_activity = str(datetime.datetime.utcnow())

        subscriptionExpression = (
            'topic=ftrack.crew.presence-enter '
            'and source.user.username != {0}'.format(
                getpass.getuser()
            )
        )

        ftrack.EVENT_HUB.subscribe(
            subscriptionExpression,
            self._onPresenceEvent
        )

        ftrack.EVENT_HUB.publish(
            ftrack.Event(
                topic='ftrack.crew.presence-enter',
                data=self.data
            ),
            onReply=self._onEnterReplyEvent
        )

        self._initiateHeartbeats()
        self._initiateChatSubscription()
Пример #9
0
    def launch(self, event):
        """Callback method for DJVView action."""

        # Launching application
        if "values" in event["data"]:

            applicationIdentifier = event["data"]["applicationIdentifier"]
            application = self.applicationStore.getApplication(
                applicationIdentifier
            )
            context = event["data"].copy()
            context["source"] = event["source"]
            command = self.launcher._getApplicationLaunchCommand(
                application, context
            )

            success = True
            message = '{0} application started.'.format(application['label'])

            command.append(event["data"]["values"]["path"])

            try:
                options = dict(
                    env={},
                    close_fds=True
                )

                # Ensure subprocess is detached so closing connect will not
                # also close launched applications.
                if sys.platform == 'win32':
                    options['creationflags'] = subprocess.CREATE_NEW_CONSOLE
                else:
                    options['preexec_fn'] = os.setsid

                self.logger.debug(
                    'Launching {0} with options {1}'.format(command, options)
                )
                process = subprocess.Popen(command, **options)

            except (OSError, TypeError):
                self.logger.exception(
                    '{0} application could not be started with command "{1}".'
                    .format(applicationIdentifier, command)
                )

                success = False
                message = '{0} application could not be started.'.format(
                    application['label']
                )

            else:
                self.logger.debug(
                    '{0} application started. (pid={1})'.format(
                        applicationIdentifier, process.pid
                    )
                )

            return {
                'success': success,
                'message': message
            }

        data = event["data"]
        data["items"] = []

        # Starting a job to show user the progress of scanning for files.
        job = ftrack.createJob("DJV: Scanning for files.", "queued",
                               ftrack.User(id=event["source"]["user"]["id"]))
        job.setStatus("running")

        try:
            ftrack.EVENT_HUB.publish(
                ftrack.Event(
                    topic='djvview.launch',
                    data=data
                ),
                synchronous=True
            )
            session = get_shared_session()
            session.event_hub.publish(
                ftrack_api.event.base.Event(
                    topic='djvview.launch',
                    data=data
                ),
                synchronous=True
            )
        except:
            job.setStatus("failed")
        else:
            job.setStatus("done")

        return {
            "items": [
                {
                    "label": "Items to view",
                    "type": "enumerator",
                    "name": "path",
                    "data": sorted(
                        data["items"],
                        key=itemgetter("label"),
                        reverse=True
                    )
                }
            ]
        }
Пример #10
0
    def launch(self, applicationIdentifier, context=None):
        '''Launch application matching *applicationIdentifier*.

        *context* should provide information that can guide how to launch the
        application.

        Return a dictionary of information containing:

            success - A boolean value indicating whether application launched
                      successfully or not.
            message - Any additional information (such as a failure message).

        '''
        # Look up application.
        applicationIdentifierPattern = applicationIdentifier
        if applicationIdentifierPattern == 'hieroplayer':
            applicationIdentifierPattern += '*'

        application = self.applicationStore.getApplication(
            applicationIdentifierPattern)

        if application is None:
            return {
                'success':
                False,
                'message':
                ('{0} application not found.'.format(applicationIdentifier))
            }

        # Construct command and environment.
        command = self._getApplicationLaunchCommand(application, context)
        environment = self._getApplicationEnvironment(application, context)

        # Environment must contain only strings.
        self._conformEnvironment(environment)

        success = True
        message = '{0} application started.'.format(application['label'])

        try:
            options = dict(env=environment, close_fds=True)

            # Ensure that current working directory is set to the root of the
            # application being launched to avoid issues with applications
            # locating shared libraries etc.
            applicationRootPath = os.path.dirname(application['path'])
            options['cwd'] = applicationRootPath

            # Ensure subprocess is detached so closing connect will not also
            # close launched applications.
            if sys.platform == 'win32':
                options['creationflags'] = subprocess.CREATE_NEW_CONSOLE
            else:
                options['preexec_fn'] = os.setsid

            launchData = dict(command=command,
                              options=options,
                              application=application,
                              context=context)
            ftrack.EVENT_HUB.publish(ftrack.Event(
                topic='ftrack.connect.application.launch', data=launchData),
                                     synchronous=True)
            ftrack_connect.session.get_shared_session().event_hub.publish(
                ftrack_api.event.base.Event(
                    topic='ftrack.connect.application.launch',
                    data=launchData),
                synchronous=True)

            # Reset variables passed through the hook since they might
            # have been replaced by a handler.
            command = launchData['command']
            options = launchData['options']
            application = launchData['application']
            context = launchData['context']

            self.logger.debug('Launching {0} with options {1}'.format(
                command, options))

            #------------------------------------------------------
            # rather than launching program directly, launch python task launcher
            command = [
                os.getenv('ARK_PYTHON'), self.launchTask,
                environment['FTRACK_TASKID'], application['path']
            ]
            if application.get('launchArguments'):
                command.extend(application.get('launchArguments'))
            #------------------------------------------------------

            process = subprocess.Popen(command, **options)

        except (OSError, TypeError):
            self.logger.exception(
                '{0} application could not be started with command "{1}".'.
                format(applicationIdentifier, command))

            success = False
            message = '{0} application could not be started.'.format(
                application['label'])

        else:
            self.logger.debug('{0} application started. (pid={1})'.format(
                applicationIdentifier, process.pid))

        return {'success': success, 'message': message}
 def _onButtonClicked(self):
     '''Handle button clicked.'''
     ftrack.EVENT_HUB.publish(ftrack.Event(
         'ftrack.crew.notification.{0._type}'.format(self),
         data=self.value()),
                              synchronous=True)