Example #1
0
    def checkPath(self, path, dlg):
        """
        Validate catalog's path entered by the user.

        Arguments:
            path (str): Catalog's path.
            dlg (QDialog): Calling dialog.

        Returns:
            bool: *True* if path is valid; *False* otherwise.
        """
        full_path = os.path.join(path, 'code_aster')
        if not os.path.exists(full_path):
            title = translate("CatalogsView", "Error")
            message = translate(
                "CatalogsView", "Path does not exist:\n{}\n\n"
                "You must select a directory that contains "
                "a 'code_aster' subdirectory.")
            Q.QMessageBox.critical(dlg, title, message.format(full_path))
            return False

        items = self._items()
        item = [i for i in items if i[1] == path]
        if item:
            title = translate("CatalogsView", "Error")
            message = translate("CatalogsView", "Path '{}' is already in use")
            Q.QMessageBox.critical(dlg, title, message.format(path))
            return False

        return True
Example #2
0
    def checkLabel(self, label, dlg):
        """
        Validate catalog's label entered by the user.

        Arguments:
            label (str): Catalog's label.
            dlg (QDialog): Calling dialog.

        Returns:
            bool: *True* if label is valid; *False* otherwise.
        """
        for internal in ['stable', 'testing']:
            if label == internal:
                title = translate("CatalogsView", "Error")
                message = translate("CatalogsView",
                                    "Label '{}' is reserved for internal use")
                Q.QMessageBox.critical(dlg, title, message.format(label))
                return False

        items = self._items()
        items += [(i, CFG.get('Versions', i)) for i in CFG.options('Versions')]
        item = [i for i in items if i[0] == label]
        if item:
            title = translate("CatalogsView", "Error")
            message = translate("CatalogsView", "Label '{}' is already in use")
            Q.QMessageBox.critical(dlg, title, message.format(label))
            return False

        return True
Example #3
0
    def _update_result(self):
        """
        Assign calculation state to the first result and remove
        it from list. In successfull case begin simulation for next
        result or interrupt simulation otherwise.
        """
        stagename = self._name(self.current_stage)
        current = self.current
        if current.state & SO.Success:
            copy_error = self._copy_results()
            if copy_error:
                current.state = SO.Error
                self.log(translate('Runner',
                                   "{0} result file(s) has(have) not been "
                                   "copied to their destination. "
                                   "Following stages will probably fail.")
                         .format(copy_error))
            else:
                self.log(translate('Runner',
                                   'Stage "{0}" calculation succeeded '
                                   'with state {1} ({2})')
                         .format(stagename, SO.name(current.state),
                                 current.state))
                self._queue.pop(0)
                self.start_next()

        if not current.state & SO.Success:
            self.log(translate('Runner',
                               'Stage "{0}" calculation failed. Interruption')
                     .format(stagename))
            self.cancel_next()
Example #4
0
    def node(self, node):
        """
        Set object to be edited.

        Arguments:
            node (Node): Object to be edited (*Command*, *Comment* or
                *Case* object).
        """
        if self._node is node:
            return

        self._node = node

        if node is not None:
            cname = ''
            pixmap = Q.QPixmap()
            node_type = get_node_type(node)
            if node_type in (NodeType.Command, NodeType.Variable):
                self._prev_state = node.comment.content \
                    if node.comment is not None else ''
                cname = translate("AsterStudy", "Edit comment")
                pixmap = load_pixmap("as_pic_edit_comment.png")
            elif node_type in (NodeType.Comment, ):
                self._prev_state = node.content
                cname = translate("AsterStudy", "Edit comment")
                pixmap = load_pixmap("as_pic_edit_comment.png")
            elif node_type in (NodeType.Case, ):
                self._prev_state = node.description
                cname = translate("AsterStudy", "Edit description")
                pixmap = load_pixmap("as_pic_edit_comment.png")
            if self._prev_state is not None:
                self.editor.setPlainText(self._prev_state)
            self._controllername = cname
            self.setWindowTitle(self.controllerName())
            self.setPixmap(pixmap)
Example #5
0
    def _updateState(self):
        """
        Update panel's state.
        """
        if self.variable is None:
            op_name = translate("VariablePanel", "Create variable")
            op_pixmap = load_pixmap("as_pic_new_variable.png")
        else:
            op_name = translate("VariablePanel", "Edit variable")
            op_pixmap = load_pixmap("as_pic_edit_variable.png")
        self._controllername = op_name
        self.setWindowTitle(op_name)
        self.setPixmap(op_pixmap)

        self._vins.menu().clear()

        vnames = sorted(self._variableNames())
        fnames = sorted([i + '()' for i in self._functionNames()])

        for i in vnames:
            self._vins.menu().addAction(i)

        if vnames and fnames:
            self._vins.menu().addSeparator()

        for f in fnames:
            a = self._vins.menu().addAction(f)
            f = a.font()
            f.setItalic(True)
            a.setFont(f)

        self._vins.menu().setEnabled(not self._vins.menu().isEmpty())
        self._vcomp.setModel(Q.QStringListModel(vnames + fnames, self._vcomp))

        self.updateButtonStatus()
Example #6
0
    def _text(self, short=False):
        """
        Get internal representation of the item's filename.

        Arguments:
            short (Optional[bool]): Says long or short reprsentation to
                get.

        Returns:
            str: String representation of filename.
        """
        prefix = NodeType.value2str(NodeType.Unit) + ": " if not short else ''
        if self.filename:
            if self.is_reference:
                res = external_file(self.filename)
                if res is None:
                    res = "<{}>".format(translate("DataFiles", "undefined"))
                res = res if short else res + " ({})".format(self.filename)
            else:
                res = os.path.basename(self.filename) if short \
                    else self.filename
        else:
            res = "<{}>".format(translate("DataFiles", "undefined"))
        if self.embedded and not self.is_reference:
            res += ' ({})'.format(translate("DataFiles", "embedded"))
        return prefix + res
Example #7
0
    def showEvent(self, event):
        """
        Reimplemented for internal reason: updates the title
        depending on read only state, etc.
        """
        title = translate("ParameterPanel", "View command") \
            if self.isReadOnly() else \
            translate("ParameterPanel", "Edit command")
        self.setWindowTitle(title)

        hide_unused = self.astergui().action(ActionType.HideUnused)
        hide_unused.setVisible(True)
        hide_unused.setChecked(self.isReadOnly())

        # update meshview
        meshes = avail_meshes_in_cmd(self.command())
        for i, mesh in enumerate(meshes):
            filename, meshname = get_cmd_mesh(mesh)
            if filename:
                if i > 0:
                    self.meshview().displayMEDFileName(filename, meshname, 1.0,
                                                       False)
                else:
                    self.meshview().displayMEDFileName(filename, meshname, 1.0,
                                                       True)

        super(ParameterPanel, self).showEvent(event)
Example #8
0
    def __init__(self, file_name, astergui, parent=None, **kwargs):
        """
        Create editor.

        Arguments:
            file_name (str): File path.
            astergui (AsterGui): AsterGui instance.
            parent (Optional[QWidget]): Parent widget. Defaults to
                *None*.
            **kwargs: Keyword arguments.
        """
        super(TextFileEditor,
              self).__init__(parent=parent,
                             name=translate("AsterStudy", "Edit file"),
                             astergui=astergui,
                             **kwargs)
        self.file_name = file_name
        self.prev_state = _text2unicode(read_file(file_name))

        title = translate("AsterStudy", "Edit file") + " '{}'"
        self.setWindowTitle(title.format(get_base_name(file_name)))
        self.setPixmap(load_pixmap("as_pic_edit_file.png"))

        self.editor = Q.QTextEdit(self)
        self.editor.setLineWrapMode(Q.QTextEdit.NoWrap)
        self.setLayout(Q.QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.editor)

        self.editor.setPlainText(self.prev_state)
        self.editor.textChanged.connect(self.updateButtonStatus)
Example #9
0
    def __init__(self, stage, astergui, parent=None, **kwargs):
        """
        Create editor.

        Arguments:
            stage (Stage): Stage to edit.
            astergui (AsterGui): AsterGui instance.
            parent (Optional[QWidget]): Parent widget. Defaults to
                *None*.
            **kwargs: Keyword arguments.
        """
        super(StageTextEditor,
              self).__init__(parent=parent,
                             name=translate("StageTextEditor", "Edit stage"),
                             astergui=astergui,
                             **kwargs)

        self.stage = stage
        self.prev_state = stage.get_text()

        title = translate("StageTextEditor", "Edit stage '{}'")
        self.setWindowTitle(title.format(stage.name))
        self.setPixmap(load_pixmap("as_pic_edit_stage.png"))

        self.editor = TextEditor(self)
        v_layout = Q.QVBoxLayout(self)
        v_layout.addWidget(self.editor)
        commands = [j for i in [CATA.get_category(i) \
                                    for i in CATA.get_categories()] for j in i]
        self.editor.setKeywords(commands, 0, Q.QColor("#ff0000"))
        self.editor.setText(self.prev_state)
        self.editor.textChanged.connect(self.updateButtonStatus)
        self.setFocusProxy(self.editor)
        astergui.preferencesChanged.connect(self.editor.updateSettings)
        self.editor.updateSettings(self.astergui().preferencesMgr())
Example #10
0
 def performChanges(self, close=True):
     """
     Validate and store the command into data model.
     """
     wid = self.currentParameterView()
     if wid is not None:
         view = wid.view()
         if view.validate():
             cur_path = self.currentPath()
             if self.isCurrentCommand():
                 self.store()
                 self._files_model.update()
                 if self.astergui() is not None:
                     opname = translate("ParameterPanel", "Edit command")
                     self.astergui().study().commit(opname)
                     self.astergui().update()
                 if close:
                     self.performDissmis(False)
                 msg = translate("ParameterPanel",
                                 "Command '{}' successfully stored")
                 msg = msg.format(self._name.text())
                 self.astergui().showMessage(msg)
             else:
                 child_val = view.itemValue()
                 self._removeCurrentView()
                 curview = self.currentParameterView()
                 subitem = curview.view().findItemByPath(cur_path)
                 if subitem is not None:
                     subitem.setItemValue(child_val)
     self._updateState()
     self.updateButtonStatus()
Example #11
0
    def headerLabels(self):
        """
        Gets horizontal header names from 'NOM_PARA' and 'NOM_RESU' parameters.
        """
        param_name = translate("ParameterPanel", "Parameter")
        func_name = translate("ParameterPanel", "Function")

        item = self.rootItem()
        master = item.masterItem()
        if master is not None:
            parent_item = master.parentItem()
            if parent_item is not None:
                for item in parent_item.childItems():
                    if not item.isUsed():
                        continue
                    if item.itemName() == 'NOM_PARA':
                        param_name = \
                            Options.translate_command(self.command().title,
                                                      self.itemName(),
                                                      item.itemValue())
                    elif item.itemName() == 'NOM_RESU':
                        func_name = item.itemValue()
        labels = list()
        labels.append(param_name)
        path = self.itemPath().path()
        if re.match("^.*[.]VALE$", path):
            labels.append(func_name)
        elif re.match("^.*[.]VALE_C$", path):
            labels.append(translate("ParameterPanel", "Real"))
            labels.append(translate("ParameterPanel", "Imaginary"))
        return labels
Example #12
0
    def _copy_results(self):
        """Copy/move results files to their final destination.

        Note:
            Results are put in the stage directory by the profile,
                they are copied to the path specified by the user
                in this function. This does not include result databases.
        """
        error = 0
        stage = self.current_stage
        stagedir = stage.folder
        for fileinfo in stage.handle2info.values():
            src = osp.join(stagedir, osp.basename(fileinfo.filename))
            if fileinfo.attr & FileAttr.Out:
                try:
                    self.log(translate('Runner',
                                       "Copying result {0!r}")
                             .format(fileinfo.filename))
                    parent = osp.dirname(fileinfo.filename)
                    if not osp.isdir(parent):
                        os.makedirs(parent)
                    dest = fileinfo.filename if not osp.isdir(src) else parent
                    shutil.move(src, dest)
                except (IOError, OSError) as exc:
                    self.log(translate('Runner',
                                       'ERROR: Copy failed: {0}').format(exc))
                    error += 1
        return error
Example #13
0
def change_text(text, strict):
    """Check for unsupported features and change text."""
    # _inc = re.compile(r"^ *INCLUDE *\(", re.M)
    replace = strict & ConversionLevel.Partial != 0
    for expr, msg in [
        (r"^ *(if|for|import|from|try|def)\b",
         translate(
             "AsterStudy",
             "Python statements can not be edited in graphical mode."
             "\nYou can only edit this commands file in text mode.")),
        (r"^(.*?\[ *None *\])",
         translate("AsterStudy",
                   "List of code_aster results is not supported.")),
        (r"^ *[^#]*DEFI_FICHIER",
         translate(
             "AsterStudy", "Command DEFI_FICHIER is not supported in "
             "graphical mode.")),
        (r"^ *[^#]*INCLUDE",
         translate(
             "AsterStudy", "Command INCLUDE is not supported in "
             "graphical mode, please add a stage instead.")),
    ]:
        err = _check_unsupported(text, expr, msg, replace)
        if err:
            text = err
            break
    return _change_text(text)
Example #14
0
    def eventFilter(self, obj, event):
        """
        Filter events if this object has been installed as an event
        filter for the watched object.

        Shows dedicated context menu for categories panel.

        Arguments:
            obj (QObject): Watched object.
            event (QEvent): Event being processed.

        Returns:
            bool: *True* if event should be filtered out (i.e. if
            further processing should be stopped); *False* otherwise.
        """
        if obj == self.panel and event.type() == Q.QEvent.ContextMenu:
            menu = Q.QMenu()
            menu.addAction(translate("ShowAllPanel", "Expand all"),
                           self.expandAll)
            menu.addAction(translate("ShowAllPanel", "Collapse all"),
                           self.collapseAll)
            event.accept()
            menu.exec_(self.mapToGlobal(event.pos()))
        # pragma pylint: disable=no-member
        return False
Example #15
0
 def applyChanges(self):
     """
     Redefined from *EditionWidget* class.
     """
     command = self._selected()
     if command:
         cmdobj = None
         selected = self.astergui().selected(Context.DataSettings)
         stage = self.astergui().study().node(selected[0])
         if get_node_type(stage) not in (NodeType.Stage,):
             stage = stage.stage
         if stage is not None:
             try:
                 cmdobj = stage.add_command(command)
             except Exception: # pragma pylint: disable=broad-except
                 cmdobj = None
         if cmdobj is not None:
             with auto_dupl_on(self.astergui().study().activeCase):
                 self.astergui().study().commit(translate("AsterStudy",
                                                          "Add command"))
                 self.astergui().update(autoSelect=cmdobj,
                                        context=Context.DataSettings)
                 msg = translate("AsterStudy",
                                 "Command with type '{}' "
                                 "successfully added")
                 msg = msg.format(command)
                 self.astergui().showMessage(msg)
         else:
             self.astergui().study().revert()
Example #16
0
    def start_current(self):
        """Activate calculation simulation for next result."""
        stage = self.current_stage
        stages = self.stages_stack + [stage]
        stagename = self._name(stage)
        name = valid_filename(stagename)
        params = self._params
        self.log(translate('Runner', 'Starting "{0}"...').format(stagename))
        try:
            server = params['server']
            servcfg = self._infos.server_config(server)
            stage.set_remote(params.get('remote_folder'))
            if not servcfg:
                raise RunnerError(translate("Runner",
                                            "Server {0!r} is not available.")
                                  .format(server))
            prof = create_profil_for_current(None, self._case,
                                             stages, name, params, servcfg)
            dbtype, _ = prof.get_base('D')
            remote_in_files = [i.path for i in prof.get_data() \
                                      if i.host and i.type == dbtype]
            salome_job = create_command_job(servcfg, params, prof, stage)
            jobid = self.hdlr.createJob(salome_job)
            try:
                self._infos.export_remote_input_files(server,
                                                      remote_in_files,
                                                      salome_job.work_directory)
                self.hdlr.launchJob(jobid)
                self.save_jobs()
            except Exception as exc:
                msg = translate('Runner',
                                'Error during submission of "{0}"'
                                .format(stagename))
                self.log(msg)
                self.log(str(exc))
                raise RunnerError(msg, str(exc))

        except RunnerError as exc:
            self.log("ERROR: {0}".format(exc.msg))
            self.stop()
            raise

        else:
            self.current.state = SO.Pending
            # Store job informations
            job = self.current.job
            job.jobid = str(jobid)
            job.server = server
            job.name = name
            job.mode = params['mode']
            job.set_parameters_from(params)
            job.start_time = current_time()
            job.description = params.get('description', '')
            self.log(translate('Runner',
                               'Stage "{0}" start calculation (jobid={1})')
                     .format(stagename, jobid))
Example #17
0
def get_object_info(obj, **kwargs):
    """
    Get object info to be displayed in tooltip.

    Arguments:
        obj (Node): Data model node.
        **kwargs: Arbitrary keyword arguments:

    Returns:
        str: Object's info.
    """
    node_type = get_node_type(obj)
    info = NodeType.value2str(node_type)
    if node_type == NodeType.Command:
        info += ": "
        if obj.type is None:
            name = translate("AsterStudy", "[noname]")
        else:
            name = obj.name
        info += bold(name)
        cata = obj.title
        title = translate_command(cata)
        tip = " ({title} / {name})" if title != cata else " ({name})"
        info += tip.format(title=italic(title), name=cata)
        if kwargs.get('with_parent_stage', False):
            info += "<br>"
            st_name = bold(obj.stage.name)
            info += translate("AsterStudy", "From stage: {}").format(st_name)
    elif node_type == NodeType.Comment:
        info += ":<br>"
        content = obj.content.split("\n")
        content = ["  # " + i for i in content]
        info += italic("\n".join(content))
    elif node_type == NodeType.Variable:
        info += ": "
        info += bold(obj.name)
        info += " ({})".format(italic(obj.expression))
    elif node_type == NodeType.Case:
        info += ": "
        info += bold(obj.name)
        if obj.description:
            info += "\n\n"
            info += obj.description
    elif node_type != NodeType.History:
        info += ": "
        info += bold(obj.name)
    if node_type in [
            NodeType.Case, NodeType.Stage, NodeType.Category, NodeType.Command
    ]:
        validity = Validity.value2str(obj.check())
        if validity:
            info += "<br>"
            info += font("Invalid:", color="#ff0000")
            info += ", ".join([bold(i.strip()) for i in validity.split(",")])
    info = preformat(info)
    return info
Example #18
0
    def _typeInformation(self):
        """
        Gets the information text about keyword type.
        """
        inflist = []
        kword = self.path().keyword()
        if kword is not None:
            kwtypelist = []
            kwdef = kword.definition
            enum = kwdef.get('into') is not None
            if enum and sorted(kwdef.get('into')) == ["NON", "OUI"]:
                txt = "'%s'/'%s'" % (bold(translate("ParameterPanel", "Yes")),
                                     bold(translate("ParameterPanel", "No")))
                inflist.append(txt)
            elif kwdef.get('typ') is not None:
                kwtypelist = to_list(kwdef.get('typ'))

            for kwtype in kwtypelist:
                if kwtype is None:
                    continue

                if kwtype == 'I':
                    txt = bold(translate("ParameterPanel", "integer"))
                    lim = self._numberLimitsInfo(kwdef.get('val_min'),
                                                 kwdef.get('val_max'))
                    if len(lim):
                        txt += " " + lim
                elif kwtype == 'R':
                    txt = bold(translate("ParameterPanel", "float"))
                    lim = self._numberLimitsInfo(kwdef.get('val_min'),
                                                 kwdef.get('val_max'))
                    if len(lim):
                        txt += " " + lim
                elif kwtype == 'TXM':
                    txt = bold(translate("ParameterPanel", "string"))
                elif is_subclass(kwtype, CATA.package('DataStructure').CO):
                    txt = bold(translate("ParameterPanel", "macro name"))
                elif isinstance(kwtype, (types.TypeType, types.ClassType)):
                    txt = translate("ParameterPanel", "object with type")
                    txt += bold(" '%s'" % kwtype.__name__)
                else:
                    txt = bold(str(kwtype))

                if len(txt):
                    if enum:
                        txt += " (%s)" % italic(translate("ParameterPanel",
                                                          "enumerated"))
                    inflist.append(txt)
        info = ""
        if len(inflist):
            islist = self.path().isKeywordSequence() and \
                not self.path().isInSequence()
            prefix = translate("ParameterPanel", "List with types") \
                if islist else translate("ParameterPanel", "Value types")
            info = prefix + ": " + ", ".join(inflist)
        return info
Example #19
0
def bool2str(value):
    """
    Convert boolean value to string representation.

    Returns:
        str: 'Yes' for *True*; 'No' for *False* and empty string for
        *None*.
    """
    if value is None:
        return ''
    return translate("DataFiles", "Yes") if value \
        else translate("DataFiles", "No")
Example #20
0
    def applyChanges(self):
        """
        Redefined from *EditionWidget* class.
        """
        # pragma pylint: disable=no-member
        result = False

        var = self.variable
        edit = var is not None

        name = self._variableName()
        expr = self._variableExpression()
        comment = self._variableComment()

        if edit:
            try:
                with auto_dupl_on(self.stage.model.current_case):
                    var.update(expr, name)
                    if comment:
                        var.comment = comment
                    elif var.comment is not None:
                        var.comment.delete()
                    result = True
            except CyclicDependencyError:
                message = translate("AsterStudy", "Cyclic dependency detected")
                Q.QMessageBox.critical(self, "AsterStudy", message)
                result = False
        else:
            try:
                with auto_dupl_on(self.stage.model.current_case):
                    if self.stage is not None:
                        var = self.stage.add_variable(name, expr)
                        if comment:
                            var.comment = comment
            except StandardError:
                var = None

            result = var is not None

        if self.controllerOwner() is None:
            if result:
                if edit:
                    op_name = translate("VariablePanel", "Edit variable")
                else:
                    op_name = translate("VariablePanel", "Create variable")
                self.astergui().study().commit(op_name)
                self.astergui().update(autoSelect=var,
                                       context=Context.DataSettings)
            else:
                self.astergui().study().revert()

        self._updateState()
Example #21
0
    def title(self):
        """
        Get directory title.

        Returns:
            str: Directory title.
        """
        val = '?'
        if self.dirType == Directory.InDir:
            val = translate("DataFiles", "Input directory")
        elif self.dirType == Directory.OutDir:
            val = translate("DataFiles", "Output directory")
        return val
Example #22
0
 def _updateMeshList(self):
     """
     Updates the mesh list in the combobox
     """
     meshlist = avail_meshes(parameterPanel(self).pendingStorage())
     meshlist.reverse()
     self.setMeshList(meshlist)
     msg = ""
     if len(meshlist) > 1:
         msg = translate("ParameterPanel", "More than one mesh found")
     elif len(meshlist) == 0:
         msg = translate("ParameterPanel", "No mesh found")
     self.setMessage(msg)
     self._meshActivated(self._mesh.currentIndex())
Example #23
0
 def stop(self):
     """Stop the case calculation process."""
     self.refresh()
     current = self.current
     if self.stop_current():
         current.state = SO.Error
         self.cancel_next()
         self.log(translate('Runner',
                            'Run case "{0}" calculations process stopped')
                  .format(self._name(self._case)))
     else:
         self.log(translate('Runner',
                            'Run case "{0}" is already stopped.')
                  .format(self._name(self._case)))
Example #24
0
 def __download(self, url, file_path):
     try:
         # Setup progress dialog and download
         self.pDialog = xbmcgui.DialogProgress()
         self.pDialog.create('PGLiveTV', common.translate(30050), common.translate(30051))
         urllib.urlretrieve(url, file_path, self.video_report_hook)
         self.pDialog.close()
         return True
     except IOError:
         self.pDialog.close()
         common.showError(common.translate(30053))
     except KeyboardInterrupt:
         self.pDialog.close()
     return False
Example #25
0
    def to_str(typ):
        """Convert message type to string representation.

        Arguments:
            typ (int): Message type (*MsgType*).

        Returns:
            str: String representation of the type.
        """
        return {
            MsgType.Runner: translate("Message", "Runner"),
            MsgType.Stage: translate("Message", "Stage"),
            MsgType.Command: translate("Message", "Command"),
        }[typ]
Example #26
0
    def to_str(level):
        """Convert message level to string representation.

        Arguments:
            level (int): Message level (*MsgLevel*).

        Returns:
            str: String representation of the level.
        """
        return {
            MsgLevel.Debug: translate("Message", "DEBUG"),
            MsgLevel.Info: translate("Message", "INFO"),
            MsgLevel.Warn: translate("Message", "WARNING"),
            MsgLevel.Error: translate("Message", "ERROR"),
        }[level]
Example #27
0
    def __init__(self, panel, **kwargs):
        """
        Create view.

        Arguments:
            **kwargs: Arbitrary keyword arguments.
        """
        super(ParameterMeshGroupView, self).__init__(panel, **kwargs)

        self.setStretchable(True)

        self._mesh = QComboBox(self)
        self._mesh.setObjectName("MESH")
        self._msg = QLabel(self)
        self._list = QTreeWidget(self)
        self._list.setAllColumnsShowFocus(True)
        self._list.setSelectionMode(QTreeWidget.SingleSelection)
        self._list.setColumnCount(2)
        titles = []
        titles.append(translate("AsterStudy", "Name"))
        titles.append(translate("AsterStudy", "Size"))
        self._list.setHeaderLabels(titles)
        self._list.header().setSectionResizeMode(QHeaderView.ResizeToContents)
        self._list.header().setStretchLastSection(True)

        manlabel = QLabel(translate("ParameterPanel", "Manual selection"),
                          self)
        manlabel.setToolTip(
            translate(
                "ParameterPanel", "Enter manually the wanted groups if "
                "not present in the list"))
        self._manual = QLineEdit(self)
        self._manual.setObjectName("MANUAL_INPUT")

        base = self.grid()
        base.addWidget(self._mesh, 0, 0, 1, -1)
        base.addWidget(self._msg, 1, 0, 1, -1)
        base.addWidget(self._list, 2, 0, 1, -1)
        base.addWidget(manlabel, 3, 0, 1, -1)
        base.addWidget(self._manual, 4, 0, 1, -1)

        self._mesh.activated[int].connect(self._meshActivated)
        self._updateMeshList()

        self.meshFileChanged.connect(self.meshview().displayMEDFileName)
        self.meshGroupCheck.connect(self.meshview().displayMeshGroup)
        self.meshGroupUnCheck.connect(self.meshview().undisplayMeshGroup)
        self._list.itemChanged.connect(self.meshGroupToChange)
Example #28
0
    def __init__(self, astergui, parent=None):
        """
        Create `Show all` edition panel.

        Arguments:
            astergui (AsterGui): Parent AsterGui instance.
            parent (Optional[QWidget]): Parent widget. Defaults to
                *None*.
        """
        super(ShowAllPanel, self).__init__(parent=parent,
                                           name=translate("ShowAllPanel",
                                                          "Show all commands"),
                                           astergui=astergui)
        self.setWindowTitle(translate("ShowAllPanel", "Add command"))
        self.setPixmap(load_pixmap("as_pic_new_command.png"))
        v_layout = Q.QVBoxLayout(self)
        v_layout.setContentsMargins(0, 0, 0, 0)
        self.panel = Panel(self)
        description = Q.QGroupBox(self)
        description.setTitle(translate("ShowAllPanel", "Command description"))
        desc_layout = Q.QVBoxLayout(description)
        self.info = Q.QLabel(description)
        self.info.setWordWrap(True)
        self.info.setOpenExternalLinks(True)
        desc_layout.addWidget(self.info)
        for category in CATA.get_categories("showall"):
            # get commands from category
            items = CATA.get_category(category)
            if not items:
                continue
            # get translation for category's title
            view = CategoryView(translate_category(category),
                                parent=self.panel)
            view.category = category
            for item in items:
                # get translation for command
                title = translate_command(item)
                if title != item:
                    title = title + " ({})".format(item)
                view.addItem(title, item)
            self.panel.addWidget(view)
            connect(view.selected, self._selectionChanged)
            connect(view.doubleClicked, self._doubleClicked)
        v_layout.addWidget(self.panel)
        v_layout.addWidget(description)
        connect(self.astergui().selectionChanged, self.updateButtonStatus)
        self.panel.installEventFilter(self)
        self.setFocusProxy(self.panel)
Example #29
0
    def downloadVideo(self, url, title):
        common.log("Trying to download video " + str(url))

        # check url
        if url.startswith("plugin"):
            common.log("Video is not downloadable")
            return None

        path = common.getSetting("download_path")
        if not path:
            path = common.browseFolders(common.translate(30017))
            common.setSetting("download_path", path)

        title = getKeyboard(default=fu.cleanFilename(title), heading="Dragon Streams")
        if title == None or title == "":
            return None

        downloader = Downloader()
        downloaded_file = downloader.downloadMovie(url, path, fu.cleanFilename(title), ".flv")

        if downloaded_file == None:
            common.log("Download cancelled")
        else:
            common.log("Video " + url + " downloaded to '" + downloaded_file + "'")

        return downloaded_file
Example #30
0
    def _parseVirtualFolder(self, path):
        fullpath = self._getFullPath(path)
        data = fu.getFileContent(fullpath)
        data = data.replace("\r\n", "\n").split("\n")
        items = []
        for m in data:
            if m and m[0] != "#":
                index = m.find("=")
                if index != -1:
                    key = lower(m[:index]).strip()
                    value = m[index + 1 :]

                    index = value.find("|")
                    if value[:index] == "sports.devil.locale":
                        value = common.translate(int(value[index + 1 :]))
                    elif value[:index] == "sports.devil.image":
                        value = os.path.join(common.Paths.imgDir, value[index + 1 :])

                    if key == "title":
                        tmp = CListItem()
                        tmp["title"] = value
                    elif key == "url":
                        tmp["url"] = value
                        items.append(tmp)
                        tmp = None
                    elif tmp != None:
                        tmp[key] = value
        return items
    def _parseVirtualFolder(self, path):
        fullpath = self._getFullPath(path)
        data = fu.getFileContent(fullpath)
        data = data.replace('\r\n', '\n').split('\n')
        items = []
        for m in data:
            if m and m[0] != '#':
                index = m.find('=')
                if index != -1:
                    key = lower(m[:index]).strip()
                    value = m[index+1:]

                    index = value.find('|')
                    if value[:index] == 'sports.devil.locale':
                        value = common.translate(int(value[index+1:]))
                    elif value[:index] == 'sports.devil.image':
                        value = os.path.join(common.Paths.imgDir, value[index+1:])

                    if key == 'title':
                        tmp = CListItem()
                        tmp['title'] = value
                    elif key == 'url':
                        tmp['url'] = value
                        items.append(tmp)
                        tmp = None
                    elif tmp != None:
                        tmp[key] = value
        return items   
Example #32
0
    def downloadMovie(self, url, path, title, extension):
        if not os.path.exists(path):
            common.log('Path does not exist')
            return None
        if title == '':
            common.log('No title given')
            return None

        file_path = xbmc.makeLegalFilename(os.path.join(path, title + extension))
        file_path = urllib.unquote_plus(file_path)
        # Overwrite existing file?
        if os.path.isfile(file_path):
            self.pDialog = xbmcgui.Dialog()

            if not common.ask('File already exists. Overwrite?\n' + os.path.basename(file_path)):
                title = common.showOSK(urllib.unquote_plus(title), common.translate(30102))
                if not title:
                    return None
                file_path = xbmc.makeLegalFilename(os.path.join(path, title + extension))
                file_path = urllib.unquote_plus(file_path)
        
        success = self.__download(url, file_path)
        if success:
            return file_path
        else:
            return None
Example #33
0
    def downloadVideo(self, url, title):
        common.log('Trying to download video ' + str(url))

        # check url
        if url.startswith('plugin'):
            common.log('Video is not downloadable')
            return None

        path = common.getSetting('download_path')
        if not path:
            path = common.browseFolders(common.translate(30017))
            common.setSetting('download_path', path)

        title = getKeyboard(default = fu.cleanFilename(title),heading='SportsDevil')
        if title == None or title == '':
            return None

        downloader = Downloader()
        downloaded_file = downloader.downloadMovie(url, path,  fu.cleanFilename(title), '.flv')

        if downloaded_file == None:
            common.log ('Download cancelled')
        else:
            common.log('Video ' + url + " downloaded to '" + downloaded_file + "'")

        return downloaded_file
    def downloadMovie(self, url, path, title, extension):
        if not os.path.exists(path):
            common.log('Path does not exist')
            return None
        if title == '':
            common.log('No title given')
            return None

        file_path = xbmc.makeLegalFilename(
            os.path.join(path, title + extension))
        file_path = urllib.unquote_plus(file_path)
        # Overwrite existing file?
        if os.path.isfile(file_path):
            self.pDialog = xbmcgui.Dialog()

            if not common.ask('File already exists. Overwrite?\n' +
                              os.path.basename(file_path)):
                title = common.showOSK(urllib.unquote_plus(title),
                                       common.translate(30102))
                if not title:
                    return None
                file_path = xbmc.makeLegalFilename(
                    os.path.join(path, title + extension))
                file_path = urllib.unquote_plus(file_path)

        success = self.__download(url, file_path)
        if success:
            return file_path
        else:
            return None
Example #35
0
    def downloadVideo(self, url, title):
        common.log('Trying to download video ' + str(url))

        # check url
        if url.startswith('plugin'):
            common.log('Video is not downloadable')
            return None

        path = common.getSetting('download_path')
        if not path:
            path = common.browseFolders(common.translate(30017))
            common.setSetting('download_path', path)

        title = getKeyboard(default=fu.cleanFilename(title),
                            heading='SportsDevil')
        if title == None or title == '':
            return None

        downloader = Downloader()
        downloaded_file = downloader.downloadMovie(url, path,
                                                   fu.cleanFilename(title),
                                                   '.flv')

        if downloaded_file == None:
            common.log('Download cancelled')
        else:
            common.log('Video ' + url + " downloaded to '" + downloaded_file +
                       "'")

        return downloaded_file
    def getSearchPhrase(self):
        searchCache = os.path.join(common.Paths.cacheDir, 'search')
        try:
            curr_phrase = fu.getFileContent(searchCache)
        except:
            curr_phrase = ''
        search_phrase = getKeyboard(default = curr_phrase, heading = common.translate(30102))
        if search_phrase == '':
            return None
        xbmc.sleep(10)
        fu.setFileContent(searchCache, search_phrase)

        return search_phrase
Example #37
0
    def getSearchPhrase(self):
        searchCache = os.path.join(common.Paths.cacheDir, 'search')
        default_phrase = fu.getFileContent(searchCache)
        if not default_phrase:
            default_phrase = ''

        search_phrase = common.showOSK(default_phrase, common.translate(30102))
        if search_phrase == '':
            return None
        xbmc.sleep(10)
        fu.setFileContent(searchCache, search_phrase)

        return search_phrase
Example #38
0
 def update(self):
     
     def checkForUpdates():
         return None
     
     def doUpdates(typeName, updates):
         count = len(updates)
         
         head = "SportsDevil Updates - %s" % typeName
         
         msg = common.translate(30277)
         if count == 1:
             msg = common.translate(30276)
             
         question = ("%s %s: " % (count, msg)) + ', '.join(map(lambda u: u.split('/')[-1], updates.keys())) + '\n'
         question += common.translate(30278)
         
         updates = updates.values()
         
         countFailed = 0
 
         dlg = DialogQuestion()
         dlg.head = head
         if dlg.ask(question):
             dlg = DialogProgress()
             firstline = common.translate(30279)
             dlg.create(head, firstline, " ")
        
             for i in range(0, count):
                 update = updates[i]
                 percent = int((i+1.0)*100/count)
                 dlg.update(percent, firstline, update.name)
                 if not update.do():
                     countFailed += 1
             
             msg = " "
             if countFailed > 0:
                 msg = "%s %s" % (countFailed, common.translate(30280))
                 
             dlg.update(100, msg, " ")
             xbmc.sleep(500)
             dlg.close()
         
     allupdates = checkForUpdates()
     count = len(allupdates)
     if count == 0:
         common.showNotification('SportsDevil', common.translate(30273))
         return
     else:
         for key, value in allupdates.items():
             doUpdates(key, value)
Example #39
0
 def checkForUpdates():
     updates = {}          
     common.showNotification('SportsDevil', common.translate(30275))
     xbmcUtils.showBusyAnimation()
          
     catchersUpdates = self.syncManager.getUpdates(SyncSourceType.CATCHERS, common.Paths.catchersDir)
     if len(catchersUpdates) > 0:
         updates["Catchers"] = catchersUpdates    
     modulesUpdates = self.syncManager.getUpdates(SyncSourceType.MODULES, common.Paths.modulesDir)
     if len(modulesUpdates) > 0:
         updates["Modules"] = modulesUpdates
     
     xbmcUtils.hideBusyAnimation()
     return updates
        def doUpdates(typeName, updates):
            count = len(updates)

            head = "ViendoKodiStreaming Updates - %s" % typeName

            msg = common.translate(30277)
            if count == 1:
                msg = common.translate(30276)

            question = ("%s %s: " % (count, msg)) + ', '.join(map(lambda u: u.split('/')[-1], updates.keys())) + '\n'
            question += common.translate(30278)

            updates = updates.values()

            countFailed = 0

            dlg = DialogQuestion()
            dlg.head = head
            if dlg.ask(question):
                dlg = DialogProgress()
                firstline = common.translate(30279)
                dlg.create(head, firstline, " ")

                for i in range(0, count):
                    update = updates[i]
                    percent = int((i+1.0)*100/count)
                    dlg.update(percent, firstline, update.name)
                    if not update.do():
                        countFailed += 1

                msg = " "
                if countFailed > 0:
                    msg = "%s %s" % (countFailed, common.translate(30280))

                dlg.update(100, msg, " ")
                xbmc.sleep(500)
                dlg.close()
Example #41
0
    def update(self):               
        common.showNotification('SportsDevil', common.translate(30275))
        xbmcUtils.showBusyAnimation()
        updates = self.syncManager.getUpdates(SyncSourceType.CATCHERS, common.Paths.catchersDir)
        xbmcUtils.hideBusyAnimation()
        count = len(updates)
        
        if count == 0:
            common.showNotification('SportsDevil', common.translate(30273))
            return
        
        head = "SportsDevil Updates"
        
        msg = common.translate(30277)
        if count == 1:
            msg = common.translate(30276)
            
        question = ("%s %s: " % (count, msg)) + ', '.join(updates.keys()) + '\n'
        question += common.translate(30278)
        
        updates = updates.values()
        
        countFailed = 0

        dlg = DialogQuestion()
        dlg.head = head
        if dlg.ask(question):
            dlg = DialogProgress()
            firstline = common.translate(30279)
            dlg.create(head, firstline, " ")
       
            for i in range(0, count):
                update = updates[i]
                percent = int((i+1.0)*100/count)
                dlg.update(percent, firstline, update.name)
                if not update.do():
                    countFailed += 1
            
            msg = " "
            if countFailed > 0:
                msg = "%s %s" % (countFailed, common.translate(30280))
                
            dlg.update(100, msg, " ")
            xbmc.sleep(500)
            dlg.close()
Example #42
0
    def __parseCommands(self, item, src, convCommands):
        # common.log('_parseCommands called')
        # helping function
        def parseCommand(txt):
            command = {"command": txt, "params": ""}
            if txt.find("(") > -1:
                command["command"] = txt[0 : txt.find("(")]
                command["params"] = txt[len(command["command"]) + 1 : -1]
            return command

        try:
            src = src.encode("utf-8")
        except:
            pass
        for convCommand in convCommands:
            pComm = parseCommand(convCommand)
            command = pComm["command"]
            params = pComm["params"]

            if params.find("@REFERER@"):
                referer = item["referer"]
                if not referer:
                    referer = ""
                params = params.replace("@REFERER@", referer)

            if command == "convDate":
                src = cc.convDate(params, src)

            elif command == "convTimestamp":
                src = cc.convTimestamp(params, src)

            elif command == "select":
                src = cc.select(params, src)
                if not src:
                    continue

            elif command == "smart_unicode":
                src = enc.smart_unicode(params.strip("'").replace("%s", src))

            elif command == "safeGerman":
                src = enc.safeGerman(src)

            elif command == "safeRegex":
                src = enc.safeRegexEncoding(params.strip("'").replace("%s", enc.smart_unicode(src)))

            elif command == "replaceFromDict":
                dictName = str(params.strip("'"))
                path = os.path.join(common.Paths.dictsDir, dictName + ".txt")
                if not (os.path.exists(path)):
                    common.log("Dictionary file not found: " + path)
                    continue
                src = cc.replaceFromDict(path, src)

            elif command == "time":
                src = time.time()

            elif command == "timediff":
                src = dt.timediff(src, params.strip("'"))

            elif command == "offset":
                src = cc.offset(params, src)

            elif command == "getSource":
                src = cc.getSource(params, src)

            elif command == "getRedirect":
                src = get_redirected_url(params.strip("'").replace("%s", src))

            elif command == "quote":
                try:
                    src = urllib.quote(params.strip("'").replace("%s", urllib.quote(src)))
                except:
                    cleanParams = params.strip("'")
                    cleanParams = cleanParams.replace("%s", src.encode("utf-8"))
                    src = urllib.quote(cleanParams)

            elif command == "unquote":
                src = urllib.unquote(params.strip("'").replace("%s", src))

            elif command == "parseText":
                src = cc.parseText(item, params, src)

            elif command == "getInfo":
                src = cc.getInfo(item, params, src)

            elif command == "decodeBase64":
                src = cc.decodeBase64(src)

            elif command == "decodeRawUnicode":
                src = cc.decodeRawUnicode(src)

            elif command == "replace":
                src = cc.replace(params, src)

            elif command == "replaceRegex":
                src = cc.replaceRegex(params, src)

            elif command == "ifEmpty":
                src = cc.ifEmpty(item, params, src)

            elif command == "isEqual":
                src = cc.isEqual(item, params, src)

            elif command == "ifFileExists":
                src = cc.ifFileExists(item, params, src)

            elif command == "ifExists":
                src = cc.ifExists(item, params, src)

            elif command == "encryptJimey":
                src = crypt.encryptJimey(params.strip("'").replace("%s", src))

            elif command == "destreamer":
                src = crypt.destreamer(params.strip("'").replace("%s", src))

            elif command == "unixTimestamp":
                src = dt.getUnixTimestamp()

            elif command == "urlMerge":
                src = cc.urlMerge(params, src)

            elif command == "translate":
                try:
                    src = common.translate(int(src))
                except:
                    pass

            elif command == "camelcase":
                src = enc.smart_unicode(src)
                src = string.capwords(string.capwords(src, "-"))

            elif command == "demystify":
                print "demystify"
                src = crypt.doDemystify(src)
                print "after demystify", src

            elif command == "random":
                paramArr = params.split(",")
                minimum = int(paramArr[0])
                maximum = int(paramArr[1])
                src = str(random.randrange(minimum, maximum))

            elif command == "debug":
                common.log("Debug from cfg file: " + src)

            elif command == "divide":
                paramArr = params.split(",")
                a = paramArr[0].strip().strip("'").replace("%s", src)
                a = resolveVariable(a, item)
                b = paramArr[1].strip().strip("'").replace("%s", src)
                b = resolveVariable(b, item)

                if not a or not b:
                    continue

                a = int(a)
                b = int(b)
                try:
                    src = str(a / b)
                except:
                    pass

        return src
Example #43
0
 def update(self):
     
     def checkForUpdates():
         updates = {}          
         common.showNotification('SportsDevil', common.translate(30275))
         xbmcUtils.showBusyAnimation()
              
         catchersUpdates = self.syncManager.getUpdates(SyncSourceType.CATCHERS, common.Paths.catchersDir)
         if len(catchersUpdates) > 0:
             updates["Catchers"] = catchersUpdates    
         modulesUpdates = self.syncManager.getUpdates(SyncSourceType.MODULES, common.Paths.modulesDir)
         if len(modulesUpdates) > 0:
             updates["Modules"] = modulesUpdates
         
         xbmcUtils.hideBusyAnimation()
         return updates
     
     def doUpdates(typeName, updates):
         count = len(updates)
         
         head = "SportsDevil Updates - %s" % typeName
         
         msg = common.translate(30277)
         if count == 1:
             msg = common.translate(30276)
             
         question = ("%s %s: " % (count, msg)) + ', '.join(map(lambda u: u.split('/')[-1], updates.keys())) + '\n'
         question += common.translate(30278)
         
         updates = updates.values()
         
         countFailed = 0
 
         dlg = DialogQuestion()
         dlg.head = head
         if dlg.ask(question):
             dlg = DialogProgress()
             firstline = common.translate(30279)
             dlg.create(head, firstline, " ")
        
             for i in range(0, count):
                 update = updates[i]
                 percent = int((i+1.0)*100/count)
                 dlg.update(percent, firstline, update.name)
                 if not update.do():
                     countFailed += 1
             
             msg = " "
             if countFailed > 0:
                 msg = "%s %s" % (countFailed, common.translate(30280))
                 
             dlg.update(100, msg, " ")
             xbmc.sleep(500)
             dlg.close()
         
     allupdates = checkForUpdates()
     count = len(allupdates)
     if count == 0:
         common.showNotification('SportsDevil', common.translate(30273))
         return
     else:
         for key, value in allupdates.items():
             doUpdates(key, value)
Example #44
0
 def getNewTags(photoinfo):
     """ returns translated photo tags + original tags """
     photoTags = [t['raw'] for t in photoinfo['photo']['tags']['tag'] if t.get('raw')]
     return set(translate(tag, language)
                for tag in photoTags
                for language in SUPPORTED_LANGUAGES)
Example #45
0
    def __parseCommands(self, item, src, convCommands):
        common.log('_parseCommands called')
        # helping function
        def parseCommand(txt):
            command = {"command": txt, "params": ""}
            if txt.find("(") > -1:
                command["command"] = txt[0:txt.find("(")]
                command["params"] = txt[len(command["command"]) + 1:-1]
            return command
        
        for convCommand in convCommands:
            pComm = parseCommand(convCommand)
            command = pComm["command"]
            params = pComm["params"]

            if params.find('@REFERER@'):
                referer = item['referer']
                if not referer:
                    referer = ''
                params = params.replace('@REFERER@', referer)

            if command == 'convDate':
                src = cc.convDate(params, src)

            elif command == 'convTimestamp':
                src = cc.convTimestamp(params, src)

            elif command == 'select':
                src = cc.select(params, src)
                if not src:
                    continue

            elif command == 'unicode_escape':
                src = src.decode('unicode-escape')

            elif command == 'replaceFromDict':
                dictName = str(params.strip('\''))
                path = os.path.join(common.Paths.dictsDir, dictName + '.txt')
                if not (os.path.exists(path)):
                    common.log('Dictionary file not found: ' + path)
                    continue
                src = cc.replaceFromDict(path, src)

            elif command == 'time':
                src = time.time()

            elif command == 'timediff':
                src = dt.timediff(src,params.strip('\''))

            elif command == 'offset':
                src = cc.offset(params, src)

            elif command == 'getSource':
                src = cc.getSource(params, src)

            elif command == 'quote':
                try:
                    src = urllib.quote(params.strip("'").replace('%s', src),'')
                except:
                    print (">>>>>>>>>>>>>",src)
                    cleanParams = params.strip("'")
                    cleanParams = cleanParams.replace("%s",src)
                    src = urllib.quote(cleanParams.encode('utf-8'),'')

            elif command == 'unquote':
                src = urllib.unquote(params.strip("'").replace('%s', src))

            elif command == 'parseText':
                src = cc.parseText(item, params, src)

            elif command == 'getInfo':
                src = cc.getInfo(item, params, src)
            
            elif command == 'getXML':
                src = cc.getInfo(item, params, src, xml=True)
                
            elif command == 'getMobile':
                src = cc.getInfo(item, params, src, mobile=True)

            elif command == 'decodeBase64':
                src = cc.decodeBase64(src)

            elif command == 'decodeRawUnicode':
                src = cc.decodeRawUnicode(src)
                
            elif command == 'resolve':
                src = cc.resolve(src)
            
            elif command == 'decodeXppod':
                src = cc.decodeXppod(src)
            
            elif command == 'decodeXppodHLS':
                src = cc.decodeXppod_hls(src)

            elif command == 'replace':
                src = cc.replace(params, src)

            elif command == 'replaceRegex':
                src = cc.replaceRegex(params, src)

            elif command == 'ifEmpty':
                src = cc.ifEmpty(item, params, src)

            elif command == 'isEqual':
                src = cc.isEqual(item, params, src)

            elif command == 'ifFileExists':
                src = cc.ifFileExists(item, params, src)

            elif command == 'ifExists':
                src = cc.ifExists(item, params, src)

            elif command == 'encryptJimey':
                src = crypt.encryptJimey(params.strip("'").replace('%s', src))

            elif command == 'gAesDec':
                src = crypt.gAesDec(src,item.infos[params])
            
            elif command == 'aesDec':
                src = crypt.aesDec(src,item.infos[params])
                
            elif command == 'getCookies':
                src = cc.getCookies(params, src)

            elif command == 'destreamer':
                src = crypt.destreamer(params.strip("'").replace('%s', src))

            elif command == 'unixTimestamp':
                src = dt.getUnixTimestamp()
                
            elif command == 'rowbalance':
                src = rb.get()

            elif command == 'urlMerge':
                src = cc.urlMerge(params, src)

            elif command == 'translate':
                try:
                    src = common.translate(int(src))
                except:
                    pass

            elif command == 'camelcase':
                src = string.capwords(string.capwords(src, '-'))
                
            elif command == 'lowercase':
                src = string.lower(src)
                
            elif command == 'reverse':
                src = src[::-1]
                
            elif command == 'demystify':
                print 'demystify'
                src = crypt.doDemystify(src)
                print 'after demystify',src

            elif command == 'random':
                paramArr = params.split(',')
                minimum = int(paramArr[0])
                maximum = int(paramArr[1])
                src = str(random.randrange(minimum,maximum))

            elif command == 'debug':
                common.log('Debug from cfg file: ' + src)
                
            elif command == 'divide':
                paramArr = params.split(',')
                a = paramArr[0].strip().strip("'").replace('%s', src)
                a = resolveVariable(a, item)
                b = paramArr[1].strip().strip("'").replace('%s', src)
                b = resolveVariable(b, item)
                
                if not a or not b:
                    continue
                
                a = int(a)
                b = int(b)
                try:
                    src = str(a/b)
                except:
                    pass
                
        return src
Example #46
0
    def __parseCfg(self, cfgFile, data, lItem):
        tmpList = CList()

        data = data.replace('\r\n', '\n').split('\n')

        items = []
        tmp = None
        hasOwnCfg = False
        
        for m in data:
            if m and m[0] != '#':
                index = m.find('=')
                if index != -1:
                    key = lower(m[:index]).strip()
                    value = m[index+1:]

                    index = value.find('|')
                    if value[:index] == 'sports.devil.locale':
                        value = common.translate(int(value[index+1:]))
                    elif value[:index] == 'sports.devil.image':
                        value = os.path.join(common.Paths.imgDir, value[index+1:])

                    if key == 'start':
                        tmpList.start = value
                    elif key == 'section':
                        tmpList.section = value
                    elif key == 'sort':
                        tmpList.sort = value
                    elif key == 'skill':
                        tmpList.skill = value
                    elif key == 'catcher':
                        tmpList.catcher = value

                    elif key == 'item_infos':
                        rule_tmp = CRuleItem()
                        hasOwnCfg = False
                        rule_tmp.infos = value
                    elif key == 'item_order':
                        rule_tmp.order = value
                    elif key == 'item_skill':
                        rule_tmp.skill = value
                    elif key == 'item_curr':
                        rule_tmp.curr = value
                    elif key == 'item_precheck':
                        rule_tmp.precheck = value

                    elif key.startswith('item_info'):
                        tmpkey = key[len('item_info'):]
                        if tmpkey == '_name':
                            info_tmp = CItemInfo()
                            info_tmp.name = value
                            if value == 'cfg':
                                hasOwnCfg = True
                        elif tmpkey == '_from':
                            info_tmp.src = value
                        elif tmpkey == '':
                            info_tmp.rule = value
                        elif tmpkey == '_default':
                            info_tmp.default = value
                        elif tmpkey == '_convert':
                            info_tmp.convert.append(value)
                        elif tmpkey == '_build':
                            info_tmp.build = value
                            rule_tmp.info_list.append(info_tmp)

                    elif key == 'item_url_build':
                        rule_tmp.url_build = value
                        
                        if tmpList.catcher != '':
                            
                            refInf = CItemInfo()
                            refInf.name = 'referer'
                            refInf.build = value
                            
                            rule_tmp.info_list.append(refInf)
                            
                            if not hasOwnCfg:
                                refInf = CItemInfo()
                                refInf.name = 'catcher'
                                refInf.build = tmpList.catcher
                                
                                rule_tmp.info_list.append(refInf)
    
                        tmpList.rules.append(rule_tmp)


                    # static menu items (without regex)
                    elif key == 'title':
                        tmp = CListItem()
                        tmp['title'] = value
                        if tmpList.skill.find('videoTitle') > -1:
                            tmp['videoTitle'] = value 
                    elif key == 'url':
                        tmp['url'] = value
                        if lItem:
                            tmp.merge(lItem)
                            
                        if tmpList.catcher != '':
                            tmp['referer'] = value
                            if not hasOwnCfg:
                                tmp['catcher'] = tmpList.catcher
                            
                        tmp['definedIn'] = cfgFile
                        items.append(tmp)
                        tmp = None
                    elif tmp != None:
                        if key == 'cfg':
                            hasOwnCfg = True
                        tmp[key] = value


        tmpList.items = items
        tmpList.cfg = cfgFile
        return tmpList
Example #47
0
    def __parseCommands(self, item, src, convCommands):
        common.log('_parseCommands called')
        # helping function
        def parseCommand(txt):
            command = {"command": txt, "params": ""}
            if txt.find("(") > -1:
                command["command"] = txt[0:txt.find("(")]
                command["params"] = txt[len(command["command"]) + 1:-1]
            return command
        
        for convCommand in convCommands:
            pComm = parseCommand(convCommand)
            command = pComm["command"]
            params = pComm["params"]

            if params.find('@REFERER@'):
                referer = item['referer']
                if not referer:
                    referer = ''
                params = params.replace('@REFERER@', referer)

            if command == 'convDate':
                src = cc.convDate(params, src)

            elif command == 'convTimestamp':
                src = cc.convTimestamp(params, src)
                
            elif command == 'convDateUtil':
                src = cc.convDateUtil(params, src)

            elif command == 'select':
                src = cc.select(params, src)
                if not src:
                    continue

            elif command == 'unicode_escape':
                src = src.decode('unicode-escape')

            elif command == 'replaceFromDict':
                dictName = str(params.strip('\''))
                path = os.path.join(common.Paths.dictsDir, dictName + '.txt')
                if not (os.path.exists(path)):
                    common.log('Dictionary file not found: ' + path)
                    continue
                src = cc.replaceFromDict(path, src)

            elif command == 'time':
                src = time.time()

            elif command == 'timediff':
                src = dt.timediff(src,params.strip('\''))

            elif command == 'offset':
                src = cc.offset(params, src)

            elif command == 'getSource':
                src = cc.getSource(params, src)

            elif command == 'quote':
                try:
                    src = urllib.quote(params.strip("'").replace('%s', src),'')
                except:
                    cleanParams = params.strip("'")
                    cleanParams = cleanParams.replace("%s",src)
                    src = urllib.quote(cleanParams.encode('utf-8'),'')

            elif command == 'unquote':
                src = urllib.unquote(params.strip("'").replace('%s', src))

            elif command == 'parseText':
                src = cc.parseText(item, params, src)

            elif command == 'getInfo':
                src = cc.getInfo(item, params, src)
            
            elif command == 'getXML':
                src = cc.getInfo(item, params, src, xml=True)
                
            elif command == 'getMobile':
                src = cc.getInfo(item, params, src, mobile=True)

            elif command == 'decodeBase64':
                src = cc.decodeBase64(src)
            
            elif command == 'encodeBase64':
                src = cc.encodeBase64(src)

            elif command == 'decodeRawUnicode':
                src = cc.decodeRawUnicode(src)
                
            elif command == 'resolve':
                src = cc.resolve(src)
            
            elif command == 'decodeXppod':
                src = cc.decodeXppod(src)
            
            elif command == 'decodeXppodHLS':
                if 'stkey' in item.infos:
                    src = src.replace(item.infos['stkey'],'')
                src = cc.decodeXppod_hls(src)
            
            elif command == 'decodeBCast':
                src = cc.bcast64(src)

            elif command == 'replace':
                src = cc.replace(params, src)

            elif command == 'replaceRegex':
                src = cc.replaceRegex(params, src)

            elif command == 'ifEmpty':
                src = cc.ifEmpty(item, params, src)

            elif command == 'isEqual':
                src = cc.isEqual(item, params, src)

            elif command == 'ifFileExists':
                src = cc.ifFileExists(item, params, src)

            elif command == 'ifExists':
                src = cc.ifExists(item, params, src)

            elif command == 'encryptJimey':
                src = crypt.encryptJimey(params.strip("'").replace('%s', src))

            elif command == 'gAesDec':
                src = crypt.gAesDec(src,item.infos[params])
                
            elif command == 'cjsAesDec':
                src = crypt.cjsAesDec(src,item.infos[params])
                
            elif command == 'm3u8AesDec':
                src = crypt.m3u8AesDec(src,item.infos[params])

            
            elif command == 'drenchDec':
                src = crypt.drenchDec(src,item.infos[params])
                
            elif command == 'onetv':
                src = crypt.onetv(src)
            
            elif command == 'getCookies':
                src = cc.getCookies(params, src)

            elif command == 'destreamer':
                src = crypt.destreamer(params.strip("'").replace('%s', src))

            elif command == 'unixTimestamp':
                src = dt.getUnixTimestamp()
                
            elif command == 'rowbalance':
                src = rb.get(src)

            elif command == 'simpleToken':
                src = cc.simpleToken(src)


			#elif command == 'wasteg':
            #    paramArr = params.split(',')
            #    ref = str(paramArr[1])
            #    src = getsaw.compose(ref, src)

            elif command == 'saurusDec':
                src = crypt.decryptSaurus(src)

            elif command == 'urlMerge':
                src = cc.urlMerge(params, src)

            elif command == 'translate':
                try:
                    src = common.translate(int(src))
                except:
                    pass

            elif command == 'camelcase':
                src = string.capwords(string.capwords(src, '-'))
                
            elif command == 'lowercase':
                src = string.lower(src)
                
            elif command == 'reverse':
                src = src[::-1]
                
            elif command == 'demystify':
                src = crypt.doDemystify(src)

            elif command == 'random':
                paramArr = params.split(',')
                minimum = int(paramArr[0])
                maximum = int(paramArr[1])
                src = str(random.randrange(minimum,maximum))

            elif command == 'debug':
                common.log('Debug from cfg file: ' + src)
                
            elif command == 'startLivestreamerProxy':
                libPath = os.path.join(common.Paths.rootDir, 'lib')
                serverPath = os.path.join(libPath, 'livestreamerXBMCLocalProxy.py')
                try:
                    import requests
                    requests.get('http://127.0.0.1:19000/version')
                    proxyIsRunning = True
                except:
                    proxyIsRunning = False
                if not proxyIsRunning:
                    xbmc.executebuiltin('RunScript(' + serverPath + ')')
                
            elif command == 'divide':
                paramArr = params.split(',')
                a = paramArr[0].strip().strip("'").replace('%s', src)
                a = resolveVariable(a, item)
                b = paramArr[1].strip().strip("'").replace('%s', src)
                b = resolveVariable(b, item)
                
                if not a or not b:
                    continue
                
                a = int(a)
                b = int(b)
                try:
                    src = str(a/b)
                except:
                    pass
                
        return src
Example #48
0
    def __parseCfg(self, cfgFile, data, lItem):
        tmpList = CList()

        data = data.replace("\r\n", "\n").split("\n")

        items = []
        tmp = None
        hasOwnCfg = False

        for m in data:
            if m and m[0] != "#":
                index = m.find("=")
                if index != -1:
                    key = lower(m[:index]).strip()
                    value = m[index + 1 :]

                    index = value.find("|")
                    if value[:index] == "sports.devil.locale":
                        value = common.translate(int(value[index + 1 :]))
                    elif value[:index] == "sports.devil.image":
                        value = os.path.join(common.Paths.imgDir, value[index + 1 :])

                    if key == "start":
                        tmpList.start = value
                    elif key == "section":
                        tmpList.section = value
                    elif key == "sort":
                        tmpList.sort = value
                    elif key == "skill":
                        tmpList.skill = value
                    elif key == "catcher":
                        tmpList.catcher = value

                    elif key == "item_infos":
                        rule_tmp = CRuleItem()
                        hasOwnCfg = False
                        rule_tmp.infos = value
                    elif key == "item_order":
                        rule_tmp.order = value
                    elif key == "item_skill":
                        rule_tmp.skill = value
                    elif key == "item_curr":
                        rule_tmp.curr = value
                    elif key == "item_precheck":
                        rule_tmp.precheck = value

                    elif key.startswith("item_info"):
                        tmpkey = key[len("item_info") :]
                        if tmpkey == "_name":
                            info_tmp = CItemInfo()
                            info_tmp.name = value
                            if value == "cfg":
                                hasOwnCfg = True
                        elif tmpkey == "_from":
                            info_tmp.src = value
                        elif tmpkey == "":
                            info_tmp.rule = value
                        elif tmpkey == "_default":
                            info_tmp.default = value
                        elif tmpkey == "_convert":
                            info_tmp.convert.append(value)
                        elif tmpkey == "_build":
                            info_tmp.build = value
                            rule_tmp.info_list.append(info_tmp)

                    elif key == "item_url_build":
                        rule_tmp.url_build = value

                        if tmpList.catcher != "":

                            refInf = CItemInfo()
                            refInf.name = "referer"
                            refInf.build = value

                            rule_tmp.info_list.append(refInf)

                            if not hasOwnCfg:
                                refInf = CItemInfo()
                                refInf.name = "catcher"
                                refInf.build = tmpList.catcher

                                rule_tmp.info_list.append(refInf)

                        tmpList.rules.append(rule_tmp)

                    # static menu items (without regex)
                    elif key == "title":
                        tmp = CListItem()
                        tmp["title"] = value
                        if tmpList.skill.find("videoTitle") > -1:
                            tmp["videoTitle"] = value
                    elif key == "url":
                        tmp["url"] = value
                        if lItem:
                            tmp.merge(lItem)

                        if tmpList.catcher != "":
                            tmp["referer"] = value
                            if not hasOwnCfg:
                                tmp["catcher"] = tmpList.catcher

                        tmp["definedIn"] = cfgFile
                        items.append(tmp)
                        tmp = None
                    elif tmp != None:
                        if key == "cfg":
                            hasOwnCfg = True
                        tmp[key] = value

        tmpList.items = items
        tmpList.cfg = cfgFile
        return tmpList
Example #49
0
 def video_report_hook(self, count, blocksize, totalsize):
     percent = int(float(count * blocksize * 100) / totalsize)
     self.pDialog.update(percent, common.translate(30050), common.translate(30051))
     if self.pDialog.iscanceled():
         raise KeyboardInterrupt
Example #50
0
    def __parseCommands(self, item, src, convCommands):
        #common.log('_parseCommands called')
        # helping function
        def parseCommand(txt):
            command = {"command": txt, "params": ""}
            if txt.find("(") > -1:
                command["command"] = txt[0:txt.find("(")]
                command["params"] = txt[len(command["command"]) + 1:-1]
            return command
        try:
            src = src.encode('utf-8')
        except:
            pass
        for convCommand in convCommands:
            pComm = parseCommand(convCommand)
            command = pComm["command"]
            params = pComm["params"]

            if params.find('@REFERER@'):
                referer = item['referer']
                if not referer:
                    referer = ''
                params = params.replace('@REFERER@', referer)

            if command == 'convDate':
                src = cc.convDate(params, src)

            elif command == 'convTimestamp':
                src = cc.convTimestamp(params, src)

            elif command == 'select':
                src = cc.select(params, src)
                if not src:
                    continue

            elif command == 'smart_unicode':
                src = enc.smart_unicode(params.strip("'").replace('%s', src))

            elif command == 'safeGerman':
                src = enc.safeGerman(src)

            elif command == 'safeRegex':
                src = enc.safeRegexEncoding(params.strip("'").replace('%s', enc.smart_unicode(src)))

            elif command == 'replaceFromDict':
                dictName = str(params.strip('\''))
                path = os.path.join(common.Paths.dictsDir, dictName + '.txt')
                if not (os.path.exists(path)):
                    common.log('Dictionary file not found: ' + path)
                    continue
                src = cc.replaceFromDict(path, src)

            elif command == 'time':
                src = time.time()

            elif command == 'timediff':
                src = dt.timediff(src,params.strip('\''))

            elif command == 'offset':
                src = cc.offset(params, src)

            elif command == 'getSource':
                src = cc.getSource(params, src)

            elif command == 'getRedirect':
                src = get_redirected_url(params.strip("'").replace('%s', src))

            elif command == 'quote':
                try:
                    src = urllib.quote(params.strip("'").replace('%s', urllib.quote(src)))
                except:
                    cleanParams = params.strip("'")
                    cleanParams = cleanParams.replace("%s",src.encode('utf-8'))
                    src = urllib.quote(cleanParams)

            elif command == 'unquote':
                src = urllib.unquote(params.strip("'").replace('%s', src))

            elif command == 'parseText':
                src = cc.parseText(item, params, src)

            elif command == 'getInfo':
                src = cc.getInfo(item, params, src)

            elif command == 'decodeBase64':
                src = cc.decodeBase64(src)

            elif command == 'decodeRawUnicode':
                src = cc.decodeRawUnicode(src)

            elif command == 'replace':
                src = cc.replace(params, src)

            elif command == 'replaceRegex':
                src = cc.replaceRegex(params, src)

            elif command == 'ifEmpty':
                src = cc.ifEmpty(item, params, src)

            elif command == 'isEqual':
                src = cc.isEqual(item, params, src)

            elif command == 'ifFileExists':
                src = cc.ifFileExists(item, params, src)

            elif command == 'ifExists':
                src = cc.ifExists(item, params, src)

            elif command == 'encryptJimey':
                src = crypt.encryptJimey(params.strip("'").replace('%s', src))

            elif command == 'destreamer':
                src = crypt.destreamer(params.strip("'").replace('%s', src))

            elif command == 'unixTimestamp':
                src = dt.getUnixTimestamp()

            elif command == 'urlMerge':
                src = cc.urlMerge(params, src)

            elif command == 'translate':
                try:
                    src = common.translate(int(src))
                except:
                    pass

            elif command == 'camelcase':
                src = enc.smart_unicode(src)
                src = string.capwords(string.capwords(src, '-'))

            elif command == 'random':
                paramArr = params.split(',')
                minimum = int(paramArr[0])
                maximum = int(paramArr[1])
                src = str(random.randrange(minimum,maximum))

            elif command == 'debug':
                common.log('Debug from cfg file: ' + src)
                
            elif command == 'divide':
                paramArr = params.split(',')
                a = paramArr[0].strip().strip("'").replace('%s', src)
                a = resolveVariable(a, item)
                b = paramArr[1].strip().strip("'").replace('%s', src)
                b = resolveVariable(b, item)
                
                if not a or not b:
                    continue
                
                a = int(a)
                b = int(b)
                try:
                    src = a/b
                except:
                    pass
                
        return src