Search in sources :

Example 91 with OLATResource

use of org.olat.resource.OLATResource in project OpenOLAT by OpenOLAT.

the class CourseResourceFolderWebService method getFiles.

public Response getFiles(Long courseId, List<PathSegment> path, FolderType type, UriInfo uriInfo, HttpServletRequest httpRequest, Request request) {
    if (!isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    ICourse course = CoursesWebService.loadCourse(courseId);
    if (course == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    VFSContainer container = null;
    RepositoryEntry re = null;
    switch(type) {
        case COURSE_FOLDER:
            container = course.getCourseFolderContainer();
            break;
        case SHARED_FOLDER:
            {
                container = null;
                String sfSoftkey = course.getCourseConfig().getSharedFolderSoftkey();
                OLATResource sharedResource = CoreSpringFactory.getImpl(RepositoryService.class).loadRepositoryEntryResourceBySoftKey(sfSoftkey);
                if (sharedResource != null) {
                    re = CoreSpringFactory.getImpl(RepositoryService.class).loadByResourceKey(sharedResource.getKey());
                    container = SharedFolderManager.getInstance().getNamedSharedFolder(re, true);
                    CourseConfig courseConfig = course.getCourseConfig();
                    if (courseConfig.isSharedFolderReadOnlyMount()) {
                        container.setLocalSecurityCallback(new ReadOnlyCallback());
                    }
                }
                break;
            }
    }
    if (container == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    VFSLeaf leaf = null;
    for (PathSegment seg : path) {
        VFSItem item = container.resolve(seg.getPath());
        if (item instanceof VFSLeaf) {
            leaf = (VFSLeaf) item;
            break;
        } else if (item instanceof VFSContainer) {
            container = (VFSContainer) item;
        }
    }
    if (leaf != null) {
        Date lastModified = new Date(leaf.getLastModified());
        Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
        if (response == null) {
            String mimeType = WebappHelper.getMimeType(leaf.getName());
            if (mimeType == null)
                mimeType = MediaType.APPLICATION_OCTET_STREAM;
            response = Response.ok(leaf.getInputStream(), mimeType).lastModified(lastModified).cacheControl(cc);
        }
        return response.build();
    }
    List<VFSItem> items = container.getItems(new SystemItemFilter());
    int count = 0;
    LinkVO[] links = new LinkVO[items.size()];
    for (VFSItem item : items) {
        UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
        UriBuilder repoUri = baseUriBuilder.path(CourseResourceFolderWebService.class).path("files");
        if (type.equals(FolderType.SHARED_FOLDER) && re != null) {
            repoUri = baseUriBuilder.replacePath("restapi").path(SharedFolderWebService.class).path(re.getKey().toString()).path("files");
        }
        for (PathSegment pathSegment : path) {
            repoUri.path(pathSegment.getPath());
        }
        String uri = repoUri.path(item.getName()).build(courseId).toString();
        links[count++] = new LinkVO("self", uri, item.getName());
    }
    return Response.ok(links).build();
}
Also used : VFSLeaf(org.olat.core.util.vfs.VFSLeaf) ReadOnlyCallback(org.olat.core.util.vfs.callbacks.ReadOnlyCallback) SharedFolderWebService(org.olat.restapi.repository.SharedFolderWebService) VFSContainer(org.olat.core.util.vfs.VFSContainer) OLATResource(org.olat.resource.OLATResource) VFSItem(org.olat.core.util.vfs.VFSItem) ICourse(org.olat.course.ICourse) RepositoryEntry(org.olat.repository.RepositoryEntry) PathSegment(javax.ws.rs.core.PathSegment) SystemItemFilter(org.olat.core.util.vfs.filters.SystemItemFilter) Date(java.util.Date) CourseConfig(org.olat.course.config.CourseConfig) Response(javax.ws.rs.core.Response) LinkVO(org.olat.restapi.support.vo.LinkVO) UriBuilder(javax.ws.rs.core.UriBuilder) RepositoryService(org.olat.repository.RepositoryService)

Example 92 with OLATResource

use of org.olat.resource.OLATResource in project OpenOLAT by OpenOLAT.

the class ReferenceManager method getReferencesInfos.

public List<ReferenceInfos> getReferencesInfos(List<RepositoryEntry> res, Identity identity, Roles roles) {
    if (res == null || res.isEmpty())
        return Collections.emptyList();
    List<Long> sourceKeys = new ArrayList<>();
    for (RepositoryEntry re : res) {
        sourceKeys.add(re.getOlatResource().getKey());
    }
    StringBuilder sb = new StringBuilder();
    sb.append("select ref from references ref").append(" where ref.target.key in (select orig.target.key from references orig where orig.source.key in (:sourceKeys))");
    List<Reference> references = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), Reference.class).setParameter("sourceKeys", sourceKeys).getResultList();
    Set<Long> targetResourceKeys = new HashSet<>();
    Set<Long> notOrphansResourceKeys = new HashSet<>();
    for (Iterator<Reference> itRef = references.iterator(); itRef.hasNext(); ) {
        Reference reference = itRef.next();
        OLATResource source = reference.getSource();
        OLATResource target = reference.getTarget();
        targetResourceKeys.add(target.getKey());
        if (!sourceKeys.contains(source.getKey())) {
            notOrphansResourceKeys.add(target.getKey());
        }
    }
    boolean isOlatAdmin = roles.isOLATAdmin();
    List<RepositoryEntry> entries = repositoryEntryDAO.loadByResourceKeys(targetResourceKeys);
    List<ReferenceInfos> infos = new ArrayList<>(entries.size());
    for (RepositoryEntry entry : entries) {
        Long resourceKey = entry.getOlatResource().getKey();
        boolean notOrphan = notOrphansResourceKeys.contains(resourceKey);
        boolean deleteManaged = RepositoryEntryManagedFlag.isManaged(entry, RepositoryEntryManagedFlag.delete);
        boolean isInstitutionalResourceManager = !roles.isGuestOnly() && repositoryManager.isInstitutionalRessourceManagerFor(identity, roles, entry);
        boolean isOwner = isOlatAdmin || reToGroupDao.hasRole(identity, entry, GroupRoles.owner.name()) || isInstitutionalResourceManager;
        ReferenceInfos refInfos = new ReferenceInfos(entry, !notOrphan, isOwner, deleteManaged);
        infos.add(refInfos);
    }
    return infos;
}
Also used : ArrayList(java.util.ArrayList) OLATResource(org.olat.resource.OLATResource) RepositoryEntry(org.olat.repository.RepositoryEntry) HashSet(java.util.HashSet)

Example 93 with OLATResource

use of org.olat.resource.OLATResource in project OpenOLAT by OpenOLAT.

the class RepositoryEntryResource method getRepoFileById.

/**
 * Download the export zip file of a repository entry.
 * @response.representation.mediaType multipart/form-data
 * @response.representation.doc Download the resource file
 * @response.representation.200.mediaType application/zip
 * @response.representation.200.doc Download the repository entry as export zip file
 * @response.representation.200.example {@link org.olat.restapi.support.vo.Examples#SAMPLE_REPOENTRYVO}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The resource could not found
 * @response.representation.406.doc Download of this resource is not possible
 * @response.representation.409.doc The resource is locked
 * @param repoEntryKey
 * @param request The HTTP request
 * @return
 */
@GET
@Path("file")
@Produces({ "application/zip", MediaType.APPLICATION_OCTET_STREAM })
public Response getRepoFileById(@PathParam("repoEntryKey") String repoEntryKey, @Context HttpServletRequest request) {
    RepositoryEntry re = lookupRepositoryEntry(repoEntryKey);
    if (re == null)
        return Response.serverError().status(Status.NOT_FOUND).build();
    RepositoryHandler typeToDownload = RepositoryHandlerFactory.getInstance().getRepositoryHandler(re);
    if (typeToDownload == null)
        return Response.serverError().status(Status.NOT_FOUND).build();
    OLATResource ores = OLATResourceManager.getInstance().findResourceable(re.getOlatResource());
    if (ores == null)
        return Response.serverError().status(Status.NOT_FOUND).build();
    Identity identity = getIdentity(request);
    boolean isAuthor = RestSecurityHelper.isAuthor(request);
    boolean isOwner = repositoryManager.isOwnerOfRepositoryEntry(identity, re);
    if (!(isAuthor | isOwner))
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    boolean canDownload = re.getCanDownload() && typeToDownload.supportsDownload();
    if (!canDownload)
        return Response.serverError().status(Status.NOT_ACCEPTABLE).build();
    boolean isAlreadyLocked = typeToDownload.isLocked(ores);
    LockResult lockResult = null;
    try {
        lockResult = typeToDownload.acquireLock(ores, identity);
        if (lockResult == null || (lockResult != null && lockResult.isSuccess() && !isAlreadyLocked)) {
            MediaResource mr = typeToDownload.getAsMediaResource(ores, false);
            if (mr != null) {
                repositoryService.incrementDownloadCounter(re);
                // success
                return Response.ok(mr.getInputStream()).cacheControl(cc).build();
            } else
                return Response.serverError().status(Status.NO_CONTENT).build();
        } else
            return Response.serverError().status(Status.CONFLICT).build();
    } finally {
        if ((lockResult != null && lockResult.isSuccess() && !isAlreadyLocked))
            typeToDownload.releaseLock(lockResult);
    }
}
Also used : LockResult(org.olat.core.util.coordinate.LockResult) OLATResource(org.olat.resource.OLATResource) MediaResource(org.olat.core.gui.media.MediaResource) RepositoryEntry(org.olat.repository.RepositoryEntry) RepositoryHandler(org.olat.repository.handlers.RepositoryHandler) Identity(org.olat.core.id.Identity) RestSecurityHelper.getIdentity(org.olat.restapi.security.RestSecurityHelper.getIdentity) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 94 with OLATResource

use of org.olat.resource.OLATResource in project OpenOLAT by OpenOLAT.

the class AuthoringEntryDataSource method processViewModel.

private List<AuthoringEntryRow> processViewModel(List<RepositoryEntryAuthorView> repoEntries) {
    Set<String> newNames = new HashSet<>();
    List<OLATResource> resourcesWithAC = new ArrayList<>(repoEntries.size());
    for (RepositoryEntryAuthorView entry : repoEntries) {
        if (entry.isOfferAvailable()) {
            resourcesWithAC.add(entry.getOlatResource());
        }
        final String author = entry.getAuthor();
        if (StringHelper.containsNonWhitespace(author)) {
            newNames.add(author);
        }
    }
    Map<String, String> fullNames = userManager.getUserDisplayNamesByUserName(newNames);
    List<OLATResourceAccess> resourcesWithOffer = acService.filterResourceWithAC(resourcesWithAC);
    Collection<OLATResourceable> resources = repoEntries.stream().map(RepositoryEntryAuthorView::getOlatResource).collect(Collectors.toList());
    List<ResourceLicense> licenses = licenseService.loadLicenses(resources);
    List<AuthoringEntryRow> items = new ArrayList<>();
    for (RepositoryEntryAuthorView entry : repoEntries) {
        String fullname = fullNames.get(entry.getAuthor());
        if (fullname == null) {
            fullname = entry.getAuthor();
        }
        AuthoringEntryRow row = new AuthoringEntryRow(entry, fullname);
        // bookmark
        row.setMarked(entry.isMarked());
        // access control
        List<PriceMethod> types = new ArrayList<>();
        if (entry.isMembersOnly()) {
            // members only always show lock icon
            types.add(new PriceMethod("", "o_ac_membersonly_icon", uifactory.getTranslator().translate("cif.access.membersonly.short")));
        } else {
            // collect access control method icons
            OLATResource resource = entry.getOlatResource();
            for (OLATResourceAccess resourceAccess : resourcesWithOffer) {
                if (resource.getKey().equals(resourceAccess.getResource().getKey())) {
                    for (PriceMethodBundle bundle : resourceAccess.getMethods()) {
                        String type = (bundle.getMethod().getMethodCssClass() + "_icon").intern();
                        String price = bundle.getPrice() == null || bundle.getPrice().isEmpty() ? "" : PriceFormat.fullFormat(bundle.getPrice());
                        AccessMethodHandler amh = acModule.getAccessMethodHandler(bundle.getMethod().getType());
                        String displayName = amh.getMethodName(uifactory.getTranslator().getLocale());
                        types.add(new PriceMethod(price, type, displayName));
                    }
                }
            }
        }
        if (!types.isEmpty()) {
            row.setAccessTypes(types);
        }
        // license
        for (ResourceLicense license : licenses) {
            OLATResource resource = entry.getOlatResource();
            if (license.getResId().equals(resource.getResourceableId()) && license.getResName().equals(resource.getResourceableTypeName())) {
                row.setLicense(license);
            }
        }
        uifactory.forgeLinks(row);
        items.add(row);
    }
    return items;
}
Also used : OLATResourceable(org.olat.core.id.OLATResourceable) ArrayList(java.util.ArrayList) OLATResource(org.olat.resource.OLATResource) OLATResourceAccess(org.olat.resource.accesscontrol.model.OLATResourceAccess) ResourceLicense(org.olat.core.commons.services.license.ResourceLicense) PriceMethod(org.olat.repository.ui.PriceMethod) RepositoryEntryAuthorView(org.olat.repository.RepositoryEntryAuthorView) AccessMethodHandler(org.olat.resource.accesscontrol.method.AccessMethodHandler) PriceMethodBundle(org.olat.resource.accesscontrol.model.PriceMethodBundle) HashSet(java.util.HashSet)

Example 95 with OLATResource

use of org.olat.resource.OLATResource in project OpenOLAT by OpenOLAT.

the class RepositoryEntryRuntimeController method isAssessmentLock.

private final boolean isAssessmentLock(UserRequest ureq, RepositoryEntry entry, RepositoryEntrySecurity reSec) {
    OLATResource resource = entry.getOlatResource();
    OLATResourceable lock = ureq.getUserSession().getLockResource();
    return lock != null && !reSec.isOwner() && !ureq.getUserSession().getRoles().isOLATAdmin() && lock.getResourceableId().equals(resource.getResourceableId()) && lock.getResourceableTypeName().equals(resource.getResourceableTypeName());
}
Also used : OLATResourceable(org.olat.core.id.OLATResourceable) OLATResource(org.olat.resource.OLATResource)

Aggregations

OLATResource (org.olat.resource.OLATResource)706 Test (org.junit.Test)304 RepositoryEntry (org.olat.repository.RepositoryEntry)198 Identity (org.olat.core.id.Identity)170 File (java.io.File)80 Date (java.util.Date)72 Feed (org.olat.modules.webFeed.Feed)72 ArrayList (java.util.ArrayList)64 ICourse (org.olat.course.ICourse)64 RepositoryService (org.olat.repository.RepositoryService)62 OLATResourceable (org.olat.core.id.OLATResourceable)60 BusinessGroup (org.olat.group.BusinessGroup)58 Item (org.olat.modules.webFeed.Item)44 AccessMethod (org.olat.resource.accesscontrol.model.AccessMethod)38 OLATResourceManager (org.olat.resource.OLATResourceManager)34 TokenAccessMethod (org.olat.resource.accesscontrol.model.TokenAccessMethod)34 PortfolioStructure (org.olat.portfolio.model.structel.PortfolioStructure)30 PortfolioStructureMap (org.olat.portfolio.model.structel.PortfolioStructureMap)30 FreeAccessMethod (org.olat.resource.accesscontrol.model.FreeAccessMethod)28 Group (org.olat.basesecurity.Group)26