Exemplo n.º 1
0
Arquivo: api.py Projeto: amarh/openPLM
def get_all_docs(request):
    """
    Returns all  the types of :class:`.Document` managed by the server.

    :implements: :func:`http_api.docs`
    """
    return {"types" : sorted(models.get_all_documents().keys())}
Exemplo n.º 2
0
def ajax_creation_form(request):
    """
    Simple view which returns the html of a creation form with the data
    of :attr:`request.GET` as initial values.

    The request must contains a get parameter *type* with a valid type,
    otherwise, a :class:`.HttpResponseForbidden` is returned.
    """
    tf = forms.TypeForm(request.GET)
    if tf.is_valid():
        type_ = tf.cleaned_data["type"]
        request.session["type"] = type_
        request.session.save()
        cls = models.get_all_users_and_plmobjects()[type_]
        view = get_creation_view(cls)
        if view is not None:
            return {"reload" : True}
        initial = dict(request.GET.iteritems())
        if "pfiles" in request.GET:
            initial["pfiles"] = request.GET.getlist("pfiles")
        if "reference" in initial:
            # gets a new reference if the type switches from a part to a document
            # and vice versa, see ticket #99
            ref = initial["reference"]
            if (ref.startswith("DOC_") and type_ in models.get_all_parts()) or \
               (ref.startswith("PART_") and type_ in models.get_all_documents()):
                del initial["reference"]
        form = forms.get_creation_form(request.user, cls, initial=initial)
        return {"reload" : False, "form" : form.as_table(),
                "type" : type_, "form_media": form.media.render(), }
    else:
        return HttpResponseForbidden()
Exemplo n.º 3
0
def get_all_docs(request):
    """
    Returns all  the types of :class:`.Document` managed by the server.

    :implements: :func:`http_api.docs`
    """
    return {"types": sorted(models.get_all_documents().keys())}
Exemplo n.º 4
0
def can_link(current_type, suggested_type):
    """
    Used in Doc-Parts views.

    :param current_type: type of the current object (part or document)
    :param suggested_type: type of the object that may be attached to the current one

    :return: True if current_type is a type of object that can be attached to current_type object
    """
    doc_types = models.get_all_documents()
    part_types = models.get_all_parts()
    return ((current_type in doc_types and suggested_type in part_types) or
            (current_type in part_types and suggested_type in doc_types))
Exemplo n.º 5
0
def can_link(current_type, suggested_type):
    """
    Used in Doc-Parts views.

    :param current_type: type of the current object (part or document)
    :param suggested_type: type of the object that may be attached to the current one

    :return: True if current_type is a type of object that can be attached to current_type object
    """
    doc_types = models.get_all_documents()
    part_types = models.get_all_parts()
    return ((current_type in doc_types and suggested_type in part_types)
            or (current_type in part_types and suggested_type in doc_types))
Exemplo n.º 6
0
def main_type(obj):
    if isinstance(obj, (User, UserController)):
        return "user"
    if isinstance(obj, (models.Part, PartController)) or getattr(obj, "is_part", False):
        return "part"
    if (isinstance(obj, (models.Document, DocumentController)) or
        getattr(obj, "is_document", False)):
        return "document"
    if isinstance(obj, (Group, GroupController)):
        return "group"
    if hasattr(obj, "has_key") and "type" in obj:
        if obj["type"] in models.get_all_parts():
            return "part"
        if obj["type"] in models.get_all_documents():
            return "document"
        return obj["type"]
    return getattr(obj, "type", "").lower()
Exemplo n.º 7
0
def main_type(obj):
    if isinstance(obj, (User, UserController)):
        return "user"
    if isinstance(obj, (models.Part, PartController)) or getattr(
            obj, "is_part", False):
        return "part"
    if (isinstance(obj, (models.Document, DocumentController))
            or getattr(obj, "is_document", False)):
        return "document"
    if isinstance(obj, (Group, GroupController)):
        return "group"
    if hasattr(obj, "has_key") and "type" in obj:
        if obj["type"] in models.get_all_parts():
            return "part"
        if obj["type"] in models.get_all_documents():
            return "document"
        return obj["type"]
    return getattr(obj, "type", "").lower()
Exemplo n.º 8
0
    def dav_propfind(self, path, property_list, depth="1"):
        ret = []
        ctrl, p = self.get_doc(path)
        now = datetime.datetime.utcnow()
        self.now = now

        files = [{
            "size": 4096,
            "locked": False,
            "locker": None,
            "filename": "",
            "is_dir": True,
            "ctime": now,
            "mtime": now,
        }]
        if ctrl is None and depth != "0":
            if not p or not p[0]:
                filenames = sorted(get_all_documents().keys())
            elif len(p) == 1:
                if p[0] not in get_all_documents():
                    raise BackendResourceNotFoundException(path)
                qs = Document.objects.filter(type=p[0]).values_list(
                    "reference", flat=True)
                filenames = set(qs)
            elif len(p) == 2:
                t, ref = p
                qs = Document.objects.filter(
                    type=t, reference=ref).values_list("revision", flat=True)
                filenames = set(qs)
                if not filenames:
                    # in that case, it is not possible to have an empty folder
                    raise BackendResourceNotFoundException(path)
            for name in filenames:
                files.append({
                    "size": 4096,
                    "locked": False,
                    "locker": None,
                    "filename": name,
                    "is_dir": True,
                    "ctime": now,
                    "mtime": now,
                })
        elif ctrl is not None:
            ctrl.check_readable(raise_=True)
            if p:
                if len(p) != 1:
                    raise BackendResourceNotFoundException(path)
                try:
                    df = ctrl.files.get(filename=p[0])
                except DocumentFile.DoesNotExist:
                    raise BackendResourceNotFoundException(path)
                else:
                    files = [{
                        "size": df.size,
                        "locked": df.locked,
                        "locker": df.locker,
                        "filename": "",
                        "is_dir": False,
                        "ctime": now,
                        "mtime": now,
                    }]

            elif depth != "0":
                for f in ctrl.files.values():
                    f["is_dir"] = False
                    try:
                        st = os.stat(docfs.path(f["file"]))
                        f["ctime"] = datetime.datetime.fromtimestamp(
                            st.st_ctime)
                        f["mtime"] = datetime.datetime.fromtimestamp(
                            st.st_mtime)
                    except OSError:
                        f["ctime"] = f["mtime"] = now
                    files.append(f)

        for f in files:
            props_ok = {}
            props_not_found = {}
            for prop in property_list:
                if prop == "{DAV:}getcontentlength":
                    if not f["is_dir"]:
                        props_ok["{DAV:}getcontentlength"] = f["size"]
                elif prop == "{DAV:}getlastmodified":
                    props_ok["{DAV:}getlastmodified"] = format_http_datetime(
                        f["mtime"])
                elif prop == "{DAV:}creationdate":
                    props_ok["{DAV:}creationdate"] = rfc3339_date(f["ctime"])
                elif prop == "{DAV:}resourcetype":
                    if f["is_dir"]:
                        props_ok["{DAV:}resourcetype"] = Element(
                            "{DAV:}collection")
                    else:
                        props_ok["{DAV:}resourcetype"] = None
                elif prop == "{DAV:}checked-in":
                    pass
                elif prop == "{DAV:}checked-out":
                    pass
                elif prop == "{http://apache.org/dav/props/}executable":
                    props_ok[
                        "{http://apache.org/dav/props/}executable"] = False
                elif prop == "{DAV:}supportedlock":
                    lockentries = [
                        Element("{DAV:}lockentry"),
                        Element("{DAV:}lockentry")
                    ]
                    scope = Element("{DAV:}lockscope")
                    scope.append(Element("{DAV:}exclusive"))
                    lockentries[0].append(scope)
                    type_ = Element("{DAV:}locktype")
                    type_.append(Element("{DAV:}write"))
                    lockentries[0].append(type_)
                    scope = Element("{DAV:}lockscope")
                    scope.append(Element("{DAV:}shared"))
                    lockentries[1].append(scope)
                    type_ = Element("{DAV:}locktype")
                    type_.append(Element("{DAV:}write"))
                    lockentries[1].append(type_)
                    props_ok["{DAV:}supportedlock"] = lockentries
                elif prop == "{DAV:}displayname":
                    pass
                elif prop == "{DAV:}ishidden":
                    props_ok[prop] = False
                elif prop == "{DAV:}getcontenttype":
                    if f["is_dir"]:
                        props_ok[prop] = "httpd/unix-directory"
                else:
                    logger.debug("unsupported property '%s'" % prop)
                    props_not_found[prop] = None

            f = BackendItem(f["filename"], f["is_dir"], [
                PropertySet(props_ok),
                PropertySet(props_not_found, "404 Not Found")
            ])
            ret.append(f)
        logger.debug("returned contents of directory '%s'" % p)
        return ret
Exemplo n.º 9
0
 def get_attached_documents(self):
     types = models.get_all_documents().keys()
     return self.plmobject_group.exclude_cancelled().filter(type__in=types)
Exemplo n.º 10
0
    def dav_propfind(self, path, property_list, depth="1"):
        ret = []
        ctrl, p = self.get_doc(path)
        now = datetime.datetime.utcnow()
        self.now = now

        files = [ {"size": 4096, "locked" : False, "locker" : None,
                  "filename" : "", "is_dir" : True, "ctime" : now,  "mtime" : now,} ]
        if ctrl is None and depth != "0":
            if not p or not p[0]:
                filenames = sorted(get_all_documents().keys())
            elif len(p) == 1:
                if p[0] not in get_all_documents():
                    raise BackendResourceNotFoundException(path)
                qs = Document.objects.filter(type=p[0]).values_list("reference", flat=True)
                filenames = set(qs)
            elif len(p) == 2:
                t, ref = p
                qs = Document.objects.filter(type=t, reference=ref).values_list("revision", flat=True)
                filenames = set(qs)
                if not filenames:
                    # in that case, it is not possible to have an empty folder
                    raise BackendResourceNotFoundException(path)
            for name in filenames:
                files.append({"size": 4096, "locked" : False, "locker" : None,
                    "filename" : name, "is_dir" : True, "ctime" : now,  "mtime" : now,})
        elif ctrl is not None:
            ctrl.check_readable(raise_=True)
            if p:
                if len(p) != 1:
                    raise BackendResourceNotFoundException(path)
                try:
                    df = ctrl.files.get(filename=p[0])
                except DocumentFile.DoesNotExist:
                    raise BackendResourceNotFoundException(path)
                else:
                    files = [ {"size": df.size, "locked" : df.locked, "locker" : df.locker,
                    "filename" : "", "is_dir" : False, "ctime" : now,  "mtime" : now,}]

            elif depth != "0":
                for f in ctrl.files.values():
                    f["is_dir"] = False
                    try:
                        st = os.stat(docfs.path(f["file"]))
                        f["ctime"] = datetime.datetime.fromtimestamp(st.st_ctime)
                        f["mtime"] = datetime.datetime.fromtimestamp(st.st_mtime)
                    except OSError:
                        f["ctime"] = f["mtime"] = now
                    files.append(f)

        for f in files:
            props_ok = {}
            props_not_found = {}
            for prop in property_list:
                if prop == "{DAV:}getcontentlength":
                    if not f["is_dir"]:
                        props_ok["{DAV:}getcontentlength"] = f["size"]
                elif prop == "{DAV:}getlastmodified":
                    props_ok["{DAV:}getlastmodified"] = format_http_datetime(f["mtime"])
                elif prop == "{DAV:}creationdate":
                    props_ok["{DAV:}creationdate"] = rfc3339_date(f["ctime"])
                elif prop == "{DAV:}resourcetype":
                    if f["is_dir"]:
                        props_ok["{DAV:}resourcetype"] = Element("{DAV:}collection")
                    else:
                        props_ok["{DAV:}resourcetype"] = None
                elif prop == "{DAV:}checked-in":
                    pass
                elif prop == "{DAV:}checked-out":
                    pass
                elif prop == "{http://apache.org/dav/props/}executable":
                    props_ok["{http://apache.org/dav/props/}executable"] = False
                elif prop == "{DAV:}supportedlock":
                    lockentries = [Element("{DAV:}lockentry"),
                                   Element("{DAV:}lockentry")]
                    scope = Element("{DAV:}lockscope")
                    scope.append(Element("{DAV:}exclusive"))
                    lockentries[0].append(scope)
                    type_ = Element("{DAV:}locktype")
                    type_.append(Element("{DAV:}write"))
                    lockentries[0].append(type_)
                    scope = Element("{DAV:}lockscope")
                    scope.append(Element("{DAV:}shared"))
                    lockentries[1].append(scope)
                    type_ = Element("{DAV:}locktype")
                    type_.append(Element("{DAV:}write"))
                    lockentries[1].append(type_)
                    props_ok["{DAV:}supportedlock"] = lockentries
                elif prop == "{DAV:}displayname":
                    pass
                elif prop == "{DAV:}ishidden":
                    props_ok[prop] = False
                elif prop == "{DAV:}getcontenttype":
                    if f["is_dir"]:
                        props_ok[prop] = "httpd/unix-directory"
                else:
                    logger.debug("unsupported property '%s'"%prop)
                    props_not_found[prop] = None

            f = BackendItem(
                f["filename"],
                f["is_dir"],
                [PropertySet(props_ok),
                 PropertySet(props_not_found, "404 Not Found")]
                )
            ret.append(f)
        logger.debug("returned contents of directory '%s'"%p)
        return ret
Exemplo n.º 11
0
 def get_attached_documents(self, time=None):
     types = models.get_all_documents().keys()
     return self.plmobjects.filter(plmobject__type__in=types).at(time)