Пример #1
0
  public void updateShare(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    try {
      request = wrapRequest(request);
      User user = securityService.getCurrentUser(request);
      int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

      Share share = shareService.getShareById(id);
      if (share == null) {
        error(request, response, ErrorCode.NOT_FOUND, "Shared media not found.");
        return;
      }
      if (!user.isAdminRole() && !share.getUsername().equals(user.getUsername())) {
        error(
            request, response, ErrorCode.NOT_AUTHORIZED, "Not authorized to modify shared media.");
        return;
      }

      share.setDescription(request.getParameter("description"));
      String expiresString = request.getParameter("expires");
      if (expiresString != null) {
        long expires = Long.parseLong(expiresString);
        share.setExpires(expires == 0L ? null : new Date(expires));
      }
      shareService.updateShare(share);
      XMLBuilder builder = createXMLBuilder(request, response, true).endAll();
      response.getWriter().print(builder);

    } catch (ServletRequestBindingException x) {
      error(request, response, ErrorCode.MISSING_PARAMETER, getErrorMessage(x));
    } catch (Exception x) {
      LOG.warn("Error in REST API.", x);
      error(request, response, ErrorCode.GENERIC, getErrorMessage(x));
    }
  }
Пример #2
0
  public void deleteShare(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    try {
      request = wrapRequest(request);
      User user = securityService.getCurrentUser(request);
      int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

      Share share = shareService.getShareById(id);
      if (share == null) {
        error(request, response, ErrorCode.NOT_FOUND, "Shared media not found.");
        return;
      }
      if (!user.isAdminRole() && !share.getUsername().equals(user.getUsername())) {
        error(
            request, response, ErrorCode.NOT_AUTHORIZED, "Not authorized to delete shared media.");
        return;
      }

      shareService.deleteShare(id);
      XMLBuilder builder = createXMLBuilder(request, response, true).endAll();
      response.getWriter().print(builder);

    } catch (ServletRequestBindingException x) {
      error(request, response, ErrorCode.MISSING_PARAMETER, getErrorMessage(x));
    } catch (Exception x) {
      LOG.warn("Error in REST API.", x);
      error(request, response, ErrorCode.GENERIC, getErrorMessage(x));
    }
  }
Пример #3
0
  public void createShare(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    request = wrapRequest(request);
    Player player = playerService.getPlayer(request, response);

    User user = securityService.getCurrentUser(request);
    if (!user.isShareRole()) {
      error(
          request,
          response,
          ErrorCode.NOT_AUTHORIZED,
          user.getUsername() + " is not authorized to share media.");
      return;
    }

    XMLBuilder builder = createXMLBuilder(request, response, true);

    try {

      List<MediaFile> files = new ArrayList<MediaFile>();
      for (String id : ServletRequestUtils.getRequiredStringParameters(request, "id")) {
        MediaFile file = mediaFileService.getMediaFile(NumberUtils.toInt(id));
        files.add(file);
      }

      // TODO: Update api.jsp

      Share share = shareService.createShare(request, files);
      share.setDescription(request.getParameter("description"));
      long expires = ServletRequestUtils.getLongParameter(request, "expires", 0L);
      if (expires != 0) {
        share.setExpires(new Date(expires));
      }
      shareService.updateShare(share);

      builder.add("shares", false);
      builder.add("share", createAttributesForShare(share), false);

      for (MediaFile mediaFile : shareService.getSharedFiles(share.getId())) {
        File coverArt = mediaFileService.getCoverArt(mediaFile);
        AttributeSet attributes =
            restBrowseController.createAttributesForMediaFile(player, coverArt, mediaFile);
        builder.add("entry", attributes, true);
      }

      builder.endAll();
      response.getWriter().print(builder);

    } catch (ServletRequestBindingException x) {
      error(request, response, ErrorCode.MISSING_PARAMETER, getErrorMessage(x));
    } catch (Exception x) {
      LOG.warn("Error in REST API.", x);
      error(request, response, ErrorCode.GENERIC, getErrorMessage(x));
    }
  }
Пример #4
0
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    User user = securityService.getCurrentUser(request);
    UserSettings userSettings = settingsService.getUserSettings(user.getUsername());
    Player player = playerService.getPlayer(request, response);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("user", user);
    map.put("player", player);
    map.put("players", playerService.getPlayersForUserAndClientId(user.getUsername(), null));
    map.put("visibility", userSettings.getPlaylistVisibility());
    map.put("partyMode", userSettings.isPartyModeEnabled());
    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
  }
Пример #5
0
  public ModelAndView settings(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String playerId = (String) request.getSession().getAttribute("player");

    List<Player> allPlayers = playerService.getAllPlayers();
    User user = securityService.getCurrentUser(request);
    List<Player> players = new ArrayList<Player>();
    Map<String, Object> map = new HashMap<String, Object>();

    for (Player player : allPlayers) {
      // Only display authorized players.
      if (user.isAdminRole() || user.getUsername().equals(player.getUsername())) {
        players.add(player);
      }
    }
    map.put("playerId", playerId);
    map.put("players", players);
    return new ModelAndView("wap/settings", "model", map);
  }
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();

    //	String id = request.getParameter("id");
    //  MediaFile mediaFile = mediaFileService.getMediaFile(path);

    int listOffset = DEFAULT_LIST_OFFSET;
    int listSize = DEFAULT_LIST_SIZE;
    String listType = DEFAULT_LIST_TYPE;

    User user = securityService.getCurrentUser(request);
    String username = user.getUsername();
    UserSettings userSettings = settingsService.getUserSettings(username);
    int userGroupId = securityService.getCurrentUserGroupId(request);

    if (request.getParameter("listOffset") != null) {
      listOffset =
          Math.max(
              0, Math.min(Integer.parseInt(request.getParameter("listOffset")), MAX_LIST_OFFSET));
    }

    if (request.getParameter("listSize") != null) {
      listSize =
          Math.max(0, Math.min(Integer.parseInt(request.getParameter("listSize")), MAX_LIST_SIZE));
    }

    if (request.getParameter("listType") != null) {
      listType = String.valueOf(request.getParameter("listType"));
    }
    List<MediaFile> songs;
    if ("topplayed".equals(listType)) {
      songs = mediaFileDao.getTopPlayedCountForUser(listOffset, listSize, username);
    } else if ("otheruser".equals(listType)) {
      songs = mediaFileDao.getLastPlayedCountForAllUser(listOffset, listSize, userGroupId);
    } else if ("overall".equals(listType)) {
      songs = mediaFileDao.getTopPlayedCountForAllUser(listOffset, listSize, userGroupId);
    } else if ("lastplayed".equals(listType)) {
      songs = mediaFileDao.getLastPlayedCountForUser(listOffset, listSize, username);
    } else {
      songs = mediaFileDao.getLastPlayedCountForAllUser(0, 1, userGroupId);
    }

    mediaFileService.populateStarredDate(songs, username);
    map.put("user", user);
    map.put("songs", songs);

    map.put("partyModeEnabled", userSettings.isPartyModeEnabled());
    map.put("player", playerService.getPlayer(request, response));

    map.put("listOffset", listOffset);
    map.put("listSize", listSize);
    map.put("listType", listType);

    //  map.put("starred", mediaFileService.getMediaFileStarredDate(dir.getId(), username) != null);

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
  }
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    TransferStatus status = null;
    PlayQueueInputStream in = null;
    Player player = playerService.getPlayer(request, response, false, true);
    User user = securityService.getUserByName(player.getUsername());

    try {

      if (!user.isStreamRole()) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "Streaming is forbidden for user " + user.getUsername());
        return null;
      }

      // If "playlist" request parameter is set, this is a Podcast request. In that case, create a
      // separate
      // play queue (in order to support multiple parallel Podcast streams).
      Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist");
      boolean isPodcast = playlistId != null;
      if (isPodcast) {
        PlayQueue playQueue = new PlayQueue();
        playQueue.addFiles(false, playlistService.getFilesInPlaylist(playlistId));
        player.setPlayQueue(playQueue);
        Util.setContentLength(response, playQueue.length());
        LOG.info("Incoming Podcast request for playlist " + playlistId);
      }

      String contentType = StringUtil.getMimeType(request.getParameter("suffix"));
      response.setContentType(contentType);

      String preferredTargetFormat = request.getParameter("format");
      Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate");
      if (Integer.valueOf(0).equals(maxBitRate)) {
        maxBitRate = null;
      }

      VideoTranscodingSettings videoTranscodingSettings = null;

      // Is this a request for a single file (typically from the embedded Flash player)?
      // In that case, create a separate playlist (in order to support multiple parallel streams).
      // Also, enable partial download (HTTP byte range).
      MediaFile file = getSingleFile(request);
      boolean isSingleFile = file != null;
      LongRange range = null;

      if (isSingleFile) {
        PlayQueue playQueue = new PlayQueue();
        playQueue.addFiles(true, file);
        player.setPlayQueue(playQueue);

        if (!file.isVideo()) {
          response.setIntHeader("ETag", file.getId());
          //          response.setHeader("Accept-Ranges", "bytes");
        }

        TranscodingService.Parameters parameters =
            transcodingService.getParameters(
                file, player, maxBitRate, preferredTargetFormat, null, false);
        long fileLength = getFileLength(parameters);
        boolean isConversion = parameters.isDownsample() || parameters.isTranscode();
        boolean estimateContentLength =
            ServletRequestUtils.getBooleanParameter(request, "estimateContentLength", false);
        boolean isHls = ServletRequestUtils.getBooleanParameter(request, "hls", false);

        range = getRange(request, file);
        if (range != null) {
          LOG.info("Got range: " + range);

          //                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
          //                    Util.setContentLength(response, fileLength -
          // range.getMinimumLong());
          //                    long firstBytePos = range.getMinimumLong();
          //                    long lastBytePos = fileLength - 1;
          //                    response.setHeader("Content-Range", "bytes " + firstBytePos + "-" +
          // lastBytePos + "/" + fileLength);

          ///
          if (isConversion) {
            response.setHeader("Accept-Ranges", "none");
          } else {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            long maxLength = fileLength;
            if (maxLength > range.getMaximumLong()) maxLength = range.getMaximumLong() + 1;
            Util.setContentLength(response, Math.max(maxLength - range.getMinimumLong(), 0));
            long firstBytePos = range.getMinimumLong();
            long lastBytePos = maxLength - 1;
            response.setHeader(
                "Content-Range", "bytes " + firstBytePos + "-" + lastBytePos + "/" + fileLength);
          }
          ///
        } else if (!isHls && (!isConversion || estimateContentLength)) {
          Util.setContentLength(response, fileLength);
        }

        if (isHls) {
          response.setContentType(StringUtil.getMimeType("ts")); // HLS is always MPEG TS.
        } else {
          String transcodedSuffix =
              transcodingService.getSuffix(player, file, preferredTargetFormat);
          response.setContentType(StringUtil.getMimeType(transcodedSuffix));
        }

        if (file.isVideo() || isHls) {
          videoTranscodingSettings = createVideoTranscodingSettings(file, request);
        }
      }

      if (request.getMethod().equals("HEAD")) {
        return null;
      }

      // Terminate any other streams to this player.
      if (!isPodcast && !isSingleFile) {
        for (TransferStatus streamStatus : statusService.getStreamStatusesForPlayer(player)) {
          if (streamStatus.isActive()) {
            streamStatus.terminate();
          }
        }
      }

      status = statusService.createStreamStatus(player);

      in =
          new PlayQueueInputStream(
              player,
              status,
              maxBitRate,
              preferredTargetFormat,
              videoTranscodingSettings,
              transcodingService,
              audioScrobblerService,
              mediaFileService,
              searchService);
      OutputStream out = RangeOutputStream.wrap(response.getOutputStream(), range);

      // Enabled SHOUTcast, if requested.
      boolean isShoutCastRequested = "1".equals(request.getHeader("icy-metadata"));
      if (isShoutCastRequested && !isSingleFile) {
        response.setHeader("icy-metaint", "" + ShoutCastOutputStream.META_DATA_INTERVAL);
        response.setHeader("icy-notice1", "This stream is served using FutureSonic");
        response.setHeader("icy-notice2", "FutureSonic - Free media streamer - sonic.lt");
        response.setHeader("icy-name", "FutureSonic");
        response.setHeader("icy-genre", "Mixed");
        response.setHeader("icy-url", "http://sonic.lt/");
        out = new ShoutCastOutputStream(out, player.getPlayQueue(), settingsService);
      }

      final int BUFFER_SIZE = 2048;
      byte[] buf = new byte[BUFFER_SIZE];

      while (true) {

        // Check if stream has been terminated.
        if (status.terminated()) {
          return null;
        }

        if (player.getPlayQueue().getStatus() == PlayQueue.Status.STOPPED) {
          if (isPodcast || isSingleFile) {
            break;
          } else {
            sendDummy(buf, out);
          }
        } else {

          int n = in.read(buf);
          if (n == -1) {
            if (isPodcast || isSingleFile) {
              break;
            } else {
              sendDummy(buf, out);
            }
          } else {
            out.write(buf, 0, n);
          }
        }
      }

    } finally {
      if (status != null) {
        securityService.updateUserByteCounts(user, status.getBytesTransfered(), 0L, 0L);
        statusService.removeStreamStatus(status);
      }
      IOUtils.closeQuietly(in);
    }
    return null;
  }