From 2f3bd5b3ced15dbc92dd5c42c2e6b718c1f0dbc6 Mon Sep 17 00:00:00 2001 From: jfederico <jesus@123it.ca> Date: Thu, 28 Jan 2016 13:58:05 -0500 Subject: [PATCH] Reformatted files with conflicts --- .gitignore | 2 + ....codehaus.groovy.eclipse.preferences.prefs | 4 - .../.settings/org.eclipse.jdt.core.prefs | 3 - .../web/controllers/ApiController.groovy | 4084 ++++++++--------- .../org/bigbluebutton/api/MeetingService.java | 1436 +++--- .../bigbluebutton/api/RecordingService.java | 620 +-- 6 files changed, 3095 insertions(+), 3054 deletions(-) delete mode 100644 bigbluebutton-web/.settings/org.codehaus.groovy.eclipse.preferences.prefs delete mode 100644 bigbluebutton-web/.settings/org.eclipse.jdt.core.prefs diff --git a/.gitignore b/.gitignore index 213b785ab8..9bd2528638 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,5 @@ bigbluebutton-web/.classpath bigbluebutton-web/.project akka-bbb-apps/akka-bbb-apps*.log bigbluebutton-html5/log/development.log +bigbluebutton-web/target-eclipse* +record-and-playback/.loadpath diff --git a/bigbluebutton-web/.settings/org.codehaus.groovy.eclipse.preferences.prefs b/bigbluebutton-web/.settings/org.codehaus.groovy.eclipse.preferences.prefs deleted file mode 100644 index 626ef8d25e..0000000000 --- a/bigbluebutton-web/.settings/org.codehaus.groovy.eclipse.preferences.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Thu Nov 12 15:28:10 EST 2009 -eclipse.preferences.version=1 -groovy.compiler.output.path=bin-groovy -support.groovy=true diff --git a/bigbluebutton-web/.settings/org.eclipse.jdt.core.prefs b/bigbluebutton-web/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 9e8e8d9aa7..0000000000 --- a/bigbluebutton-web/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Thu Sep 03 13:19:16 EDT 2009 -eclipse.preferences.version=1 -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch,*.groovy diff --git a/bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ApiController.groovy b/bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ApiController.groovy index 551349ef56..b5b9ae701c 100755 --- a/bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ApiController.groovy +++ b/bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ApiController.groovy @@ -1,21 +1,21 @@ /** -* BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ -* -* Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). -* -* This program is free software; you can redistribute it and/or modify it under the -* terms of the GNU Lesser General Public License as published by the Free Software -* Foundation; either version 3.0 of the License, or (at your option) any later -* version. -* -* BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY -* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. -* -* You should have received a copy of the GNU Lesser General Public License along -* with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. -* -*/ + * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ + * + * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). + * + * This program is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free Software + * Foundation; either version 3.0 of the License, or (at your option) any later + * version. + * + * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. + * + */ package org.bigbluebutton.web.controllers import javax.servlet.ServletRequest; @@ -51,2112 +51,2106 @@ import freemarker.template.Configuration; import freemarker.cache.WebappTemplateLoader; class ApiController { - private static final Integer SESSION_TIMEOUT = 14400 // 4 hours - private static final String CONTROLLER_NAME = 'ApiController' - private static final String RESP_CODE_SUCCESS = 'SUCCESS' - private static final String RESP_CODE_FAILED = 'FAILED' - private static final String ROLE_MODERATOR = "MODERATOR"; - private static final String ROLE_ATTENDEE = "VIEWER"; - private static final String SECURITY_SALT = '639259d4-9dd8-4b25-bf01-95f9567eaf4b' - private static final String API_VERSION = '0.81' - - MeetingService meetingService; - PresentationService presentationService - ParamsProcessorUtil paramsProcessorUtil - ClientConfigService configService - PresentationUrlDownloadService presDownloadService - StunTurnService stunTurnService - - /* general methods */ - def index = { - log.debug CONTROLLER_NAME + "#index" - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - version(paramsProcessorUtil.getApiVersion()) - } - } - } + private static final Integer SESSION_TIMEOUT = 14400 // 4 hours + private static final String CONTROLLER_NAME = 'ApiController' + private static final String RESP_CODE_SUCCESS = 'SUCCESS' + private static final String RESP_CODE_FAILED = 'FAILED' + private static final String ROLE_MODERATOR = "MODERATOR"; + private static final String ROLE_ATTENDEE = "VIEWER"; + private static final String SECURITY_SALT = '639259d4-9dd8-4b25-bf01-95f9567eaf4b' + private static final String API_VERSION = '0.81' + + MeetingService meetingService; + PresentationService presentationService + ParamsProcessorUtil paramsProcessorUtil + ClientConfigService configService + PresentationUrlDownloadService presDownloadService + StunTurnService stunTurnService + + /* general methods */ + def index = { + log.debug CONTROLLER_NAME + "#index" + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + version(paramsProcessorUtil.getApiVersion()) + } + } + } + } } - } - - - /*********************************** - * CREATE (API) - ***********************************/ - def create = { - String API_CALL = 'create' - log.debug CONTROLLER_NAME + "#${API_CALL}" - log.debug params - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return + + + /*********************************** + * CREATE (API) + ***********************************/ + def create = { + String API_CALL = 'create' + log.debug CONTROLLER_NAME + "#${API_CALL}" + log.debug params + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors(); + paramsProcessorUtil.processRequiredCreateParams(params, errors); + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree with the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + + // Translate the external meeting id into an internal meeting id. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); + Meeting existing = meetingService.getNotEndedMeetingWithId(internalMeetingId); + if (existing != null) { + log.debug "Existing conference found" + Map<String, Object> updateParams = paramsProcessorUtil.processUpdateCreateParams(params); + if (existing.getViewerPassword().equals(params.get("attendeePW")) && existing.getModeratorPassword().equals(params.get("moderatorPW"))) { + paramsProcessorUtil.updateMeeting(updateParams, existing); + // trying to create a conference a second time, return success, but give extra info + // Ignore pre-uploaded presentations. We only allow uploading of presentation once. + //uploadDocuments(existing); + respondWithConference(existing, "duplicateWarning", "This conference was already in existence and may currently be in progress."); + } else { + // BEGIN - backward compatibility + invalid("idNotUnique", "A meeting already exists with that meeting ID. Please use a different meeting ID."); + return; + // END - backward compatibility + + // enforce meetingID unique-ness + errors.nonUniqueMeetingIdError() + respondWithErrors(errors) + } + + return; + } + + Meeting newMeeting = paramsProcessorUtil.processCreateParams(params); + + if (! StringUtils.isEmpty(params.moderatorOnlyMessage)) { + newMeeting.setModeratorOnlyMessage(params.moderatorOnlyMessage); + } + + meetingService.createMeeting(newMeeting); + + // See if the request came with pre-uploading of presentation. + uploadDocuments(newMeeting); + respondWithConference(newMeeting, null, null) } - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors(); - paramsProcessorUtil.processRequiredCreateParams(params, errors); - - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree with the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - - // Translate the external meeting id into an internal meeting id. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); - Meeting existing = meetingService.getNotEndedMeetingWithId(internalMeetingId); - if (existing != null) { - log.debug "Existing conference found" - Map<String, Object> updateParams = paramsProcessorUtil.processUpdateCreateParams(params); - if (existing.getViewerPassword().equals(params.get("attendeePW")) && existing.getModeratorPassword().equals(params.get("moderatorPW"))) { - paramsProcessorUtil.updateMeeting(updateParams, existing); - // trying to create a conference a second time, return success, but give extra info - // Ignore pre-uploaded presentations. We only allow uploading of presentation once. - //uploadDocuments(existing); - respondWithConference(existing, "duplicateWarning", "This conference was already in existence and may currently be in progress."); - } else { - // BEGIN - backward compatibility - invalid("idNotUnique", "A meeting already exists with that meeting ID. Please use a different meeting ID."); - return; - // END - backward compatibility - - // enforce meetingID unique-ness - errors.nonUniqueMeetingIdError() - respondWithErrors(errors) - } - - return; - } - - Meeting newMeeting = paramsProcessorUtil.processCreateParams(params); - - if (! StringUtils.isEmpty(params.moderatorOnlyMessage)) { - newMeeting.setModeratorOnlyMessage(params.moderatorOnlyMessage); - } - - meetingService.createMeeting(newMeeting); - - // See if the request came with pre-uploading of presentation. - uploadDocuments(newMeeting); - respondWithConference(newMeeting, null, null) - } - - /********************************************** - * JOIN API - *********************************************/ - def join = { - String API_CALL = 'join' - log.debug CONTROLLER_NAME + "#${API_CALL}" - ApiErrors errors = new ApiErrors() - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - //checking for an empty username or for a username containing whitespaces only - if(!StringUtils.isEmpty(params.fullName)) { - params.fullName = StringUtils.strip(params.fullName); - if (StringUtils.isEmpty(params.fullName)) { - invalid("missingParamFullName", "You must specify a name for the attendee who will be joining the meeting."); - return - } - } else { - invalid("missingParamFullName", "You must specify a name for the attendee who will be joining the meeting."); - return - } - - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - - if (StringUtils.isEmpty(params.password)) { - invalid("invalidPassword","You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference."); - return - } - - if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return + /********************************************** + * JOIN API + *********************************************/ + def join = { + String API_CALL = 'join' + log.debug CONTROLLER_NAME + "#${API_CALL}" + ApiErrors errors = new ApiErrors() + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + //checking for an empty username or for a username containing whitespaces only + if(!StringUtils.isEmpty(params.fullName)) { + params.fullName = StringUtils.strip(params.fullName); + if (StringUtils.isEmpty(params.fullName)) { + invalid("missingParamFullName", "You must specify a name for the attendee who will be joining the meeting."); + return + } + } else { + invalid("missingParamFullName", "You must specify a name for the attendee who will be joining the meeting."); + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + if (StringUtils.isEmpty(params.password)) { + invalid("invalidPassword","You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference."); + return + } + + if (!paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + // END - backward compatibility + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + // Do we have a name for the user joining? If none, complain. + if(!StringUtils.isEmpty(params.fullName)) { + params.fullName = StringUtils.strip(params.fullName); + if (StringUtils.isEmpty(params.fullName)) { + errors.missingParamError("fullName"); + } + } else { + errors.missingParamError("fullName"); + } + String fullName = params.fullName + + // Do we have a meeting id? If none, complain. + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + errors.missingParamError("meetingID"); + } + } + else { + errors.missingParamError("meetingID"); + } + String externalMeetingId = params.meetingID + + // Do we have a password? If not, complain. + String attPW = params.password + if (StringUtils.isEmpty(attPW)) { + errors.missingParamError("password"); + } + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + // Everything is good so far. Translate the external meeting id to an internal meeting id. If + // we can't find the meeting, complain. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); + log.info("Retrieving meeting ${internalMeetingId}") + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + // the createTime mismatch with meeting's createTime, complain + // In the future, the createTime param will be required + if (params.createTime != null) { + long createTime = 0; + try{ + createTime=Long.parseLong(params.createTime); + } catch(Exception e){ + log.warn("could not parse createTime param"); + createTime = -1; + } + if(createTime != meeting.getCreateTime()) { + errors.mismatchCreateTimeParam(); + respondWithErrors(errors); + return; + } + } + + // Is this user joining a meeting that has been ended. If so, complain. + if (meeting.isForciblyEnded()) { + // BEGIN - backward compatibility + invalid("meetingForciblyEnded", "You can not re-join a meeting that has already been forcibly ended. However, once the meeting is removed from memory (according to the timeout configured on this server, you will be able to once again create a meeting with the same meeting ID"); + return; + // END - backward compatibility + + errors.meetingForciblyEndedError(); + respondWithErrors(errors) + return; + } + + // Now determine if this user is a moderator or a viewer. + String role = null; + if (meeting.getModeratorPassword().equals(attPW)) { + role = ROLE_MODERATOR; + } else if (meeting.getViewerPassword().equals(attPW)) { + role = ROLE_ATTENDEE; + } + + if (role == null) { + // BEGIN - backward compatibility + invalid("invalidPassword","You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference."); + return + // END - backward compatibility + + errors.invalidPasswordError() + respondWithErrors(errors) + return; + } + + String webVoice = StringUtils.isEmpty(params.webVoiceConf) ? meeting.getTelVoice() : params.webVoiceConf + + boolean redirectImm = parseBoolean(params.redirectImmediately) + + String internalUserID = RandomStringUtils.randomAlphanumeric(12).toLowerCase() + + String authToken = RandomStringUtils.randomAlphanumeric(12).toLowerCase() + + String externUserID = params.userID + if (StringUtils.isEmpty(externUserID)) { + externUserID = internalUserID + } + + //Return a Map with the user custom data + Map<String,String> userCustomData = paramsProcessorUtil.getUserCustomData(params); + + //Currently, it's associated with the externalUserID + if (userCustomData.size() > 0) + meetingService.addUserCustomData(meeting.getInternalId(), externUserID, userCustomData); + + String configxml = null; + + if (! StringUtils.isEmpty(params.configToken)) { + Config conf = meeting.getConfig(params.configToken); + if (conf == null) { + // Check if this config is one of our pre-built config + configxml = configService.getConfig(params.configToken) + if (configxml == null) { + // Default to the default config. + configxml = conf.config; + } + } else { + configxml = conf.config; + } + } else { + Config conf = meeting.getDefaultConfig(); + if (conf == null) { + errors.noConfigFound(); + respondWithErrors(errors); + } else { + configxml = conf.config; + } + } + + if (StringUtils.isEmpty(configxml)) { + errors.noConfigFound(); + respondWithErrors(errors); + } + UserSession us = new UserSession(); + us.authToken = authToken; + us.internalUserId = internalUserID + us.conferencename = meeting.getName() + us.meetingID = meeting.getInternalId() + us.externMeetingID = meeting.getExternalId() + us.externUserID = externUserID + us.fullname = fullName + us.role = role + us.conference = meeting.getInternalId() + us.room = meeting.getInternalId() + us.voicebridge = meeting.getTelVoice() + us.webvoiceconf = meeting.getWebVoice() + us.mode = "LIVE" + us.record = meeting.isRecord() + us.welcome = meeting.getWelcomeMessage() + us.logoutUrl = meeting.getLogoutUrl(); + us.configXML = configxml; + + if (! StringUtils.isEmpty(params.defaultLayout)) { + us.defaultLayout = params.defaultLayout; + } + + if (! StringUtils.isEmpty(params.avatarURL)) { + us.avatarURL = params.avatarURL; + } else { + us.avatarURL = meeting.defaultAvatarURL + } + + // Store the following into a session so we can handle + // logout, restarts properly. + session['meeting-id'] = us.meetingID + session['user-token'] = us.meetingID + "-" + us.authToken; + session['logout-url'] = us.logoutUrl + + meetingService.addUserSession(session['user-token'], us); + + // Register user into the meeting. + meetingService.registerUser(us.meetingID, us.internalUserId, us.fullname, us.role, us.externUserID, us.authToken) + + log.info("Session user token for " + us.fullname + " [" + session['user-token'] + "]") + session.setMaxInactiveInterval(SESSION_TIMEOUT); + + //check if exists the param redirect + boolean redirectClient = true; + String clientURL = paramsProcessorUtil.getDefaultClientUrl(); + + if(! StringUtils.isEmpty(params.redirect)) { + try{ + redirectClient = Boolean.parseBoolean(params.redirect); + }catch(Exception e){ + redirectClient = true; + } + } + + if(!StringUtils.isEmpty(params.clientURL)){ + clientURL = params.clientURL; + } + + if (redirectClient){ + log.info("Successfully joined. Redirecting to ${paramsProcessorUtil.getDefaultClientUrl()}"); + redirect(url: clientURL); + } + else{ + log.info("Successfully joined. Sending XML response."); + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + messageKey("successfullyJoined") + message("You have joined successfully.") + meeting_id() { mkp.yield(us.meetingID) } + user_id(us.internalUserId) + auth_token(us.authToken) + } + } + } + } + } + } + + /******************************************* + * IS_MEETING_RUNNING API + *******************************************/ + def isMeetingRunning = { + String API_CALL = 'isMeetingRunning' + log.debug CONTROLLER_NAME + "#${API_CALL}" + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + // Do we have a meeting id? If none, complain. + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + errors.missingParamError("meetingID"); + } + } else { + errors.missingParamError("meetingID"); + } + String externalMeetingId = params.meetingID + + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + // Everything is good so far. Translate the external meeting id to an internal meeting id. If + // we can't find the meeting, complain. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); + log.info("Retrieving meeting ${internalMeetingId}") + Meeting meeting = meetingService.getMeeting(internalMeetingId); + boolean isRunning = meeting != null && meeting.isRunning(); + + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + running(isRunning ? "true" : "false") + } + } + } + } + } + + /************************************ + * END API + ************************************/ + def end = { + String API_CALL = "end" + + log.debug CONTROLLER_NAME + "#${API_CALL}" + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + if (StringUtils.isEmpty(params.password)) { + invalid("invalidPassword","You must supply the moderator password for this call."); + return + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + // Do we have a meeting id? If none, complain. + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + errors.missingParamError("meetingID"); + } + } else { + errors.missingParamError("meetingID"); + } + String externalMeetingId = params.meetingID + + // Do we have a password? If not, complain. + String modPW = params.password + if (StringUtils.isEmpty(modPW)) { + errors.missingParamError("password"); + } + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + // Everything is good so far. Translate the external meeting id to an internal meeting id. If + // we can't find the meeting, complain. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); + log.info("Retrieving meeting ${internalMeetingId}") + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("notFound", "We could not find a meeting with that meeting ID - perhaps the meeting is not yet running?"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + if (meeting.getModeratorPassword().equals(modPW) == false) { + // BEGIN - backward compatibility + invalid("invalidPassword","You must supply the moderator password for this call."); + return; + // END - backward compatibility + + errors.invalidPasswordError(); + respondWithErrors(errors) + return; + } + + meetingService.endMeeting(meeting.getInternalId()); + + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + messageKey("sentEndMeetingRequest") + message("A request to end the meeting was sent. Please wait a few seconds, and then use the getMeetingInfo or isMeetingRunning API calls to verify that it was ended.") + } + } + } + } + } + + /***************************************** + * GETMEETINGINFO API + *****************************************/ + def getMeetingInfo = { + String API_CALL = "getMeetingInfo" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + // Do we have a meeting id? If none, complain. + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + errors.missingParamError("meetingID"); + } + } else { + errors.missingParamError("meetingID"); + } + String externalMeetingId = params.meetingID + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + // Everything is good so far. Translate the external meeting id to an internal meeting id. If + // we can't find the meeting, complain. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); + log.info("Retrieving meeting ${internalMeetingId}") + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("notFound", "We could not find a meeting with that meeting ID"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + respondWithConferenceDetails(meeting, null, null, null); + } + + /************************************ + * GETMEETINGS API + ************************************/ + def getMeetingsHandler = { + String API_CALL = "getMeetings" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + Collection<Meeting> mtgs = meetingService.getMeetings(); + + if (mtgs == null || mtgs.isEmpty()) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + meetings() + messageKey("noMeetings") + message("no meetings were found on this server") + } + } + } + } + } else { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + meetings { + for (m in mtgs) { + meeting { + meetingID() { mkp.yield(m.getExternalId()) } + meetingName() { mkp.yield(m.getName()) } + createTime(m.getCreateTime()) + createDate(formatPrettyDate(m.getCreateTime())) + voiceBridge() { mkp.yield(m.getTelVoice()) } + dialNumber() { mkp.yield(m.getDialNumber()) } + attendeePW() { mkp.yield(m.getViewerPassword()) } + moderatorPW() { mkp.yield(m.getModeratorPassword()) } + hasBeenForciblyEnded(m.isForciblyEnded() ? "true" : "false") + running(m.isRunning() ? "true" : "false") + participantCount(m.getNumUsers()) + listenerCount(m.getNumListenOnly()) + voiceParticipantCount(m.getNumVoiceJoined()) + videoCount(m.getNumVideos()) + duration(m.duration) + hasUserJoined(m.hasUserJoined()) + } + } + } + } + } + } + } + } + } + + /************************************ + * GETSESSIONS API + ************************************/ + def getSessionsHandler = { + String API_CALL = "getSessions" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + Collection<Meeting> sssns = meetingService.getSessions(); + + if (sssns == null || sssns.isEmpty()) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + sessions() + messageKey("noSessions") + message("no sessions were found on this server") + } + } + } + } + } else { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + sessions { + for (m in sssns) { + meeting { + meetingID() { mkp.yield(m.meetingID) } + meetingName() { mkp.yield(m.conferencename) } + userName() { mkp.yield(m.fullname) } + } + } + } + } + } + } + } + } + } + + + def getDefaultConfigXML = { + + String API_CALL = "getDefaultConfigXML" + ApiErrors errors = new ApiErrors(); + + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + String defConfigXML = paramsProcessorUtil.getDefaultConfigXML(); + + response.addHeader("Cache-Control", "no-cache") + render text: defConfigXML, contentType: 'text/xml' + + } + + private Map<String, String[]> getParameters(ServletRequest request) { + // Copy the parameters into our own Map as we can't pass the paramMap + // from the request as it's an unmodifiable map. + Map<String, String[]> reqParams = new HashMap<String, String[]>(); + Map<String, String[]> unModReqParams = request.getParameterMap(); + + SortedSet<String> keys = new TreeSet<String>(unModReqParams.keySet()); + + for (String key: keys) { + reqParams.put(key, unModReqParams.get(key)); + } + + return reqParams; + } + + /*********************************************** + * POLL API + ***********************************************/ + def setPollXML = { + String API_CALL = "setPollXML" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (StringUtils.isEmpty(params.pollXML)) { + invalid("configXMLError", "You did not pass a poll XML") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + // Translate the external meeting id into an internal meeting id. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + Map<String, String[]> reqParams = getParameters(request) + + String pollXML = params.pollXML + + String decodedPollXML; + + try { + decodedPollXML = URLDecoder.decode(pollXML, "UTF-8"); + } catch (UnsupportedEncodingException e) { + log.error("Couldn't decode poll XML."); + invalid("pollXMLError", "Cannot decode poll XML") + return; + } + + if (! paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("pollXMLChecksumError") + message("pollXMLChecksumError: request did not pass the checksum security check.") + } + } + } + } + } else { + + def pollxml = new XmlSlurper().parseText(decodedPollXML); + + pollxml.children().each { poll -> + String title = poll.title.text(); + String question = poll.question.text(); + String questionType = poll.questionType.text(); + + ArrayList<String> answers = new ArrayList<String>(); + poll.answers.children().each { answer -> + answers.add(answer.text()); + } + + //send poll to BigBlueButton Apps + meetingService.createdPolls(meeting.getInternalId(), title, question, questionType, answers); + } + + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { returncode("SUCCESS") } + } + } + } + } + } + + /*********************************************** + * CONFIG API + ***********************************************/ + def setConfigXML = { + String API_CALL = "setConfigXML" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (StringUtils.isEmpty(params.configXML)) { + invalid("configXMLError", "You did not pass a config XML") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + // Translate the external meeting id into an internal meeting id. + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + Map<String, String[]> reqParams = getParameters(request) + + String configXML = params.configXML + + String decodedConfigXML; + + try { + decodedConfigXML = URLDecoder.decode(configXML, "UTF-8"); + } catch (UnsupportedEncodingException e) { + log.error("Couldn't decode config XML."); + invalid("configXMLError", "Cannot decode config XML") + return; + } + + if (! paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("configXMLChecksumError") + message("configXMLChecksumError: request did not pass the checksum security check.") + } + } + } + } + } else { + boolean defaultConfig = false; + + if (! StringUtils.isEmpty(params.defaultConfig)) { + try { + defaultConfig = Boolean.parseBoolean(params.defaultConfig); + } catch(Exception e) { + defaultConfig = false; + } + } + + + String token = meeting.storeConfig(defaultConfig, decodedConfigXML); + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("SUCCESS") + configToken(token) + } + } + } + } + } + } + + /*********************************************** + * CALLBACK API + ***********************************************/ + def subscribeEvent = { + String API_CALL = "subscribeEvent" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (StringUtils.isEmpty(params.callbackURL)) { + invalid("missingParamCallbackURL", "You must specify a callbackURL for subscribing"); + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("subscribeEventChecksumError") + message("subscribeEventChecksumError: request did not pass the checksum security check.") + } + } + } + } + } else { + String sid = meetingService.addSubscription(meeting.getInternalId(), meeting.getExternalId(), params.callbackURL); + + if(sid.isEmpty()){ + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("subscribeEventError") + message("subscribeEventError: An error happen while storing your subscription. Check the logs.") + } + } + } + } + + }else{ + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("SUCCESS") + subscriptionID(sid) + } + } + } + } + } + } + } + + def unsubscribeEvent = { + String API_CALL = "unsubscribeEvent" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (StringUtils.isEmpty(params.subscriptionID)) { + invalid("missingParamSubscriptionID", "You must pass a subscriptionID for unsubscribing") + return + } + + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("unsubscribeEventChecksumError") + message("unsubscribeEventChecksumError: request did not pass the checksum security check.") + } + } + } + } + } else { + boolean status = meetingService.removeSubscription(meeting.getInternalId(), params.subscriptionID); + + if(!status){ + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("unsubscribeEventError") + message("unsubscribeEventError: An error happen while unsubscribing. Check the logs.") + } + } + } + } + + }else{ + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("SUCCESS") + unsubscribed(status) + } + } + } + } + } + } } - // END - backward compatibility - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - } + def listSubscriptions = { + String API_CALL = "listSubscriptions" + log.debug CONTROLLER_NAME + "#${API_CALL}" - // Do we have a name for the user joining? If none, complain. - if(!StringUtils.isEmpty(params.fullName)) { - params.fullName = StringUtils.strip(params.fullName); - if (StringUtils.isEmpty(params.fullName)) { - errors.missingParamError("fullName"); + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return } - } else { - errors.missingParamError("fullName"); - } - String fullName = params.fullName - - // Do we have a meeting id? If none, complain. - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - errors.missingParamError("meetingID"); - } - } - else { - errors.missingParamError("meetingID"); - } - String externalMeetingId = params.meetingID - // Do we have a password? If not, complain. - String attPW = params.password - if (StringUtils.isEmpty(attPW)) { - errors.missingParamError("password"); - } - - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } + if(!StringUtils.isEmpty(params.meetingID)) { + params.meetingID = StringUtils.strip(params.meetingID); + if (StringUtils.isEmpty(params.meetingID)) { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } + } else { + invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); + return + } - // Everything is good so far. Translate the external meeting id to an internal meeting id. If - // we can't find the meeting, complain. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); - log.info("Retrieving meeting ${internalMeetingId}") - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } + String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); + Meeting meeting = meetingService.getMeeting(internalMeetingId); + if (meeting == null) { + // BEGIN - backward compatibility + invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); + return; + // END - backward compatibility + + errors.invalidMeetingIdError(); + respondWithErrors(errors) + return; + } - // the createTime mismatch with meeting's createTime, complain - // In the future, the createTime param will be required - if (params.createTime != null) { - long createTime = 0; - try{ - createTime=Long.parseLong(params.createTime); - } catch(Exception e){ - log.warn("could not parse createTime param"); - createTime = -1; - } - if(createTime != meeting.getCreateTime()) { - errors.mismatchCreateTimeParam(); - respondWithErrors(errors); - return; - } - } - - // Is this user joining a meeting that has been ended. If so, complain. - if (meeting.isForciblyEnded()) { - // BEGIN - backward compatibility - invalid("meetingForciblyEnded", "You can not re-join a meeting that has already been forcibly ended. However, once the meeting is removed from memory (according to the timeout configured on this server, you will be able to once again create a meeting with the same meeting ID"); - return; - // END - backward compatibility - - errors.meetingForciblyEndedError(); - respondWithErrors(errors) - return; - } + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + messageKey("listSubscriptionsChecksumError") + message("listSubscriptionsChecksumError: request did not pass the checksum security check.") + } + } + } + } + } else { + List<Map<String,String>> list = meetingService.listSubscriptions(meeting.getInternalId()); + + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("SUCCESS") + subscriptions() { + list.each{ item -> + subscription(){ + subscriptionID() { mkp.yield(item.get("subscriptionID")) } + event() { mkp.yield(item.get("event")) } + callbackURL() { mkp.yield(item.get("callbackURL")) } + active() { mkp.yield(item.get("active")) } + } + } + } + } + } + } + } - // Now determine if this user is a moderator or a viewer. - String role = null; - if (meeting.getModeratorPassword().equals(attPW)) { - role = ROLE_MODERATOR; - } else if (meeting.getViewerPassword().equals(attPW)) { - role = ROLE_ATTENDEE; - } - - if (role == null) { - // BEGIN - backward compatibility - invalid("invalidPassword","You either did not supply a password or the password supplied is neither the attendee or moderator password for this conference."); - return - // END - backward compatibility - - errors.invalidPasswordError() - respondWithErrors(errors) - return; - } - - String webVoice = StringUtils.isEmpty(params.webVoiceConf) ? meeting.getTelVoice() : params.webVoiceConf - - boolean redirectImm = parseBoolean(params.redirectImmediately) - - String internalUserID = RandomStringUtils.randomAlphanumeric(12).toLowerCase() - - String authToken = RandomStringUtils.randomAlphanumeric(12).toLowerCase() - - String externUserID = params.userID - if (StringUtils.isEmpty(externUserID)) { - externUserID = internalUserID - } - - //Return a Map with the user custom data - Map<String,String> userCustomData = paramsProcessorUtil.getUserCustomData(params); - - //Currently, it's associated with the externalUserID - if (userCustomData.size() > 0) - meetingService.addUserCustomData(meeting.getInternalId(), externUserID, userCustomData); - - String configxml = null; - - if (! StringUtils.isEmpty(params.configToken)) { - Config conf = meeting.getConfig(params.configToken); - if (conf == null) { - // Check if this config is one of our pre-built config - configxml = configService.getConfig(params.configToken) - if (configxml == null) { - // Default to the default config. - configxml = conf.config; - } - } else { - configxml = conf.config; - } - } else { - Config conf = meeting.getDefaultConfig(); - if (conf == null) { - errors.noConfigFound(); - respondWithErrors(errors); - } else { - configxml = conf.config; - } - } - - if (StringUtils.isEmpty(configxml)) { - errors.noConfigFound(); - respondWithErrors(errors); - } - UserSession us = new UserSession(); - us.authToken = authToken; - us.internalUserId = internalUserID - us.conferencename = meeting.getName() - us.meetingID = meeting.getInternalId() - us.externMeetingID = meeting.getExternalId() - us.externUserID = externUserID - us.fullname = fullName - us.role = role - us.conference = meeting.getInternalId() - us.room = meeting.getInternalId() - us.voicebridge = meeting.getTelVoice() - us.webvoiceconf = meeting.getWebVoice() - us.mode = "LIVE" - us.record = meeting.isRecord() - us.welcome = meeting.getWelcomeMessage() - us.logoutUrl = meeting.getLogoutUrl(); - us.configXML = configxml; - - if (! StringUtils.isEmpty(params.defaultLayout)) { - us.defaultLayout = params.defaultLayout; - } - - if (! StringUtils.isEmpty(params.avatarURL)) { - us.avatarURL = params.avatarURL; - } else { - us.avatarURL = meeting.defaultAvatarURL - } - - // Store the following into a session so we can handle - // logout, restarts properly. - session['meeting-id'] = us.meetingID - session['user-token'] = us.meetingID + "-" + us.authToken; - session['logout-url'] = us.logoutUrl - - meetingService.addUserSession(session['user-token'], us); - - // Register user into the meeting. - meetingService.registerUser(us.meetingID, us.internalUserId, us.fullname, us.role, us.externUserID, us.authToken) - - log.info("Session user token for " + us.fullname + " [" + session['user-token'] + "]") - session.setMaxInactiveInterval(SESSION_TIMEOUT); - - //check if exists the param redirect - boolean redirectClient = true; - String clientURL = paramsProcessorUtil.getDefaultClientUrl(); - - if(! StringUtils.isEmpty(params.redirect)) { - try{ - redirectClient = Boolean.parseBoolean(params.redirect); - }catch(Exception e){ - redirectClient = true; - } - } - - if(!StringUtils.isEmpty(params.clientURL)){ - clientURL = params.clientURL; - } - - if (redirectClient){ - log.info("Successfully joined. Redirecting to ${paramsProcessorUtil.getDefaultClientUrl()}"); - redirect(url: clientURL); - } - else{ - log.info("Successfully joined. Sending XML response."); - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - messageKey("successfullyJoined") - message("You have joined successfully.") - meeting_id() { mkp.yield(us.meetingID) } - user_id(us.internalUserId) - auth_token(us.authToken) - } - } - } - } - } - } - - /******************************************* - * IS_MEETING_RUNNING API - *******************************************/ - def isMeetingRunning = { - String API_CALL = 'isMeetingRunning' - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return + } } - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - } + /*********************************************** + * CONFIG API + ***********************************************/ + def configXML = { - // Do we have a meeting id? If none, complain. - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - errors.missingParamError("meetingID"); - } - } else { - errors.missingParamError("meetingID"); - } - String externalMeetingId = params.meetingID + if (! session["user-token"] || (meetingService.getUserSession(session['user-token']) == null)) { + log.info("No session for user in conference.") + Meeting meeting = null; - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - // Everything is good so far. Translate the external meeting id to an internal meeting id. If - // we can't find the meeting, complain. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); - log.info("Retrieving meeting ${internalMeetingId}") - Meeting meeting = meetingService.getMeeting(internalMeetingId); - boolean isRunning = meeting != null && meeting.isRunning(); - - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - running(isRunning ? "true" : "false") - } - } - } - } - } - - /************************************ - * END API - ************************************/ - def end = { - String API_CALL = "end" - - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } + // Determine the logout url so we can send the user there. + String logoutUrl = session["logout-url"] - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - - if (StringUtils.isEmpty(params.password)) { - invalid("invalidPassword","You must supply the moderator password for this call."); - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - } + if (! session['meeting-id']) { + meeting = meetingService.getMeeting(session['meeting-id']); + } - // Do we have a meeting id? If none, complain. - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - errors.missingParamError("meetingID"); - } - } else { - errors.missingParamError("meetingID"); - } - String externalMeetingId = params.meetingID + // Log the user out of the application. + session.invalidate() - // Do we have a password? If not, complain. - String modPW = params.password - if (StringUtils.isEmpty(modPW)) { - errors.missingParamError("password"); - } + if (meeting != null) { + log.debug("Logging out from [" + meeting.getInternalId() + "]"); + logoutUrl = meeting.getLogoutUrl(); + } - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - // Everything is good so far. Translate the external meeting id to an internal meeting id. If - // we can't find the meeting, complain. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); - log.info("Retrieving meeting ${internalMeetingId}") - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("notFound", "We could not find a meeting with that meeting ID - perhaps the meeting is not yet running?"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - if (meeting.getModeratorPassword().equals(modPW) == false) { - // BEGIN - backward compatibility - invalid("invalidPassword","You must supply the moderator password for this call."); - return; - // END - backward compatibility - - errors.invalidPasswordError(); - respondWithErrors(errors) - return; - } - - meetingService.endMeeting(meeting.getInternalId()); - - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - messageKey("sentEndMeetingRequest") - message("A request to end the meeting was sent. Please wait a few seconds, and then use the getMeetingInfo or isMeetingRunning API calls to verify that it was ended.") - } - } - } - } - } - - /***************************************** - * GETMEETINGINFO API - *****************************************/ - def getMeetingInfo = { - String API_CALL = "getMeetingInfo" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - } + if (StringUtils.isEmpty(logoutUrl)) + logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() + + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode("FAILED") + message("Could not find conference.") + logoutURL() { mkp.yield(logoutUrl) } + } + } + } + } + } else { + UserSession us = meetingService.getUserSession(session['user-token']); + log.info("Found session for " + us.fullname) - // Do we have a meeting id? If none, complain. - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - errors.missingParamError("meetingID"); - } - } else { - errors.missingParamError("meetingID"); - } - String externalMeetingId = params.meetingID + response.addHeader("Cache-Control", "no-cache") + render text: us.configXML, contentType: 'text/xml' + } - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - // Everything is good so far. Translate the external meeting id to an internal meeting id. If - // we can't find the meeting, complain. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingId); - log.info("Retrieving meeting ${internalMeetingId}") - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("notFound", "We could not find a meeting with that meeting ID"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - respondWithConferenceDetails(meeting, null, null, null); - } - - /************************************ - * GETMEETINGS API - ************************************/ - def getMeetingsHandler = { - String API_CALL = "getMeetings" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); } - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - Collection<Meeting> mtgs = meetingService.getMeetings(); - - if (mtgs == null || mtgs.isEmpty()) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - meetings() - messageKey("noMeetings") - message("no meetings were found on this server") - } - } - } - } - } else { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - meetings { - for (m in mtgs) { - meeting { - meetingID() { mkp.yield(m.getExternalId()) } - meetingName() { mkp.yield(m.getName()) } - createTime(m.getCreateTime()) - createDate(formatPrettyDate(m.getCreateTime())) - voiceBridge() { mkp.yield(m.getTelVoice()) } - dialNumber() { mkp.yield(m.getDialNumber()) } - attendeePW() { mkp.yield(m.getViewerPassword()) } - moderatorPW() { mkp.yield(m.getModeratorPassword()) } - hasBeenForciblyEnded(m.isForciblyEnded() ? "true" : "false") - running(m.isRunning() ? "true" : "false") - participantCount(m.getNumUsers()) - listenerCount(m.getNumListenOnly()) - voiceParticipantCount(m.getNumVoiceJoined()) - videoCount(m.getNumVideos()) - duration(m.duration) - hasUserJoined(m.hasUserJoined()) + /*********************************************** + * ENTER API + ***********************************************/ + def enter = { + boolean reject = false; + + UserSession us = null; + Meeting meeting = null; + + if (!session["user-token"]) { + reject = true; + } else { + if (meetingService.getUserSession(session['user-token']) == null) + reject = true; + else { + us = meetingService.getUserSession(session['user-token']); + meeting = meetingService.getMeeting(us.meetingID); + if (meeting == null || meeting.isForciblyEnded()) { + reject = true + } + } + } + + if (reject) { + log.info("No session for user in conference.") + + // Determine the logout url so we can send the user there. + String logoutUrl = session["logout-url"] + + if (! session['meeting-id']) { + meeting = meetingService.getMeeting(session['meeting-id']); + } + + // Log the user out of the application. + session.invalidate() + + if (meeting != null) { + log.debug("Logging out from [" + meeting.getInternalId() + "]"); + logoutUrl = meeting.getLogoutUrl(); + } + + if (StringUtils.isEmpty(logoutUrl)) + logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() + + response.addHeader("Cache-Control", "no-cache") + withFormat { + json { + render(contentType: "application/json") { + response = { + returncode = "FAILED" + message = "Could not find conference." + logoutURL = logoutUrl + } } - } } - } } - } - } - } - } - - /************************************ - * GETSESSIONS API - ************************************/ - def getSessionsHandler = { - String API_CALL = "getSessions" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); + } else { + + Map<String,String> userCustomData = paramsProcessorUtil.getUserCustomData(params); + + // Generate a new userId for this user. This prevents old connections from + // removing the user when the user reconnects after being disconnected. (ralam jan 22, 2015) + // We use underscore (_) to associate userid with the user. We are also able to track + // how many times a user reconnects or refresh the browser. + String newInternalUserID = us.internalUserId + "_" + us.incrementConnectionNum() + + log.info("Found conference for " + us.fullname) + response.addHeader("Cache-Control", "no-cache") + withFormat { + json { + render(contentType: "application/json") { + response = { + returncode = "SUCCESS" + fullname = us.fullname + confname = us.conferencename + meetingID = us.meetingID + externMeetingID = us.externMeetingID + externUserID = us.externUserID + internalUserID = newInternalUserID + authToken = us.authToken + role = us.role + conference = us.conference + room = us.room + voicebridge = us.voicebridge + dialnumber = meeting.getDialNumber() + webvoiceconf = us.webvoiceconf + mode = us.mode + record = us.record + allowStartStopRecording = meeting.getAllowStartStopRecording() + welcome = us.welcome + if (! StringUtils.isEmpty(meeting.moderatorOnlyMessage)) + modOnlyMessage = meeting.moderatorOnlyMessage + logoutUrl = us.logoutUrl + defaultLayout = us.defaultLayout + avatarURL = us.avatarURL + customdata = array { + userCustomData.each { k, v -> + // Somehow we need to prepend something (custdata) for the JSON to work + custdata "$k" : v + } + } + } + } + } + } + } } - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - Collection<Meeting> sssns = meetingService.getSessions(); - - if (sssns == null || sssns.isEmpty()) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - sessions() - messageKey("noSessions") - message("no sessions were found on this server") - } - } - } - } - } else { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - sessions { - for (m in sssns) { - meeting { - meetingID() { mkp.yield(m.meetingID) } - meetingName() { mkp.yield(m.conferencename) } - userName() { mkp.yield(m.fullname) } + /*********************************************** + * STUN/TURN API + ***********************************************/ + def stuns = { + boolean reject = false; + + UserSession us = null; + Meeting meeting = null; + + if (!session["user-token"]) { + reject = true; + } else { + if (meetingService.getUserSession(session['user-token']) == null) + reject = true; + else { + us = meetingService.getUserSession(session['user-token']); + meeting = meetingService.getMeeting(us.meetingID); + if (meeting == null || meeting.isForciblyEnded()) { + reject = true + } + } + } + + if (reject) { + log.info("No session for user in conference.") + + // Determine the logout url so we can send the user there. + String logoutUrl = session["logout-url"] + + if (! session['meeting-id']) { + meeting = meetingService.getMeeting(session['meeting-id']); + } + + // Log the user out of the application. + session.invalidate() + + if (meeting != null) { + log.debug("Logging out from [" + meeting.getInternalId() + "]"); + logoutUrl = meeting.getLogoutUrl(); + } + + if (StringUtils.isEmpty(logoutUrl)) { + logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() + } + + response.addHeader("Cache-Control", "no-cache") + withFormat { + json { + render(contentType: "application/json") { + response = { + returncode = "FAILED" + message = "Could not find conference." + logoutURL = logoutUrl + } } - } } - } } - } - } - } - } - - - def getDefaultConfigXML = { - - String API_CALL = "getDefaultConfigXML" - ApiErrors errors = new ApiErrors(); - - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - String defConfigXML = paramsProcessorUtil.getDefaultConfigXML(); - - response.addHeader("Cache-Control", "no-cache") - render text: defConfigXML, contentType: 'text/xml' - - } - - private Map<String, String[]> getParameters(ServletRequest request) { - // Copy the parameters into our own Map as we can't pass the paramMap - // from the request as it's an unmodifiable map. - Map<String, String[]> reqParams = new HashMap<String, String[]>(); - Map<String, String[]> unModReqParams = request.getParameterMap(); - - SortedSet<String> keys = new TreeSet<String>(unModReqParams.keySet()); - - for (String key: keys) { - reqParams.put(key, unModReqParams.get(key)); + } else { + Set<String> stuns = stunTurnService.getStunServers() + Set<TurnEntry> turns = stunTurnService.getStunAndTurnServersFor(us.internalUserId) + + response.addHeader("Cache-Control", "no-cache") + withFormat { + json { + render(contentType: "application/json") { + stunServers = array { + stuns.each { stun -> + stunData = { url = stun.url } + } + } + turnServers = array { + turns.each { turn -> + turnData = { + username = turn.username + password = turn.password + url = turn.url + ttl = turn.ttl + } + } + } + } + } + } + } } - return reqParams; - } - /*********************************************** - * POLL API - ***********************************************/ - def setPollXML = { - String API_CALL = "setPollXML" - log.debug CONTROLLER_NAME + "#${API_CALL}" + /************************************************* + * SIGNOUT API + *************************************************/ + def signOut = { + Meeting meeting = null; - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (StringUtils.isEmpty(params.pollXML)) { - invalid("configXMLError", "You did not pass a poll XML") - return - } + if (session["user-token"] && (meetingService.getUserSession(session['user-token']) != null)) { + log.info("Found session for user in conference.") + UserSession us = meetingService.removeUserSession(session['user-token']); + meeting = meetingService.getMeeting(us.meetingID); + } - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - - // Translate the external meeting id into an internal meeting id. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - Map<String, String[]> reqParams = getParameters(request) - - String pollXML = params.pollXML - - String decodedPollXML; - - try { - decodedPollXML = URLDecoder.decode(pollXML, "UTF-8"); - } catch (UnsupportedEncodingException e) { - log.error("Couldn't decode poll XML."); - invalid("pollXMLError", "Cannot decode poll XML") - return; - } - - if (! paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("pollXMLChecksumError") - message("pollXMLChecksumError: request did not pass the checksum security check.") - } - } - } - } - } else { - - def pollxml = new XmlSlurper().parseText(decodedPollXML); - - pollxml.children().each { poll -> - String title = poll.title.text(); - String question = poll.question.text(); - String questionType = poll.questionType.text(); - - ArrayList<String> answers = new ArrayList<String>(); - poll.answers.children().each { answer -> - answers.add(answer.text()); - } - - //send poll to BigBlueButton Apps - meetingService.createdPolls(meeting.getInternalId(), title, question, questionType, answers); - } - - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("SUCCESS") - } - } - } - } - } - } - - /*********************************************** - * CONFIG API - ***********************************************/ - def setConfigXML = { - String API_CALL = "setConfigXML" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (StringUtils.isEmpty(params.configXML)) { - invalid("configXMLError", "You did not pass a config XML") - return - } - - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - - // Translate the external meeting id into an internal meeting id. - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - Map<String, String[]> reqParams = getParameters(request) - - String configXML = params.configXML - - String decodedConfigXML; - - try { - decodedConfigXML = URLDecoder.decode(configXML, "UTF-8"); - } catch (UnsupportedEncodingException e) { - log.error("Couldn't decode config XML."); - invalid("configXMLError", "Cannot decode config XML") - return; - } - - if (! paramsProcessorUtil.isPostChecksumSame(API_CALL, reqParams)) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("configXMLChecksumError") - message("configXMLChecksumError: request did not pass the checksum security check.") - } - } - } - } - } else { - boolean defaultConfig = false; - - if (! StringUtils.isEmpty(params.defaultConfig)) { - try { - defaultConfig = Boolean.parseBoolean(params.defaultConfig); - } catch(Exception e) { - defaultConfig = false; - } - } - - - String token = meeting.storeConfig(defaultConfig, decodedConfigXML); - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("SUCCESS") - configToken(token) - } - } - } - } - } - } - - /*********************************************** - * CALLBACK API - ***********************************************/ - def subscribeEvent = { - String API_CALL = "subscribeEvent" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (StringUtils.isEmpty(params.callbackURL)) { - invalid("missingParamCallbackURL", "You must specify a callbackURL for subscribing"); - return - } + String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } + if ((meeting == null) && (! session['meeting-id'])) { + meeting = meetingService.getMeeting(session['meeting-id']); + } - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("subscribeEventChecksumError") - message("subscribeEventChecksumError: request did not pass the checksum security check.") - } - } - } - } - } else { - String sid = meetingService.addSubscription(meeting.getInternalId(), meeting.getExternalId(), params.callbackURL); - - if(sid.isEmpty()){ - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("subscribeEventError") - message("subscribeEventError: An error happen while storing your subscription. Check the logs.") - } - } - } + // Log the user out of the application. + session.invalidate() + + if (meeting != null) { + log.debug("Logging out from [" + meeting.getInternalId() + "]"); + logoutUrl = meeting.getLogoutUrl(); } - }else{ + log.debug("Signing out. Redirecting to " + logoutUrl) response.addHeader("Cache-Control", "no-cache") withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("SUCCESS") - subscriptionID(sid) - } + xml { + render(contentType:"text/xml") { + response() { returncode(RESP_CODE_SUCCESS) } + } } - } } - } } - } - def unsubscribeEvent = { - String API_CALL = "unsubscribeEvent" - log.debug CONTROLLER_NAME + "#${API_CALL}" + /****************************************************** + * GET_RECORDINGS API + ******************************************************/ + def getRecordingsHandler = { + String API_CALL = "getRecordings" + log.debug CONTROLLER_NAME + "#${API_CALL}" - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (StringUtils.isEmpty(params.subscriptionID)) { - invalid("missingParamSubscriptionID", "You must pass a subscriptionID for unsubscribing") - return - } + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("unsubscribeEventChecksumError") - message("unsubscribeEventChecksumError: request did not pass the checksum security check.") - } - } - } - } - } else { - boolean status = meetingService.removeSubscription(meeting.getInternalId(), params.subscriptionID); - - if(!status){ - response.addHeader("Cache-Control", "no-cache") + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + ArrayList<String> externalMeetingIds = new ArrayList<String>(); + if (!StringUtils.isEmpty(params.meetingID)) { + externalMeetingIds=paramsProcessorUtil.decodeIds(params.meetingID); + } + + // Everything is good so far. Translate the external meeting ids to an internal meeting ids. + ArrayList<String> internalMeetingIds = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingIds); + HashMap<String,Recording> recs = meetingService.getRecordings(internalMeetingIds); + recs = meetingService.filterRecordingsByMetadata(recs, ParamsProcessorUtil.processMetaParam(params)); + + if (recs.isEmpty()) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + recordings(null) + messageKey("noRecordings") + message("There are not recordings for the meetings") + } + } + } + } + return; + } + def cfg = new Configuration() + + // Load the XML template + // TODO: Maybe there is a better way to define the templates path + def wtl = new WebappTemplateLoader(getServletContext(), "/WEB-INF/freemarker") + cfg.setTemplateLoader(wtl) + def ftl = cfg.getTemplate("get-recordings.ftl") + def xmlText = new StringWriter() + ftl.process([code:RESP_CODE_SUCCESS, recs:recs.values()], xmlText) withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("unsubscribeEventError") - message("unsubscribeEventError: An error happen while unsubscribing. Check the logs.") - } + xml { + render(text: xmlText.toString(), contentType: "text/xml") } - } } + } - }else{ - response.addHeader("Cache-Control", "no-cache") + /****************************************************** + * PUBLISH_RECORDINGS API + ******************************************************/ + + def publishRecordings = { + String API_CALL = "publishRecordings" + log.debug CONTROLLER_NAME + "#${API_CALL}" + + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + + if (StringUtils.isEmpty(params.recordID)) { + invalid("missingParamRecordID", "You must specify a recordID."); + return + } + + if (StringUtils.isEmpty(params.publish)) { + invalid("missingParamPublish", "You must specify a publish value true or false."); + return + } + + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + // Do we have a recording id? If none, complain. + String recordId = params.recordID + if (StringUtils.isEmpty(recordId)) { + errors.missingParamError("recordID"); + } + // Do we have a publish status? If none, complain. + String publish = params.publish + if (StringUtils.isEmpty(publish)) { + errors.missingParamError("publish"); + } + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + ArrayList<String> recordIdList = new ArrayList<String>(); + if (!StringUtils.isEmpty(recordId)) { + recordIdList=paramsProcessorUtil.decodeIds(recordId); + } + + if(!meetingService.existsAnyRecording(recordIdList)){ + // BEGIN - backward compatibility + invalid("notFound", "We could not find recordings"); + return; + // END - backward compatibility + + errors.recordingNotFound(); + respondWithErrors(errors); + return; + } + + meetingService.setPublishRecording(recordIdList,publish.toBoolean()); withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("SUCCESS") - unsubscribed(status) - } + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + published(publish) + } + } } - } } - } } - } - def listSubscriptions = { - String API_CALL = "listSubscriptions" - log.debug CONTROLLER_NAME + "#${API_CALL}" + /****************************************************** + * DELETE_RECORDINGS API + ******************************************************/ + def deleteRecordings = { + String API_CALL = "deleteRecordings" + log.debug CONTROLLER_NAME + "#${API_CALL}" - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } + // BEGIN - backward compatibility + if (StringUtils.isEmpty(params.checksum)) { + invalid("checksumError", "You did not pass the checksum security check") + return + } - if(!StringUtils.isEmpty(params.meetingID)) { - params.meetingID = StringUtils.strip(params.meetingID); - if (StringUtils.isEmpty(params.meetingID)) { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } - } else { - invalid("missingParamMeetingID", "You must specify a meeting ID for the meeting."); - return - } + if (StringUtils.isEmpty(params.recordID)) { + invalid("missingParamRecordID", "You must specify a recordID."); + return + } - String internalMeetingId = paramsProcessorUtil.convertToInternalMeetingId(params.meetingID); - Meeting meeting = meetingService.getMeeting(internalMeetingId); - if (meeting == null) { - // BEGIN - backward compatibility - invalid("invalidMeetingIdentifier", "The meeting ID that you supplied did not match any existing meetings"); - return; - // END - backward compatibility - - errors.invalidMeetingIdError(); - respondWithErrors(errors) - return; - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - messageKey("listSubscriptionsChecksumError") - message("listSubscriptionsChecksumError: request did not pass the checksum security check.") - } - } - } - } - } else { - List<Map<String,String>> list = meetingService.listSubscriptions(meeting.getInternalId()); - - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("SUCCESS") - subscriptions() { - list.each{ item -> - subscription(){ - subscriptionID() { mkp.yield(item.get("subscriptionID")) } - event() { mkp.yield(item.get("event")) } - callbackURL() { mkp.yield(item.get("callbackURL")) } - active() { mkp.yield(item.get("active")) } - } + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + invalid("checksumError", "You did not pass the checksum security check") + return + } + // END - backward compatibility + + ApiErrors errors = new ApiErrors() + + // Do we have a checksum? If none, complain. + if (StringUtils.isEmpty(params.checksum)) { + errors.missingParamError("checksum"); + } + + // Do we have a recording id? If none, complain. + String recordId = params.recordID + if (StringUtils.isEmpty(recordId)) { + errors.missingParamError("recordID"); + } + + if (errors.hasErrors()) { + respondWithErrors(errors) + return + } + + // Do we agree on the checksum? If not, complain. + if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { + errors.checksumError() + respondWithErrors(errors) + return + } + + ArrayList<String> recordIdList = new ArrayList<String>(); + if (!StringUtils.isEmpty(recordId)) { + recordIdList=paramsProcessorUtil.decodeIds(recordId); + } + + if(recordIdList.isEmpty()){ + // BEGIN - backward compatibility + invalid("notFound", "We could not find recordings"); + return; + // END - backward compatibility + + errors.recordingNotFound(); + respondWithErrors(errors); + return; + } + + meetingService.deleteRecordings(recordIdList); + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + deleted(true) + } } - } } - } } - } - } - } - - /*********************************************** - * CONFIG API - ***********************************************/ - def configXML = { - - if (! session["user-token"] || (meetingService.getUserSession(session['user-token']) == null)) { - log.info("No session for user in conference.") - - Meeting meeting = null; - - // Determine the logout url so we can send the user there. - String logoutUrl = session["logout-url"] - - if (! session['meeting-id']) { - meeting = meetingService.getMeeting(session['meeting-id']); - } - - // Log the user out of the application. - session.invalidate() - - if (meeting != null) { - log.debug("Logging out from [" + meeting.getInternalId() + "]"); - logoutUrl = meeting.getLogoutUrl(); - } - - if (StringUtils.isEmpty(logoutUrl)) - logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() - - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode("FAILED") - message("Could not find conference.") - logoutURL() { mkp.yield(logoutUrl) } - } - } - } - } - } else { - UserSession us = meetingService.getUserSession(session['user-token']); - log.info("Found session for " + us.fullname) - - response.addHeader("Cache-Control", "no-cache") - render text: us.configXML, contentType: 'text/xml' - } - - } - - /*********************************************** - * ENTER API - ***********************************************/ - def enter = { - boolean reject = false; - - UserSession us = null; - Meeting meeting = null; - - if (!session["user-token"]) { - reject = true; - } else { - if (meetingService.getUserSession(session['user-token']) == null) - reject = true; - else { - us = meetingService.getUserSession(session['user-token']); - meeting = meetingService.getMeeting(us.meetingID); - if (meeting == null || meeting.isForciblyEnded()) { - reject = true - } - } + + def uploadDocuments(conf) { + log.debug("ApiController#uploadDocuments(${conf.getInternalId()})"); + + String requestBody = request.inputStream == null ? null : request.inputStream.text; + requestBody = StringUtils.isEmpty(requestBody) ? null : requestBody; + + if (requestBody == null) { + downloadAndProcessDocument(presentationService.defaultUploadedPresentation, conf.getInternalId()); + } else { + log.debug "Request body: \n" + requestBody; + def xml = new XmlSlurper().parseText(requestBody); + xml.children().each { module -> + log.debug("module config found: [${module.@name}]"); + + if ("presentation".equals(module.@name.toString())) { + // need to iterate over presentation files and process them + module.children().each { document -> + if (!StringUtils.isEmpty(document.@url.toString())) { + downloadAndProcessDocument(document.@url.toString(), conf.getInternalId()); + } else if (!StringUtils.isEmpty(document.@name.toString())) { + def b64 = new Base64() + def decodedBytes = b64.decode(document.text().getBytes()) + processDocumentFromRawBytes(decodedBytes, document.@name.toString(), conf.getInternalId()); + } else { + log.debug("presentation module config found, but it did not contain url or name attributes"); + } + } + } + } + } } - if (reject) { - log.info("No session for user in conference.") - - // Determine the logout url so we can send the user there. - String logoutUrl = session["logout-url"] - - if (! session['meeting-id']) { - meeting = meetingService.getMeeting(session['meeting-id']); - } - - // Log the user out of the application. - session.invalidate() - - if (meeting != null) { - log.debug("Logging out from [" + meeting.getInternalId() + "]"); - logoutUrl = meeting.getLogoutUrl(); - } - - if (StringUtils.isEmpty(logoutUrl)) - logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() - - response.addHeader("Cache-Control", "no-cache") - withFormat { - json { - render(contentType: "application/json") { - response = { - returncode = "FAILED" - message = "Could not find conference." - logoutURL = logoutUrl - } - } - } - } - } else { - - Map<String,String> userCustomData = paramsProcessorUtil.getUserCustomData(params); - - // Generate a new userId for this user. This prevents old connections from - // removing the user when the user reconnects after being disconnected. (ralam jan 22, 2015) - // We use underscore (_) to associate userid with the user. We are also able to track - // how many times a user reconnects or refresh the browser. - String newInternalUserID = us.internalUserId + "_" + us.incrementConnectionNum() - - log.info("Found conference for " + us.fullname) - response.addHeader("Cache-Control", "no-cache") - withFormat { - json { - render(contentType: "application/json") { - response = { - returncode = "SUCCESS" - fullname = us.fullname - confname = us.conferencename - meetingID = us.meetingID - externMeetingID = us.externMeetingID - externUserID = us.externUserID - internalUserID = newInternalUserID - authToken = us.authToken - role = us.role - conference = us.conference - room = us.room - voicebridge = us.voicebridge - dialnumber = meeting.getDialNumber() - webvoiceconf = us.webvoiceconf - mode = us.mode - record = us.record - allowStartStopRecording = meeting.getAllowStartStopRecording() - welcome = us.welcome - if (! StringUtils.isEmpty(meeting.moderatorOnlyMessage)) - modOnlyMessage = meeting.moderatorOnlyMessage - logoutUrl = us.logoutUrl - defaultLayout = us.defaultLayout - avatarURL = us.avatarURL - customdata = array { - userCustomData.each { k, v -> - // Somehow we need to prepend something (custdata) for the JSON to work - custdata "$k" : v - } - } - } - } - } - } - } - } - - /*********************************************** - * STUN/TURN API - ***********************************************/ - def stuns = { - boolean reject = false; - - UserSession us = null; - Meeting meeting = null; - - if (!session["user-token"]) { - reject = true; - } else { - if (meetingService.getUserSession(session['user-token']) == null) - reject = true; - else { - us = meetingService.getUserSession(session['user-token']); - meeting = meetingService.getMeeting(us.meetingID); - if (meeting == null || meeting.isForciblyEnded()) { - reject = true - } - } + + def processDocumentFromRawBytes(bytes, presFilename, meetingId) { + def filenameExt = Util.getFilenameExt(presFilename); + String presentationDir = presentationService.getPresentationDir() + def presId = Util.generatePresentationId(presFilename) + File uploadDir = Util.createPresentationDirectory(meetingId, presentationDir, presId) + if (uploadDir != null) { + def newFilename = Util.createNewFilename(presId, filenameExt) + def pres = new File(uploadDir.absolutePath + File.separatorChar + newFilename); + + FileOutputStream fos = new java.io.FileOutputStream(pres) + fos.write(bytes) + fos.flush() + fos.close() + + processUploadedFile(meetingId, presId, presFilename, pres); + } + } - if (reject) { - log.info("No session for user in conference.") - - // Determine the logout url so we can send the user there. - String logoutUrl = session["logout-url"] - - if (! session['meeting-id']) { - meeting = meetingService.getMeeting(session['meeting-id']); - } - - // Log the user out of the application. - session.invalidate() - - if (meeting != null) { - log.debug("Logging out from [" + meeting.getInternalId() + "]"); - logoutUrl = meeting.getLogoutUrl(); - } - - if (StringUtils.isEmpty(logoutUrl)) { - logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() - } - - response.addHeader("Cache-Control", "no-cache") - withFormat { - json { - render(contentType: "application/json") { - response = { - returncode = "FAILED" - message = "Could not find conference." - logoutURL = logoutUrl - } - } - } - } - } else { - Set<String> stuns = stunTurnService.getStunServers() - Set<TurnEntry> turns = stunTurnService.getStunAndTurnServersFor(us.internalUserId) - - response.addHeader("Cache-Control", "no-cache") - withFormat { - json { - render(contentType: "application/json") { - stunServers = array { - stuns.each { stun -> - stunData = { - url = stun.url - } - } - } - turnServers = array { - turns.each { turn -> - turnData = { - username = turn.username - password = turn.password - url = turn.url - ttl = turn.ttl - } - } - } - } - } - } - } - } - - - /************************************************* - * SIGNOUT API - *************************************************/ - def signOut = { - Meeting meeting = null; - - if (session["user-token"] && (meetingService.getUserSession(session['user-token']) != null)) { - log.info("Found session for user in conference.") - UserSession us = meetingService.removeUserSession(session['user-token']); - meeting = meetingService.getMeeting(us.meetingID); - } - - String logoutUrl = paramsProcessorUtil.getDefaultLogoutUrl() - - if ((meeting == null) && (! session['meeting-id'])) { - meeting = meetingService.getMeeting(session['meeting-id']); - } - - // Log the user out of the application. - session.invalidate() - - if (meeting != null) { - log.debug("Logging out from [" + meeting.getInternalId() + "]"); - logoutUrl = meeting.getLogoutUrl(); - } - - log.debug("Signing out. Redirecting to " + logoutUrl) - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - } - } - } + def downloadAndProcessDocument(address, meetingId) { + log.debug("ApiController#downloadAndProcessDocument(${address}, ${meetingId})"); + String presFilename = address.tokenize("/")[-1]; + def filenameExt = presDownloadService.getFilenameExt(presFilename); + String presentationDir = presentationService.getPresentationDir() + + def presId = presDownloadService.generatePresentationId(presFilename) + File uploadDir = presDownloadService.createPresentationDirectory(meetingId, presentationDir, presId) + if (uploadDir != null) { + def newFilename = presDownloadService.createNewFilename(presId, filenameExt) + def newFilePath = uploadDir.absolutePath + File.separatorChar + newFilename + + if (presDownloadService.savePresentation(meetingId, newFilePath, address)) { + def pres = new File(newFilePath) + processUploadedFile(meetingId, presId, presFilename, pres); + } else { + log.error("Failed to download presentation=[${address}], meeting=[${meetingId}]") + } + } } - } - - /****************************************************** - * GET_RECORDINGS API - ******************************************************/ - def getRecordingsHandler = { - String API_CALL = "getRecordings" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - respondWithErrors(errors) - return + + + def processUploadedFile(meetingId, presId, filename, presFile) { + def presentationBaseUrl = presentationService.presentationBaseUrl + UploadedPresentation uploadedPres = new UploadedPresentation(meetingId, presId, filename, presentationBaseUrl); + uploadedPres.setUploadedFile(presFile); + presentationService.processUploadedPresentation(uploadedPres); } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return + + def beforeInterceptor = { + if (paramsProcessorUtil.isServiceEnabled() == false) { + log.info("apiNotEnabled: The API service and/or controller is not enabled on this server. To use it, you must first enable it.") + // TODO: this doesn't stop the request - so it generates invalid XML + // since the request continues and renders a second response + invalid("apiNotEnabled", "The API service and/or controller is not enabled on this server. To use it, you must first enable it.") + } } - - ArrayList<String> externalMeetingIds = new ArrayList<String>(); - if (!StringUtils.isEmpty(params.meetingID)) { - externalMeetingIds=paramsProcessorUtil.decodeIds(params.meetingID); - } - - // Everything is good so far. Translate the external meeting ids to an internal meeting ids. - ArrayList<String> internalMeetingIds = paramsProcessorUtil.convertToInternalMeetingId(externalMeetingIds); - HashMap<String,Recording> recs = meetingService.getRecordings(internalMeetingIds); - recs = meetingService.filterRecordingsByMetadata(recs, ParamsProcessorUtil.processMetaParam(params)); - - if (recs.isEmpty()) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - recordings(null) - messageKey("noRecordings") - message("There are not recordings for the meetings") - } - } - } - } - return; + + def formatPrettyDate(timestamp) { + // SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); + // return ft.format(new Date(timestamp)) + + return new Date(timestamp).toString() } - def cfg = new Configuration() - - // Load the XML template - // TODO: Maybe there is a better way to define the templates path - def wtl = new WebappTemplateLoader(getServletContext(), "/WEB-INF/freemarker") - cfg.setTemplateLoader(wtl) - def ftl = cfg.getTemplate("get-recordings.ftl") - def xmlText = new StringWriter() - ftl.process([code:RESP_CODE_SUCCESS, recs:recs.values()], xmlText) - withFormat { - xml { - render(text: xmlText.toString(), contentType: "text/xml") - } + + def respondWithConferenceDetails(meeting, room, msgKey, msg) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + meetingName() { mkp.yield(meeting.getName()) } + meetingID() { mkp.yield(meeting.getExternalId()) } + internalMeetingID(meeting.getInternalId()) + createTime(meeting.getCreateTime()) + createDate(formatPrettyDate(meeting.getCreateTime())) + voiceBridge() { mkp.yield(meeting.getTelVoice()) } + dialNumber() { mkp.yield(meeting.getDialNumber()) } + attendeePW() { mkp.yield(meeting.getViewerPassword()) } + moderatorPW() { mkp.yield(meeting.getModeratorPassword()) } + running(meeting.isRunning() ? "true" : "false") + duration(meeting.duration) + hasUserJoined(meeting.hasUserJoined()) + recording(meeting.isRecord() ? "true" : "false") + hasBeenForciblyEnded(meeting.isForciblyEnded() ? "true" : "false") + startTime(meeting.getStartTime()) + endTime(meeting.getEndTime()) + participantCount(meeting.getNumUsers()) + listenerCount(meeting.getNumListenOnly()) + voiceParticipantCount(meeting.getNumVoiceJoined()) + videoCount(meeting.getNumVideos()) + maxUsers(meeting.getMaxUsers()) + moderatorCount(meeting.getNumModerators()) + attendees() { + meeting.getUsers().each { att -> + attendee() { + userID() { mkp.yield("${att.externalUserId}") } + fullName() { mkp.yield("${att.fullname}") } + role("${att.role}") + isPresenter("${att.isPresenter()}") + isListeningOnly("${att.isListeningOnly()}") + hasJoinedVoice("${att.isVoiceJoined()}") + hasVideo("${att.hasVideo()}") + customdata(){ + meeting.getUserCustomData(att.externalUserId).each{ k,v -> + "$k"("$v") + } + } + } + } + } + metadata(){ + meeting.getMetadata().each{ k,v -> + "$k"("$v") + } + } + messageKey(msgKey == null ? "" : msgKey) + message(msg == null ? "" : msg) + } + } + } + } } - } - - /****************************************************** - * PUBLISH_RECORDINGS API - ******************************************************/ - - def publishRecordings = { - String API_CALL = "publishRecordings" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (StringUtils.isEmpty(params.recordID)) { - invalid("missingParamRecordID", "You must specify a recordID."); - return - } - - if (StringUtils.isEmpty(params.publish)) { - invalid("missingParamPublish", "You must specify a publish value true or false."); - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - } - - // Do we have a recording id? If none, complain. - String recordId = params.recordID - if (StringUtils.isEmpty(recordId)) { - errors.missingParamError("recordID"); - } - // Do we have a publish status? If none, complain. - String publish = params.publish - if (StringUtils.isEmpty(publish)) { - errors.missingParamError("publish"); - } - - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - ArrayList<String> recordIdList = new ArrayList<String>(); - if (!StringUtils.isEmpty(recordId)) { - recordIdList=paramsProcessorUtil.decodeIds(recordId); - } - - if(!meetingService.existsAnyRecording(recordIdList)){ - // BEGIN - backward compatibility - invalid("notFound", "We could not find recordings"); - return; - // END - backward compatibility - - errors.recordingNotFound(); - respondWithErrors(errors); - return; - } - - meetingService.setPublishRecording(recordIdList,publish.toBoolean()); - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - published(publish) - } - } - } - } - } - - /****************************************************** - * DELETE_RECORDINGS API - ******************************************************/ - def deleteRecordings = { - String API_CALL = "deleteRecordings" - log.debug CONTROLLER_NAME + "#${API_CALL}" - - // BEGIN - backward compatibility - if (StringUtils.isEmpty(params.checksum)) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - - if (StringUtils.isEmpty(params.recordID)) { - invalid("missingParamRecordID", "You must specify a recordID."); - return - } - - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - invalid("checksumError", "You did not pass the checksum security check") - return - } - // END - backward compatibility - - ApiErrors errors = new ApiErrors() - - // Do we have a checksum? If none, complain. - if (StringUtils.isEmpty(params.checksum)) { - errors.missingParamError("checksum"); - } - - // Do we have a recording id? If none, complain. - String recordId = params.recordID - if (StringUtils.isEmpty(recordId)) { - errors.missingParamError("recordID"); - } - - if (errors.hasErrors()) { - respondWithErrors(errors) - return - } - - // Do we agree on the checksum? If not, complain. - if (! paramsProcessorUtil.isChecksumSame(API_CALL, params.checksum, request.getQueryString())) { - errors.checksumError() - respondWithErrors(errors) - return - } - - ArrayList<String> recordIdList = new ArrayList<String>(); - if (!StringUtils.isEmpty(recordId)) { - recordIdList=paramsProcessorUtil.decodeIds(recordId); - } - - if(recordIdList.isEmpty()){ - // BEGIN - backward compatibility - invalid("notFound", "We could not find recordings"); - return; - // END - backward compatibility - - errors.recordingNotFound(); - respondWithErrors(errors); - return; - } - - meetingService.deleteRecordings(recordIdList); - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - deleted(true) - } - } - } - } - } - - def uploadDocuments(conf) { - log.debug("ApiController#uploadDocuments(${conf.getInternalId()})"); - - String requestBody = request.inputStream == null ? null : request.inputStream.text; - requestBody = StringUtils.isEmpty(requestBody) ? null : requestBody; - - if (requestBody == null) { - downloadAndProcessDocument(presentationService.defaultUploadedPresentation, conf.getInternalId()); - } else { - log.debug "Request body: \n" + requestBody; - def xml = new XmlSlurper().parseText(requestBody); - xml.children().each { module -> - log.debug("module config found: [${module.@name}]"); - - if ("presentation".equals(module.@name.toString())) { - // need to iterate over presentation files and process them - module.children().each { document -> - if (!StringUtils.isEmpty(document.@url.toString())) { - downloadAndProcessDocument(document.@url.toString(), conf.getInternalId()); - } else if (!StringUtils.isEmpty(document.@name.toString())) { - def b64 = new Base64() - def decodedBytes = b64.decode(document.text().getBytes()) - processDocumentFromRawBytes(decodedBytes, document.@name.toString(), conf.getInternalId()); - } else { - log.debug("presentation module config found, but it did not contain url or name attributes"); - } - } - } - } - } - } - - - def processDocumentFromRawBytes(bytes, presFilename, meetingId) { - def filenameExt = Util.getFilenameExt(presFilename); - String presentationDir = presentationService.getPresentationDir() - def presId = Util.generatePresentationId(presFilename) - File uploadDir = Util.createPresentationDirectory(meetingId, presentationDir, presId) - if (uploadDir != null) { - def newFilename = Util.createNewFilename(presId, filenameExt) - def pres = new File(uploadDir.absolutePath + File.separatorChar + newFilename); - - FileOutputStream fos = new java.io.FileOutputStream(pres) - fos.write(bytes) - fos.flush() - fos.close() - - processUploadedFile(meetingId, presId, presFilename, pres); + + def respondWithConference(meeting, msgKey, msg) { + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + log.debug "Rendering as xml" + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_SUCCESS) + meetingID() { mkp.yield(meeting.getExternalId()) } + attendeePW() { mkp.yield(meeting.getViewerPassword()) } + moderatorPW() { mkp.yield(meeting.getModeratorPassword()) } + createTime(meeting.getCreateTime()) + voiceBridge() { mkp.yield(meeting.getTelVoice()) } + dialNumber() { mkp.yield(meeting.getDialNumber()) } + createDate(formatPrettyDate(meeting.getCreateTime())) + hasUserJoined(meeting.hasUserJoined()) + duration(meeting.duration) + hasBeenForciblyEnded(meeting.isForciblyEnded() ? "true" : "false") + messageKey(msgKey == null ? "" : msgKey) + message(msg == null ? "" : msg) + } + } + } + } } - } - - def downloadAndProcessDocument(address, meetingId) { - log.debug("ApiController#downloadAndProcessDocument(${address}, ${meetingId})"); - String presFilename = address.tokenize("/")[-1]; - def filenameExt = presDownloadService.getFilenameExt(presFilename); - String presentationDir = presentationService.getPresentationDir() - - def presId = presDownloadService.generatePresentationId(presFilename) - File uploadDir = presDownloadService.createPresentationDirectory(meetingId, presentationDir, presId) - if (uploadDir != null) { - def newFilename = presDownloadService.createNewFilename(presId, filenameExt) - def newFilePath = uploadDir.absolutePath + File.separatorChar + newFilename - - if (presDownloadService.savePresentation(meetingId, newFilePath, address)) { - def pres = new File(newFilePath) - processUploadedFile(meetingId, presId, presFilename, pres); - } else { - log.error("Failed to download presentation=[${address}], meeting=[${meetingId}]") - } - } - } - - - def processUploadedFile(meetingId, presId, filename, presFile) { - def presentationBaseUrl = presentationService.presentationBaseUrl - UploadedPresentation uploadedPres = new UploadedPresentation(meetingId, presId, filename, presentationBaseUrl); - uploadedPres.setUploadedFile(presFile); - presentationService.processUploadedPresentation(uploadedPres); - } - - def beforeInterceptor = { - if (paramsProcessorUtil.isServiceEnabled() == false) { - log.info("apiNotEnabled: The API service and/or controller is not enabled on this server. To use it, you must first enable it.") - // TODO: this doesn't stop the request - so it generates invalid XML - // since the request continues and renders a second response - invalid("apiNotEnabled", "The API service and/or controller is not enabled on this server. To use it, you must first enable it.") + def respondWithErrors(errorList) { + log.debug CONTROLLER_NAME + "#invalid" + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_FAILED) + errors() { + ArrayList errs = errorList.getErrors(); + Iterator itr = errs.iterator(); + while (itr.hasNext()){ + String[] er = (String[]) itr.next(); + log.debug CONTROLLER_NAME + "#invalid" + er[0] + error(key: er[0], message: er[1]) + } + } + } + } + } + json { + log.debug "Rendering as json" + render(contentType:"text/json") { + returncode(RESP_CODE_FAILED) + messageKey(key) + message(msg) + } + } + } } - } - - def formatPrettyDate(timestamp) { -// SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); -// return ft.format(new Date(timestamp)) - - return new Date(timestamp).toString() - } - - def respondWithConferenceDetails(meeting, room, msgKey, msg) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - meetingName() { mkp.yield(meeting.getName()) } - meetingID() { mkp.yield(meeting.getExternalId()) } - internalMeetingID(meeting.getInternalId()) - createTime(meeting.getCreateTime()) - createDate(formatPrettyDate(meeting.getCreateTime())) - voiceBridge() { mkp.yield(meeting.getTelVoice()) } - dialNumber() { mkp.yield(meeting.getDialNumber()) } - attendeePW() { mkp.yield(meeting.getViewerPassword()) } - moderatorPW() { mkp.yield(meeting.getModeratorPassword()) } - running(meeting.isRunning() ? "true" : "false") - duration(meeting.duration) - hasUserJoined(meeting.hasUserJoined()) - recording(meeting.isRecord() ? "true" : "false") - hasBeenForciblyEnded(meeting.isForciblyEnded() ? "true" : "false") - startTime(meeting.getStartTime()) - endTime(meeting.getEndTime()) - participantCount(meeting.getNumUsers()) - listenerCount(meeting.getNumListenOnly()) - voiceParticipantCount(meeting.getNumVoiceJoined()) - videoCount(meeting.getNumVideos()) - maxUsers(meeting.getMaxUsers()) - moderatorCount(meeting.getNumModerators()) - attendees() { - meeting.getUsers().each { att -> - attendee() { - userID() { mkp.yield("${att.externalUserId}") } - fullName() { mkp.yield("${att.fullname}") } - role("${att.role}") - isPresenter("${att.isPresenter()}") - isListeningOnly("${att.isListeningOnly()}") - hasJoinedVoice("${att.isVoiceJoined()}") - hasVideo("${att.hasVideo()}") - customdata(){ - meeting.getUserCustomData(att.externalUserId).each{ k,v -> - "$k"("$v") - } - } + //TODO: method added for backward compability, it will be removed in next versions after 0.8 + def invalid(key, msg) { + String deprecatedMsg=" Note: This xml scheme will be DEPRECATED." + log.debug CONTROLLER_NAME + "#invalid" + response.addHeader("Cache-Control", "no-cache") + withFormat { + xml { + render(contentType:"text/xml") { + response() { + returncode(RESP_CODE_FAILED) + messageKey(key) + message(msg) + } } - } - } - metadata(){ - meeting.getMetadata().each{ k,v -> - "$k"("$v") - } - } - messageKey(msgKey == null ? "" : msgKey) - message(msg == null ? "" : msg) - } - } - } - } - } - - def respondWithConference(meeting, msgKey, msg) { - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - log.debug "Rendering as xml" - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_SUCCESS) - meetingID() { mkp.yield(meeting.getExternalId()) } - attendeePW() { mkp.yield(meeting.getViewerPassword()) } - moderatorPW() { mkp.yield(meeting.getModeratorPassword()) } - createTime(meeting.getCreateTime()) - voiceBridge() { mkp.yield(meeting.getTelVoice()) } - dialNumber() { mkp.yield(meeting.getDialNumber()) } - createDate(formatPrettyDate(meeting.getCreateTime())) - hasUserJoined(meeting.hasUserJoined()) - duration(meeting.duration) - hasBeenForciblyEnded(meeting.isForciblyEnded() ? "true" : "false") - messageKey(msgKey == null ? "" : msgKey) - message(msg == null ? "" : msg) - } - } - } + } + json { + log.debug "Rendering as json" + render(contentType:"text/json") { + returncode(RESP_CODE_FAILED) + messageKey(key) + message(msg) + } + } + } } - } - - def respondWithErrors(errorList) { - log.debug CONTROLLER_NAME + "#invalid" - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_FAILED) - errors() { - ArrayList errs = errorList.getErrors(); - Iterator itr = errs.iterator(); - while (itr.hasNext()){ - String[] er = (String[]) itr.next(); - log.debug CONTROLLER_NAME + "#invalid" + er[0] - error(key: er[0], message: er[1]) - } - } - } - } - } - json { - log.debug "Rendering as json" - render(contentType:"text/json") { - returncode(RESP_CODE_FAILED) - messageKey(key) - message(msg) - } - } - } - } - //TODO: method added for backward compability, it will be removed in next versions after 0.8 - def invalid(key, msg) { - String deprecatedMsg=" Note: This xml scheme will be DEPRECATED." - log.debug CONTROLLER_NAME + "#invalid" - response.addHeader("Cache-Control", "no-cache") - withFormat { - xml { - render(contentType:"text/xml") { - response() { - returncode(RESP_CODE_FAILED) - messageKey(key) - message(msg) - } - } - } - json { - log.debug "Rendering as json" - render(contentType:"text/json") { - returncode(RESP_CODE_FAILED) - messageKey(key) - message(msg) - } - } - } - } - - def parseBoolean(obj) { - if (obj instanceof Number) { - return ((Number) obj).intValue() == 1; - } - return false - } - + + def parseBoolean(obj) { + if (obj instanceof Number) { + return ((Number) obj).intValue() == 1; + } + return false + } + } diff --git a/bigbluebutton-web/src/java/org/bigbluebutton/api/MeetingService.java b/bigbluebutton-web/src/java/org/bigbluebutton/api/MeetingService.java index 637b8fd01c..da96918056 100755 --- a/bigbluebutton-web/src/java/org/bigbluebutton/api/MeetingService.java +++ b/bigbluebutton-web/src/java/org/bigbluebutton/api/MeetingService.java @@ -1,21 +1,21 @@ /** -* BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ -* -* Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). -* -* This program is free software; you can redistribute it and/or modify it under the -* terms of the GNU Lesser General Public License as published by the Free Software -* Foundation; either version 3.0 of the License, or (at your option) any later -* version. -* -* BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY -* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. -* -* You should have received a copy of the GNU Lesser General Public License along -* with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. -* -*/ + * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ + * + * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). + * + * This program is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free Software + * Foundation; either version 3.0 of the License, or (at your option) any later + * version. + * + * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. + * + */ package org.bigbluebutton.api; @@ -66,692 +66,718 @@ import org.slf4j.LoggerFactory; import com.google.gson.Gson; public class MeetingService implements MessageListener { - private static Logger log = LoggerFactory.getLogger(MeetingService.class); - - private BlockingQueue<IMessage> receivedMessages = new LinkedBlockingQueue<IMessage>(); - private volatile boolean processMessage = false; - - private final Executor msgProcessorExec = Executors.newSingleThreadExecutor(); - private final Executor runExec = Executors.newSingleThreadExecutor(); - - /** - * http://ria101.wordpress.com/2011/12/12/concurrenthashmap-avoid-a-common-misuse/ - */ - private final ConcurrentMap<String, Meeting> meetings; - private final ConcurrentMap<String, UserSession> sessions; - - private int defaultMeetingExpireDuration = 1; - private int defaultMeetingCreateJoinDuration = 5; - private RecordingService recordingService; - private MessagingService messagingService; - private ExpiredMeetingCleanupTimerTask cleaner; - private boolean removeMeetingWhenEnded = false; - - public MeetingService() { - meetings = new ConcurrentHashMap<String, Meeting>(8, 0.9f, 1); - sessions = new ConcurrentHashMap<String, UserSession>(8, 0.9f, 1); - } - - public void addUserSession(String token, UserSession user) { - sessions.put(token, user); - } - - public void registerUser(String meetingID, String internalUserId, String fullname, String role, String externUserID, String authToken) { - handle(new RegisterUser(meetingID, internalUserId, fullname, role, externUserID, authToken)); - } - - public UserSession getUserSession(String token) { - return sessions.get(token); - } - - public UserSession removeUserSession(String token) { - UserSession user = sessions.remove(token); - if (user != null) { - log.debug("Found user [" + user.fullname + "] token=[" + token + "] to meeting [" + user.meetingID + "]"); - } - return user; - } - - /** - * Remove the meetings that have ended from the list of - * running meetings. - */ - public void removeExpiredMeetings() { - handle(new RemoveExpiredMeetings()); - } - - private void kickOffProcessingOfRecording(Meeting m) { - if (m.isRecord() && m.getNumUsers() == 0) { - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("event", "kick_off_ingest_and_processing"); - logData.put("description", "Start processing of recording."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Initiate recording processing: data={}", logStr); - - processRecording(m.getInternalId()); - } - } - - private void processMeetingForRemoval(Meeting m) { - kickOffProcessingOfRecording(m); - destroyMeeting(m.getInternalId()); - meetings.remove(m.getInternalId()); - removeUserSessions(m.getInternalId()); - } - - private void removeUserSessions(String meetingId) { - Iterator<Map.Entry<String, UserSession>> iterator = sessions.entrySet().iterator(); - while(iterator.hasNext()){ - Map.Entry<String, UserSession> entry = iterator.next(); - UserSession userSession = entry.getValue(); - - if (userSession.meetingID.equals(meetingId)) { - iterator.remove(); - } - } - } - - private void checkAndRemoveExpiredMeetings() { - for (Meeting m : meetings.values()) { - if (m.hasExpired(defaultMeetingExpireDuration) ) { - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("event", "removing_meeting"); - logData.put("description", "Meeting has expired."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - log.info("Removing expired meeting: data={}", logStr); - - processMeetingForRemoval(m); - continue; - } - - if (m.isForciblyEnded()) { - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("event", "removing_meeting"); - logData.put("description", "Meeting forcefully ended."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Removing ended meeting: data={}", logStr); - processMeetingForRemoval(m); - continue; - } - - if (m.wasNeverJoined(defaultMeetingCreateJoinDuration)) { - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("event", "removing_meeting"); - logData.put("description", "Meeting has not been joined."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Removing un-joined meeting: data={}", logStr); - - destroyMeeting(m.getInternalId()); - meetings.remove(m.getInternalId()); - removeUserSessions(m.getInternalId()); - continue; - } - - if (m.hasExceededDuration()) { - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("event", "removing_meeting"); - logData.put("description", "Meeting exceeded duration."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Removing past duration meeting: data={}", logStr); - - endMeeting(m.getInternalId()); - } - } - } - - private void destroyMeeting(String meetingID) { - messagingService.destroyMeeting(meetingID); - } - - public Collection<Meeting> getMeetings() { - return meetings.isEmpty() ? Collections.<Meeting>emptySet() : Collections.unmodifiableCollection(meetings.values()); - } - - public Collection<UserSession> getSessions() { - return sessions.isEmpty() ? Collections.<UserSession>emptySet() : Collections.unmodifiableCollection(sessions.values()); - } - - public void createMeeting(Meeting m) { - handle(new CreateMeeting(m)); - } - - private void handleCreateMeeting(Meeting m) { - meetings.put(m.getInternalId(), m); - if (m.isRecord()) { - Map<String,String> metadata = new LinkedHashMap<String,String>(); - metadata.putAll(m.getMetadata()); - //TODO: Need a better way to store these values for recordings - metadata.put("meetingId", m.getExternalId()); - metadata.put("meetingName", m.getName()); - - messagingService.recordMeetingInfo(m.getInternalId(), metadata); - } - - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("duration", m.getDuration()); - logData.put("record", m.isRecord()); - logData.put("event", "create_meeting"); - logData.put("description", "Create meeting."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Create meeting: data={}", logStr); - - messagingService.createMeeting(m.getInternalId(), m.getExternalId(), m.getName(), m.isRecord(), - m.getTelVoice(), m.getDuration(), m.getAutoStartRecording(), m.getAllowStartStopRecording(), - m.getModeratorPassword(), m.getViewerPassword(), m.getCreateTime(), - formatPrettyDate(m.getCreateTime())); - } - - private String formatPrettyDate(Long timestamp) { - return new Date(timestamp).toString(); - } - - private void processCreateMeeting(CreateMeeting message) { - handleCreateMeeting(message.meeting); - } - - private void processRegisterUser(RegisterUser message) { - messagingService.registerUser(message.meetingID, message.internalUserId, message.fullname, message.role, message.externUserID, message.authToken); - } - - public String addSubscription(String meetingId, String event, String callbackURL){ - String sid = messagingService.storeSubscription(meetingId, event, callbackURL); - return sid; - } - - public boolean removeSubscription(String meetingId, String subscriptionId){ - return messagingService.removeSubscription(meetingId, subscriptionId); - } - - public List<Map<String,String>> listSubscriptions(String meetingId){ - return messagingService.listSubscriptions(meetingId); - } - - public Meeting getMeeting(String meetingId) { - if (meetingId == null) - return null; - for (String key : meetings.keySet()) { - if (key.startsWith(meetingId)) - return (Meeting) meetings.get(key); - } - - return null; - } - - public Collection<Meeting> getMeetingsWithId(String meetingId) { - if (meetingId == null) return Collections.<Meeting>emptySet(); - - Collection<Meeting> m = new HashSet<Meeting>(); - - for (String key : meetings.keySet()) { - if (key.startsWith(meetingId)) - m.add(meetings.get(key)); - } - - return m; - } - - public Meeting getNotEndedMeetingWithId(String meetingId) { - if (meetingId == null) - return null; - for (String key : meetings.keySet()) { - if (key.startsWith(meetingId)) { - Meeting m = (Meeting) meetings.get(key); - if (! m.isForciblyEnded()) return m; - } - } - - return null; - } - - public HashMap<String,Recording> getRecordings(ArrayList<String> idList) { - //TODO: this method shouldn't be used - log.debug("starting to fetch recordings"); - ArrayList<Recording> recsList = recordingService.getRecordings(idList); - log.debug("got all recordings, without ordering"); - HashMap<String,Recording> recs= reorderRecordings(recsList); - log.debug("returning ordered recordings"); - return recs; - } - - public Map<String, Recording> filterRecordingsByMetadata(Map<String, Recording> recordings, Map<String, String> metadataFilters) { - return recordingService.filterRecordingsByMetadata(recordings, metadataFilters); - } - - public HashMap<String,Recording> reorderRecordings(ArrayList<Recording> olds){ - HashMap<String,Recording> map= new HashMap<String, Recording>(); - for (Recording r:olds) { - if (!map.containsKey(r.getId())) { - Map<String,String> meta= r.getMetadata(); - String mid = meta.remove("meetingId"); - String name = meta.remove("meetingName"); - - r.setMeetingID(mid); - r.setName(name); - - ArrayList<Playback> plays = new ArrayList<Playback>(); - - plays.add(new Playback(r.getPlaybackFormat(), r.getPlaybackLink(), - getDurationRecording(r.getPlaybackDuration(), - r.getEndTime(), r.getStartTime()), - r.getPlaybackExtensions())); - r.setPlaybacks(plays); - map.put(r.getId(), r); - } else { - Recording rec = map.get(r.getId()); - rec.getPlaybacks().add(new Playback(r.getPlaybackFormat(), r.getPlaybackLink(), - getDurationRecording(r.getPlaybackDuration(), - r.getEndTime(), r.getStartTime()), - r.getPlaybackExtensions())); - } - } - - return map; - } - - private int getDurationRecording(String playbackDuration, String end, String start) { - int duration; - try { - if (!playbackDuration.equals("")) { - duration = (int)Math.ceil((Long.parseLong(playbackDuration))/60000.0); - } else { - duration = (int)Math.ceil((Long.parseLong(end) - Long.parseLong(start))/60000.0); - } - } catch(Exception e){ - log.debug(e.getMessage()); - duration = 0; - } - - return duration; - } - - public boolean existsAnyRecording(ArrayList<String> idList){ - return recordingService.existAnyRecording(idList); - } - - public void setPublishRecording(ArrayList<String> idList,boolean publish){ - for(String id:idList){ - recordingService.publish(id,publish); - } - } - - public void deleteRecordings(ArrayList<String> idList){ - for(String id:idList){ - recordingService.delete(id); - } - } - - public void processRecording(String meetingId) { - recordingService.startIngestAndProcessing(meetingId); - } - - public boolean isMeetingWithVoiceBridgeExist(String voiceBridge) { -/* Collection<Meeting> confs = meetings.values(); - for (Meeting c : confs) { - if (voiceBridge == c.getVoiceBridge()) { - return true; - } - } -*/ return false; - } - - public void send(String channel, String message) { - messagingService.send(channel, message); - } - - public void createdPolls(String meetingId, String title, String question, String questionType, ArrayList<String> answers){ - messagingService.sendPolls(meetingId, title, question, questionType, answers); - } - - public void endMeeting(String meetingId) { - handle(new EndMeeting(meetingId)); - } - - private void processEndMeeting(EndMeeting message) { - messagingService.endMeeting(message.meetingId); - - Meeting m = getMeeting(message.meetingId); - if (m != null) { - m.setForciblyEnded(true); - if (removeMeetingWhenEnded) { - processRecording(m.getInternalId()); - destroyMeeting(m.getInternalId()); - meetings.remove(m.getInternalId()); - removeUserSessions(m.getInternalId()); - } - } - } - - public void addUserCustomData(String meetingId, String userID, Map<String,String> userCustomData){ - Meeting m = getMeeting(meetingId); - if (m != null){ - m.addUserCustomData(userID, userCustomData); - } - } - - private void meetingStarted(MeetingStarted message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - if (m.getStartTime() == 0) { - long now = System.currentTimeMillis(); - m.setStartTime(now); - - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("duration", m.getDuration()); - logData.put("record", m.isRecord()); - logData.put("event", "meeting_started"); - logData.put("description", "Meeting has started."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Meeting started: data={}", logStr); - - } else { - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("duration", m.getDuration()); - logData.put("record", m.isRecord()); - logData.put("event", "meeting_restarted"); - logData.put("description", "Meeting has restarted."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Meeting restarted: data={}", logStr); - } - return; - } - } - - private void meetingEnded(MeetingEnded message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - long now = System.currentTimeMillis(); - m.setEndTime(now); - - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("duration", m.getDuration()); - logData.put("record", m.isRecord()); - logData.put("event", "meeting_ended"); - logData.put("description", "Meeting has ended."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("Meeting ended: data={}", logStr); - - return; - } - } - - private void userJoined(UserJoined message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = new User(message.userId, message.externalUserId, message.name, message.role); - m.userJoined(user); - - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("userId", message.userId); - logData.put("externalUserId", user.getExternalUserId()); - logData.put("username", user.getFullname()); - logData.put("role", user.getRole()); - logData.put("event", "user_joined_message"); - logData.put("description", "User had joined the meeting."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("User joined meeting: data={}", logStr); - - return; - } - } - - private void userLeft(UserLeft message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.userLeft(message.userId); - if(user != null){ - - Map<String, Object> logData = new HashMap<String, Object>(); - logData.put("meetingId", m.getInternalId()); - logData.put("externalMeetingId", m.getExternalId()); - logData.put("name", m.getName()); - logData.put("userId", message.userId); - logData.put("externalUserId", user.getExternalUserId()); - logData.put("username", user.getFullname()); - logData.put("role", user.getRole()); - logData.put("event", "user_left_message"); - logData.put("description", "User had left the meeting."); - - Gson gson = new Gson(); - String logStr = gson.toJson(logData); - - log.info("User left meeting: data={}", logStr); - - return; - } - return; - } - } - - private void updatedStatus(UserStatusChanged message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.getUserById(message.userId); - if(user != null){ - user.setStatus(message.status, message.value); - return; - } - return; - } - } - - public void userJoinedVoice(UserJoinedVoice message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.getUserById(message.userId); - if(user != null){ - user.setVoiceJoined(true); - return; - } - return; - } - } - - public void userLeftVoice(UserLeftVoice message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.getUserById(message.userId); - if(user != null){ - user.setVoiceJoined(false); - return; - } - return; - } - } - - public void userListeningOnly(UserListeningOnly message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.getUserById(message.userId); - if(user != null){ - user.setListeningOnly(message.listenOnly); - return; - } - return; - } - } - - public void userSharedWebcam(UserSharedWebcam message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.getUserById(message.userId); - if(user != null){ - user.addStream(message.stream); - return; - } - return; - } - } - - public void userUnsharedWebcam(UserUnsharedWebcam message) { - Meeting m = getMeeting(message.meetingId); - if (m != null) { - User user = m.getUserById(message.userId); - if(user != null){ - user.removeStream(message.stream); - return; - } - return; - } - } - - private void processMessage(final IMessage message) { - Runnable task = new Runnable() { - public void run() { - if (message instanceof MeetingDestroyed) { - - } else if (message instanceof MeetingStarted) { - meetingStarted((MeetingStarted)message); - } else if (message instanceof MeetingEnded) { - meetingEnded((MeetingEnded)message); - } else if (message instanceof UserJoined) { - userJoined((UserJoined)message); - } else if (message instanceof UserLeft) { - userLeft((UserLeft)message); - } else if (message instanceof UserStatusChanged) { - updatedStatus((UserStatusChanged)message); - } else if (message instanceof UserJoinedVoice) { - userJoinedVoice((UserJoinedVoice)message); - } else if (message instanceof UserLeftVoice) { - userLeftVoice((UserLeftVoice)message); - } else if (message instanceof UserListeningOnly) { - userListeningOnly((UserListeningOnly)message); - } else if (message instanceof UserSharedWebcam) { - userSharedWebcam((UserSharedWebcam)message); - } else if (message instanceof UserUnsharedWebcam) { - userUnsharedWebcam((UserUnsharedWebcam)message); - } else if (message instanceof RemoveExpiredMeetings) { - checkAndRemoveExpiredMeetings(); - } else if (message instanceof CreateMeeting) { - processCreateMeeting((CreateMeeting)message); - } else if (message instanceof EndMeeting) { - processEndMeeting((EndMeeting)message); - } else if (message instanceof RegisterUser) { - processRegisterUser((RegisterUser) message); - } - } - }; - - runExec.execute(task); - } - - @Override - public void handle(IMessage message) { - receivedMessages.add(message); - } - - public void start() { - log.info("Starting Meeting Service."); - try { - processMessage = true; - Runnable messageReceiver = new Runnable() { - public void run() { - while (processMessage) { - try { - IMessage msg = receivedMessages.take(); - processMessage(msg); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (Exception e) { - log.error("Handling unexpected exception [{}]", e.toString()); - } - } - } - }; - - msgProcessorExec.execute(messageReceiver); - } catch (Exception e) { - log.error("Error PRocessing Message"); - } - } - - public void stop() { - processMessage = false; - cleaner.stop(); - } - - public void setDefaultMeetingCreateJoinDuration(int expiration) { - this.defaultMeetingCreateJoinDuration = expiration; - } - - public void setDefaultMeetingExpireDuration(int meetingExpiration) { - this.defaultMeetingExpireDuration = meetingExpiration; - } - - public void setRecordingService(RecordingService s) { - recordingService = s; - } - - public void setMessagingService(MessagingService mess) { - messagingService = mess; - } - - public void setExpiredMeetingCleanupTimerTask(ExpiredMeetingCleanupTimerTask c) { - cleaner = c; - cleaner.setMeetingService(this); - cleaner.start(); - } - - public void setRemoveMeetingWhenEnded(boolean s) { - removeMeetingWhenEnded = s; - } + private static Logger log = LoggerFactory.getLogger(MeetingService.class); + + private BlockingQueue<IMessage> receivedMessages = new LinkedBlockingQueue<IMessage>(); + private volatile boolean processMessage = false; + + private final Executor msgProcessorExec = Executors + .newSingleThreadExecutor(); + private final Executor runExec = Executors.newSingleThreadExecutor(); + + /** + * http://ria101.wordpress.com/2011/12/12/concurrenthashmap-avoid-a-common- + * misuse/ + */ + private final ConcurrentMap<String, Meeting> meetings; + private final ConcurrentMap<String, UserSession> sessions; + + private int defaultMeetingExpireDuration = 1; + private int defaultMeetingCreateJoinDuration = 5; + private RecordingService recordingService; + private MessagingService messagingService; + private ExpiredMeetingCleanupTimerTask cleaner; + private boolean removeMeetingWhenEnded = false; + + public MeetingService() { + meetings = new ConcurrentHashMap<String, Meeting>(8, 0.9f, 1); + sessions = new ConcurrentHashMap<String, UserSession>(8, 0.9f, 1); + } + + public void addUserSession(String token, UserSession user) { + sessions.put(token, user); + } + + public void registerUser(String meetingID, String internalUserId, + String fullname, String role, String externUserID, String authToken) { + handle(new RegisterUser(meetingID, internalUserId, fullname, role, + externUserID, authToken)); + } + + public UserSession getUserSession(String token) { + return sessions.get(token); + } + + public UserSession removeUserSession(String token) { + UserSession user = sessions.remove(token); + if (user != null) { + log.debug("Found user [" + user.fullname + "] token=[" + token + + "] to meeting [" + user.meetingID + "]"); + } + return user; + } + + /** + * Remove the meetings that have ended from the list of running meetings. + */ + public void removeExpiredMeetings() { + handle(new RemoveExpiredMeetings()); + } + + private void kickOffProcessingOfRecording(Meeting m) { + if (m.isRecord() && m.getNumUsers() == 0) { + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("event", "kick_off_ingest_and_processing"); + logData.put("description", "Start processing of recording."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Initiate recording processing: data={}", logStr); + + processRecording(m.getInternalId()); + } + } + + private void processMeetingForRemoval(Meeting m) { + kickOffProcessingOfRecording(m); + destroyMeeting(m.getInternalId()); + meetings.remove(m.getInternalId()); + removeUserSessions(m.getInternalId()); + } + + private void removeUserSessions(String meetingId) { + Iterator<Map.Entry<String, UserSession>> iterator = sessions.entrySet() + .iterator(); + while (iterator.hasNext()) { + Map.Entry<String, UserSession> entry = iterator.next(); + UserSession userSession = entry.getValue(); + + if (userSession.meetingID.equals(meetingId)) { + iterator.remove(); + } + } + } + + private void checkAndRemoveExpiredMeetings() { + for (Meeting m : meetings.values()) { + if (m.hasExpired(defaultMeetingExpireDuration)) { + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("event", "removing_meeting"); + logData.put("description", "Meeting has expired."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + log.info("Removing expired meeting: data={}", logStr); + + processMeetingForRemoval(m); + continue; + } + + if (m.isForciblyEnded()) { + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("event", "removing_meeting"); + logData.put("description", "Meeting forcefully ended."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Removing ended meeting: data={}", logStr); + processMeetingForRemoval(m); + continue; + } + + if (m.wasNeverJoined(defaultMeetingCreateJoinDuration)) { + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("event", "removing_meeting"); + logData.put("description", "Meeting has not been joined."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Removing un-joined meeting: data={}", logStr); + + destroyMeeting(m.getInternalId()); + meetings.remove(m.getInternalId()); + removeUserSessions(m.getInternalId()); + continue; + } + + if (m.hasExceededDuration()) { + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("event", "removing_meeting"); + logData.put("description", "Meeting exceeded duration."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Removing past duration meeting: data={}", logStr); + + endMeeting(m.getInternalId()); + } + } + } + + private void destroyMeeting(String meetingID) { + messagingService.destroyMeeting(meetingID); + } + + public Collection<Meeting> getMeetings() { + return meetings.isEmpty() ? Collections.<Meeting> emptySet() + : Collections.unmodifiableCollection(meetings.values()); + } + + public Collection<UserSession> getSessions() { + return sessions.isEmpty() ? Collections.<UserSession> emptySet() + : Collections.unmodifiableCollection(sessions.values()); + } + + public void createMeeting(Meeting m) { + handle(new CreateMeeting(m)); + } + + private void handleCreateMeeting(Meeting m) { + meetings.put(m.getInternalId(), m); + if (m.isRecord()) { + Map<String, String> metadata = new LinkedHashMap<String, String>(); + metadata.putAll(m.getMetadata()); + // TODO: Need a better way to store these values for recordings + metadata.put("meetingId", m.getExternalId()); + metadata.put("meetingName", m.getName()); + + messagingService.recordMeetingInfo(m.getInternalId(), metadata); + } + + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("duration", m.getDuration()); + logData.put("record", m.isRecord()); + logData.put("event", "create_meeting"); + logData.put("description", "Create meeting."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Create meeting: data={}", logStr); + + messagingService.createMeeting(m.getInternalId(), m.getExternalId(), + m.getName(), m.isRecord(), m.getTelVoice(), m.getDuration(), + m.getAutoStartRecording(), m.getAllowStartStopRecording(), + m.getModeratorPassword(), m.getViewerPassword(), + m.getCreateTime(), formatPrettyDate(m.getCreateTime())); + } + + private String formatPrettyDate(Long timestamp) { + return new Date(timestamp).toString(); + } + + private void processCreateMeeting(CreateMeeting message) { + handleCreateMeeting(message.meeting); + } + + private void processRegisterUser(RegisterUser message) { + messagingService.registerUser(message.meetingID, + message.internalUserId, message.fullname, message.role, + message.externUserID, message.authToken); + } + + public String addSubscription(String meetingId, String event, + String callbackURL) { + String sid = messagingService.storeSubscription(meetingId, event, + callbackURL); + return sid; + } + + public boolean removeSubscription(String meetingId, String subscriptionId) { + return messagingService.removeSubscription(meetingId, subscriptionId); + } + + public List<Map<String, String>> listSubscriptions(String meetingId) { + return messagingService.listSubscriptions(meetingId); + } + + public Meeting getMeeting(String meetingId) { + if (meetingId == null) + return null; + for (String key : meetings.keySet()) { + if (key.startsWith(meetingId)) + return (Meeting) meetings.get(key); + } + + return null; + } + + public Collection<Meeting> getMeetingsWithId(String meetingId) { + if (meetingId == null) + return Collections.<Meeting> emptySet(); + + Collection<Meeting> m = new HashSet<Meeting>(); + + for (String key : meetings.keySet()) { + if (key.startsWith(meetingId)) + m.add(meetings.get(key)); + } + + return m; + } + + public Meeting getNotEndedMeetingWithId(String meetingId) { + if (meetingId == null) + return null; + for (String key : meetings.keySet()) { + if (key.startsWith(meetingId)) { + Meeting m = (Meeting) meetings.get(key); + if (!m.isForciblyEnded()) + return m; + } + } + + return null; + } + + public HashMap<String, Recording> getRecordings(ArrayList<String> idList) { + // TODO: this method shouldn't be used + log.debug("starting to fetch recordings"); + ArrayList<Recording> recsList = recordingService.getRecordings(idList); + log.debug("got all recordings, without ordering"); + HashMap<String, Recording> recs = reorderRecordings(recsList); + log.debug("returning ordered recordings"); + return recs; + } + + public Map<String, Recording> filterRecordingsByMetadata( + Map<String, Recording> recordings, + Map<String, String> metadataFilters) { + return recordingService.filterRecordingsByMetadata(recordings, + metadataFilters); + } + + public HashMap<String, Recording> reorderRecordings( + ArrayList<Recording> olds) { + HashMap<String, Recording> map = new HashMap<String, Recording>(); + for (Recording r : olds) { + if (!map.containsKey(r.getId())) { + Map<String, String> meta = r.getMetadata(); + String mid = meta.remove("meetingId"); + String name = meta.remove("meetingName"); + + r.setMeetingID(mid); + r.setName(name); + + ArrayList<Playback> plays = new ArrayList<Playback>(); + + plays.add(new Playback(r.getPlaybackFormat(), r + .getPlaybackLink(), getDurationRecording( + r.getPlaybackDuration(), r.getEndTime(), + r.getStartTime()), r.getPlaybackExtensions())); + r.setPlaybacks(plays); + map.put(r.getId(), r); + } else { + Recording rec = map.get(r.getId()); + rec.getPlaybacks().add( + new Playback(r.getPlaybackFormat(), + r.getPlaybackLink(), getDurationRecording( + r.getPlaybackDuration(), + r.getEndTime(), r.getStartTime()), r + .getPlaybackExtensions())); + } + } + + return map; + } + + private int getDurationRecording(String playbackDuration, String end, + String start) { + int duration; + try { + if (!playbackDuration.equals("")) { + duration = (int) Math + .ceil((Long.parseLong(playbackDuration)) / 60000.0); + } else { + duration = (int) Math.ceil((Long.parseLong(end) - Long + .parseLong(start)) / 60000.0); + } + } catch (Exception e) { + log.debug(e.getMessage()); + duration = 0; + } + + return duration; + } + + public boolean existsAnyRecording(ArrayList<String> idList) { + return recordingService.existAnyRecording(idList); + } + + public void setPublishRecording(ArrayList<String> idList, boolean publish) { + for (String id : idList) { + recordingService.publish(id, publish); + } + } + + public void deleteRecordings(ArrayList<String> idList) { + for (String id : idList) { + recordingService.delete(id); + } + } + + public void processRecording(String meetingId) { + recordingService.startIngestAndProcessing(meetingId); + } + + public boolean isMeetingWithVoiceBridgeExist(String voiceBridge) { + /* + * Collection<Meeting> confs = meetings.values(); for (Meeting c : + * confs) { if (voiceBridge == c.getVoiceBridge()) { return true; } } + */return false; + } + + public void send(String channel, String message) { + messagingService.send(channel, message); + } + + public void createdPolls(String meetingId, String title, String question, + String questionType, ArrayList<String> answers) { + messagingService.sendPolls(meetingId, title, question, questionType, + answers); + } + + public void endMeeting(String meetingId) { + handle(new EndMeeting(meetingId)); + } + + private void processEndMeeting(EndMeeting message) { + messagingService.endMeeting(message.meetingId); + + Meeting m = getMeeting(message.meetingId); + if (m != null) { + m.setForciblyEnded(true); + if (removeMeetingWhenEnded) { + processRecording(m.getInternalId()); + destroyMeeting(m.getInternalId()); + meetings.remove(m.getInternalId()); + removeUserSessions(m.getInternalId()); + } + } + } + + public void addUserCustomData(String meetingId, String userID, + Map<String, String> userCustomData) { + Meeting m = getMeeting(meetingId); + if (m != null) { + m.addUserCustomData(userID, userCustomData); + } + } + + private void meetingStarted(MeetingStarted message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + if (m.getStartTime() == 0) { + long now = System.currentTimeMillis(); + m.setStartTime(now); + + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("duration", m.getDuration()); + logData.put("record", m.isRecord()); + logData.put("event", "meeting_started"); + logData.put("description", "Meeting has started."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Meeting started: data={}", logStr); + + } else { + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("duration", m.getDuration()); + logData.put("record", m.isRecord()); + logData.put("event", "meeting_restarted"); + logData.put("description", "Meeting has restarted."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Meeting restarted: data={}", logStr); + } + return; + } + } + + private void meetingEnded(MeetingEnded message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + long now = System.currentTimeMillis(); + m.setEndTime(now); + + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("duration", m.getDuration()); + logData.put("record", m.isRecord()); + logData.put("event", "meeting_ended"); + logData.put("description", "Meeting has ended."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("Meeting ended: data={}", logStr); + + return; + } + } + + private void userJoined(UserJoined message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = new User(message.userId, message.externalUserId, + message.name, message.role); + m.userJoined(user); + + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("userId", message.userId); + logData.put("externalUserId", user.getExternalUserId()); + logData.put("username", user.getFullname()); + logData.put("role", user.getRole()); + logData.put("event", "user_joined_message"); + logData.put("description", "User had joined the meeting."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("User joined meeting: data={}", logStr); + + return; + } + } + + private void userLeft(UserLeft message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.userLeft(message.userId); + if (user != null) { + + Map<String, Object> logData = new HashMap<String, Object>(); + logData.put("meetingId", m.getInternalId()); + logData.put("externalMeetingId", m.getExternalId()); + logData.put("name", m.getName()); + logData.put("userId", message.userId); + logData.put("externalUserId", user.getExternalUserId()); + logData.put("username", user.getFullname()); + logData.put("role", user.getRole()); + logData.put("event", "user_left_message"); + logData.put("description", "User had left the meeting."); + + Gson gson = new Gson(); + String logStr = gson.toJson(logData); + + log.info("User left meeting: data={}", logStr); + + return; + } + return; + } + } + + private void updatedStatus(UserStatusChanged message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.getUserById(message.userId); + if (user != null) { + user.setStatus(message.status, message.value); + return; + } + return; + } + } + + public void userJoinedVoice(UserJoinedVoice message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.getUserById(message.userId); + if (user != null) { + user.setVoiceJoined(true); + return; + } + return; + } + } + + public void userLeftVoice(UserLeftVoice message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.getUserById(message.userId); + if (user != null) { + user.setVoiceJoined(false); + return; + } + return; + } + } + + public void userListeningOnly(UserListeningOnly message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.getUserById(message.userId); + if (user != null) { + user.setListeningOnly(message.listenOnly); + return; + } + return; + } + } + + public void userSharedWebcam(UserSharedWebcam message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.getUserById(message.userId); + if (user != null) { + user.addStream(message.stream); + return; + } + return; + } + } + + public void userUnsharedWebcam(UserUnsharedWebcam message) { + Meeting m = getMeeting(message.meetingId); + if (m != null) { + User user = m.getUserById(message.userId); + if (user != null) { + user.removeStream(message.stream); + return; + } + return; + } + } + + private void processMessage(final IMessage message) { + Runnable task = new Runnable() { + public void run() { + if (message instanceof MeetingDestroyed) { + + } else if (message instanceof MeetingStarted) { + meetingStarted((MeetingStarted) message); + } else if (message instanceof MeetingEnded) { + meetingEnded((MeetingEnded) message); + } else if (message instanceof UserJoined) { + userJoined((UserJoined) message); + } else if (message instanceof UserLeft) { + userLeft((UserLeft) message); + } else if (message instanceof UserStatusChanged) { + updatedStatus((UserStatusChanged) message); + } else if (message instanceof UserJoinedVoice) { + userJoinedVoice((UserJoinedVoice) message); + } else if (message instanceof UserLeftVoice) { + userLeftVoice((UserLeftVoice) message); + } else if (message instanceof UserListeningOnly) { + userListeningOnly((UserListeningOnly) message); + } else if (message instanceof UserSharedWebcam) { + userSharedWebcam((UserSharedWebcam) message); + } else if (message instanceof UserUnsharedWebcam) { + userUnsharedWebcam((UserUnsharedWebcam) message); + } else if (message instanceof RemoveExpiredMeetings) { + checkAndRemoveExpiredMeetings(); + } else if (message instanceof CreateMeeting) { + processCreateMeeting((CreateMeeting) message); + } else if (message instanceof EndMeeting) { + processEndMeeting((EndMeeting) message); + } else if (message instanceof RegisterUser) { + processRegisterUser((RegisterUser) message); + } + } + }; + + runExec.execute(task); + } + + @Override + public void handle(IMessage message) { + receivedMessages.add(message); + } + + public void start() { + log.info("Starting Meeting Service."); + try { + processMessage = true; + Runnable messageReceiver = new Runnable() { + public void run() { + while (processMessage) { + try { + IMessage msg = receivedMessages.take(); + processMessage(msg); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + log.error("Handling unexpected exception [{}]", + e.toString()); + } + } + } + }; + + msgProcessorExec.execute(messageReceiver); + } catch (Exception e) { + log.error("Error PRocessing Message"); + } + } + + public void stop() { + processMessage = false; + cleaner.stop(); + } + + public void setDefaultMeetingCreateJoinDuration(int expiration) { + this.defaultMeetingCreateJoinDuration = expiration; + } + + public void setDefaultMeetingExpireDuration(int meetingExpiration) { + this.defaultMeetingExpireDuration = meetingExpiration; + } + + public void setRecordingService(RecordingService s) { + recordingService = s; + } + + public void setMessagingService(MessagingService mess) { + messagingService = mess; + } + + public void setExpiredMeetingCleanupTimerTask( + ExpiredMeetingCleanupTimerTask c) { + cleaner = c; + cleaner.setMeetingService(this); + cleaner.start(); + } + + public void setRemoveMeetingWhenEnded(boolean s) { + removeMeetingWhenEnded = s; + } } diff --git a/bigbluebutton-web/src/java/org/bigbluebutton/api/RecordingService.java b/bigbluebutton-web/src/java/org/bigbluebutton/api/RecordingService.java index 15fad0201c..48bcbf06d4 100755 --- a/bigbluebutton-web/src/java/org/bigbluebutton/api/RecordingService.java +++ b/bigbluebutton-web/src/java/org/bigbluebutton/api/RecordingService.java @@ -1,21 +1,21 @@ /** -* BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ -* -* Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). -* -* This program is free software; you can redistribute it and/or modify it under the -* terms of the GNU Lesser General Public License as published by the Free Software -* Foundation; either version 3.0 of the License, or (at your option) any later -* version. -* -* BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY -* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A -* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. -* -* You should have received a copy of the GNU Lesser General Public License along -* with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. -* -*/ + * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ + * + * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). + * + * This program is free software; you can redistribute it and/or modify it under the + * terms of the GNU Lesser General Public License as published by the Free Software + * Foundation; either version 3.0 of the License, or (at your option) any later + * version. + * + * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. + * + */ package org.bigbluebutton.api; @@ -40,284 +40,310 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecordingService { - private static Logger log = LoggerFactory.getLogger(RecordingService.class); - - private String publishedDir = "/var/bigbluebutton/published"; - private String unpublishedDir = "/var/bigbluebutton/unpublished"; - private RecordingServiceHelper recordingServiceHelper; - private String recordStatusDir; - - public void startIngestAndProcessing(String meetingId) { - String done = recordStatusDir + "/" + meetingId + ".done"; - - File doneFile = new File(done); - if (!doneFile.exists()) { - try { - doneFile.createNewFile(); - if (!doneFile.exists()) - log.error("Failed to create " + done + " file."); - } catch (IOException e) { - log.error("Failed to create " + done + " file."); - } - } else { - log.error(done + " file already exists."); - } - } - - public ArrayList<Recording> getRecordings(ArrayList<String> meetingIds) { - ArrayList<Recording> recs = new ArrayList<Recording>(); - - List<File> allPublishedDirectories = new ArrayList<File>(); - String[] publishedFormats = getPlaybackFormats(publishedDir); - for (int i = 0; i < publishedFormats.length; ++i) { - allPublishedDirectories.addAll(getDirectories(publishedDir + File.separatorChar + publishedFormats[i])); - } - - List<File> allUnpublishedDirectories = new ArrayList<File>(); - String[] unpublishedFormats = getPlaybackFormats(unpublishedDir); - for (int i = 0; i < unpublishedFormats.length; ++i) { - allUnpublishedDirectories.addAll(getDirectories(unpublishedDir + File.separatorChar + unpublishedFormats[i])); - } - - if(meetingIds.isEmpty()){ - meetingIds.addAll(getAllRecordingIds(allPublishedDirectories)); - meetingIds.addAll(getAllRecordingIds(allUnpublishedDirectories)); - } - - log.debug("got all recording ids"); - - for(String meetingId : meetingIds){ - List<Recording> published = getRecordingsForPath(meetingId, allPublishedDirectories); - if (!published.isEmpty()) { - recs.addAll(published); - } - - List<Recording> unpublished = getRecordingsForPath(meetingId, allUnpublishedDirectories); - if (!unpublished.isEmpty()) { - recs.addAll(unpublished); - } - } - - return recs; - } - - public boolean recordingMatchesMetadata(Recording recording, Map<String, String> metadataFilters) { - for (Map.Entry<String, String> filter : metadataFilters.entrySet()) { - String metadataValue = recording.getMetadata().get(filter.getKey()); - if (metadataValue != null && metadataValue.equals(filter.getValue())) { - // the recording has the metadata specified - // AND the value is the same as the filter - } else { - return false; - } - } - return true; - } - - public Map<String, Recording> filterRecordingsByMetadata(Map<String, Recording> recordings, Map<String, String> metadataFilters) { - Map<String, Recording> resultRecordings = new HashMap<String, Recording>(); - for (Map.Entry<String, Recording> entry : recordings.entrySet()) { - if (recordingMatchesMetadata(entry.getValue(), metadataFilters)) - resultRecordings.put(entry.getKey(), entry.getValue()); - } - return resultRecordings; - } - - public boolean existAnyRecording(List<String> idList){ - List<String> publishList=getAllRecordingIds(publishedDir); - List<String> unpublishList=getAllRecordingIds(unpublishedDir); - - for(String id:idList){ - if(publishList.contains(id)||unpublishList.contains(id)){ - return true; - } - } - return false; - } - - private List<String> getAllRecordingIds(String path){ - String[] format = getPlaybackFormats(path); - - return getAllRecordingIds(path, format); - } - - private List<String> getAllRecordingIds(String path, String[] format) { - List<String> ids=new ArrayList<String>(); - - for (int i = 0; i < format.length; i++) { - List<File> recordings = getDirectories(path + File.separatorChar + format[i]); - for (int f = 0; f < recordings.size(); f++) { - if(!ids.contains(recordings.get(f).getName())) - ids.add(recordings.get(f).getName()); - } - } - return ids; - } - - private Set<String> getAllRecordingIds(List<File> recs) { - Set<String> ids=new HashSet<String>(); - - Iterator<File> iterator = recs.iterator(); - while (iterator.hasNext()) { - ids.add(iterator.next().getName()); - } - return ids; - } - - private List<Recording> getRecordingsForPath(String meetingId, String path) { - List<Recording> recs = new ArrayList<Recording>(); - - String[] format = getPlaybackFormats(path); - for (int i = 0; i < format.length; i++) { - List<File> recordings = getDirectories(path + File.separatorChar + format[i]); - for (int f = 0; f < recordings.size(); f++) { - if (recordings.get(f).getName().startsWith(meetingId)) { - Recording r = getRecordingInfo(path, recordings.get(f).getName(), format[i]); - if (r != null) recs.add(r); - } - } - } - return recs; - } - - private List<Recording> getRecordingsForPath(String meetingId, List<File> recordings) { - List<Recording> recs = new ArrayList<Recording>(); - - Iterator<File> iterator = recordings.iterator(); - while (iterator.hasNext()) { - File recording = iterator.next(); - if (recording.getName().startsWith(meetingId)) { - Recording r = getRecordingInfo(recording); - if (r != null) recs.add(r); - } - } - return recs; - } - - public Recording getRecordingInfo(String recordingId, String format) { - return getRecordingInfo(publishedDir, recordingId, format); - } - - private Recording getRecordingInfo(String path, String recordingId, String format) { - Recording rec = recordingServiceHelper.getRecordingInfo(recordingId, path, format); - return rec; - } - - private Recording getRecordingInfo(File dir) { - Recording rec = recordingServiceHelper.getRecordingInfo(dir); - return rec; - } - - public void publish(String recordingId, boolean publish) { - if(publish) - publish(unpublishedDir, recordingId, publish); - else - publish(publishedDir, recordingId, publish); - } - - private void publish(String path, String recordingId, boolean publish) { - String[] format = getPlaybackFormats(path); - for (int i = 0; i < format.length; i++) { - List<File> recordings = getDirectories(path + File.separatorChar + format[i]); - for (int f = 0; f < recordings.size(); f++) { - File recording = recordings.get(f); - if (recording.getName().equalsIgnoreCase(recordingId)) { - Recording r = getRecordingInfo(path, recordingId, format[i]); - if (r != null) { - File dest; - if (publish) { - dest = new File(publishedDir+ File.separatorChar + format[i]); - } else { - dest = new File(unpublishedDir+ File.separatorChar + format[i]); - } - if(!dest.exists()) dest.mkdir(); - boolean moved = recording.renameTo(new File(dest, recording.getName())); - if (moved) { - log.debug("Recording successfully moved!"); - r.setPublished(publish); - recordingServiceHelper.writeRecordingInfo(dest.getAbsolutePath() + File.separatorChar + recording.getName(), r); - } - } - } - } - } - } - - public void delete(String recordingId) { - deleteRecording(recordingId, publishedDir); - deleteRecording(recordingId, unpublishedDir); - } - - private void deleteRecording(String id, String path) { - String[] format = getPlaybackFormats(path); - for (int i = 0; i < format.length; i++) { - List<File> recordings = getDirectories(path + File.separatorChar + format[i]); - for (int f = 0; f < recordings.size(); f++) { - if (recordings.get(f).getName().equals(id)) { - deleteDirectory(recordings.get(f)); - } - } - } - } - - private void deleteDirectory(File directory) { - /** - * Go through each directory and check if it's not empty. - * We need to delete files inside a directory before a - * directory can be deleted. - **/ - File[] files = directory.listFiles(); - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - deleteDirectory(files[i]); - } else { - files[i].delete(); - } - } - // Now that the directory is empty. Delete it. - directory.delete(); - } - - private List<File> getDirectories(String path) { - // Collection<File> files = FileUtils.listFilesAndDirs(new File(path), new NotFileFilter(TrueFileFilter.INSTANCE), DirectoryFileFilter.DIRECTORY); - log.debug("getting directories for {}", path); - List<File> files = new ArrayList<File>(); - try { - DirectoryStream<Path> stream = Files.newDirectoryStream(FileSystems.getDefault().getPath(path)); - Iterator<Path> iter = stream.iterator(); - while (iter.hasNext()) { - Path next = iter.next(); - files.add(next.toFile()); - } - } catch (IOException e) { - e.printStackTrace(); - } - return files; - } - - private String[] getPlaybackFormats(String path) { - List<File> dirs = getDirectories(path); - String[] formats = new String[dirs.size()]; - - for (int i = 0; i < dirs.size(); i++) { - formats[i] = dirs.get(i).getName(); - } - return formats; - } - - public void setRecordingStatusDir(String dir) { - recordStatusDir = dir; - } - - public void setUnpublishedDir(String dir) { - unpublishedDir = dir; - } - - public void setPublishedDir(String dir) { - publishedDir = dir; - } - - public void setRecordingServiceHelper(RecordingServiceHelper r) { - recordingServiceHelper = r; - } + private static Logger log = LoggerFactory.getLogger(RecordingService.class); + + private String publishedDir = "/var/bigbluebutton/published"; + private String unpublishedDir = "/var/bigbluebutton/unpublished"; + private RecordingServiceHelper recordingServiceHelper; + private String recordStatusDir; + + public void startIngestAndProcessing(String meetingId) { + String done = recordStatusDir + "/" + meetingId + ".done"; + + File doneFile = new File(done); + if (!doneFile.exists()) { + try { + doneFile.createNewFile(); + if (!doneFile.exists()) + log.error("Failed to create " + done + " file."); + } catch (IOException e) { + log.error("Failed to create " + done + " file."); + } + } else { + log.error(done + " file already exists."); + } + } + + public ArrayList<Recording> getRecordings(ArrayList<String> meetingIds) { + ArrayList<Recording> recs = new ArrayList<Recording>(); + + List<File> allPublishedDirectories = new ArrayList<File>(); + String[] publishedFormats = getPlaybackFormats(publishedDir); + for (int i = 0; i < publishedFormats.length; ++i) { + allPublishedDirectories.addAll(getDirectories(publishedDir + + File.separatorChar + publishedFormats[i])); + } + + List<File> allUnpublishedDirectories = new ArrayList<File>(); + String[] unpublishedFormats = getPlaybackFormats(unpublishedDir); + for (int i = 0; i < unpublishedFormats.length; ++i) { + allUnpublishedDirectories.addAll(getDirectories(unpublishedDir + + File.separatorChar + unpublishedFormats[i])); + } + + if (meetingIds.isEmpty()) { + meetingIds.addAll(getAllRecordingIds(allPublishedDirectories)); + meetingIds.addAll(getAllRecordingIds(allUnpublishedDirectories)); + } + + log.debug("got all recording ids"); + + for (String meetingId : meetingIds) { + List<Recording> published = getRecordingsForPath(meetingId, + allPublishedDirectories); + if (!published.isEmpty()) { + recs.addAll(published); + } + + List<Recording> unpublished = getRecordingsForPath(meetingId, + allUnpublishedDirectories); + if (!unpublished.isEmpty()) { + recs.addAll(unpublished); + } + } + + return recs; + } + + public boolean recordingMatchesMetadata(Recording recording, + Map<String, String> metadataFilters) { + for (Map.Entry<String, String> filter : metadataFilters.entrySet()) { + String metadataValue = recording.getMetadata().get(filter.getKey()); + if (metadataValue != null + && metadataValue.equals(filter.getValue())) { + // the recording has the metadata specified + // AND the value is the same as the filter + } else { + return false; + } + } + return true; + } + + public Map<String, Recording> filterRecordingsByMetadata( + Map<String, Recording> recordings, + Map<String, String> metadataFilters) { + Map<String, Recording> resultRecordings = new HashMap<String, Recording>(); + for (Map.Entry<String, Recording> entry : recordings.entrySet()) { + if (recordingMatchesMetadata(entry.getValue(), metadataFilters)) + resultRecordings.put(entry.getKey(), entry.getValue()); + } + return resultRecordings; + } + + public boolean existAnyRecording(List<String> idList) { + List<String> publishList = getAllRecordingIds(publishedDir); + List<String> unpublishList = getAllRecordingIds(unpublishedDir); + + for (String id : idList) { + if (publishList.contains(id) || unpublishList.contains(id)) { + return true; + } + } + return false; + } + + private List<String> getAllRecordingIds(String path) { + String[] format = getPlaybackFormats(path); + + return getAllRecordingIds(path, format); + } + + private List<String> getAllRecordingIds(String path, String[] format) { + List<String> ids = new ArrayList<String>(); + + for (int i = 0; i < format.length; i++) { + List<File> recordings = getDirectories(path + File.separatorChar + + format[i]); + for (int f = 0; f < recordings.size(); f++) { + if (!ids.contains(recordings.get(f).getName())) + ids.add(recordings.get(f).getName()); + } + } + return ids; + } + + private Set<String> getAllRecordingIds(List<File> recs) { + Set<String> ids = new HashSet<String>(); + + Iterator<File> iterator = recs.iterator(); + while (iterator.hasNext()) { + ids.add(iterator.next().getName()); + } + return ids; + } + + private List<Recording> getRecordingsForPath(String meetingId, String path) { + List<Recording> recs = new ArrayList<Recording>(); + + String[] format = getPlaybackFormats(path); + for (int i = 0; i < format.length; i++) { + List<File> recordings = getDirectories(path + File.separatorChar + + format[i]); + for (int f = 0; f < recordings.size(); f++) { + if (recordings.get(f).getName().startsWith(meetingId)) { + Recording r = getRecordingInfo(path, recordings.get(f) + .getName(), format[i]); + if (r != null) + recs.add(r); + } + } + } + return recs; + } + + private List<Recording> getRecordingsForPath(String meetingId, + List<File> recordings) { + List<Recording> recs = new ArrayList<Recording>(); + + Iterator<File> iterator = recordings.iterator(); + while (iterator.hasNext()) { + File recording = iterator.next(); + if (recording.getName().startsWith(meetingId)) { + Recording r = getRecordingInfo(recording); + if (r != null) + recs.add(r); + } + } + return recs; + } + + public Recording getRecordingInfo(String recordingId, String format) { + return getRecordingInfo(publishedDir, recordingId, format); + } + + private Recording getRecordingInfo(String path, String recordingId, + String format) { + Recording rec = recordingServiceHelper.getRecordingInfo(recordingId, + path, format); + return rec; + } + + private Recording getRecordingInfo(File dir) { + Recording rec = recordingServiceHelper.getRecordingInfo(dir); + return rec; + } + + public void publish(String recordingId, boolean publish) { + if (publish) + publish(unpublishedDir, recordingId, publish); + else + publish(publishedDir, recordingId, publish); + } + + private void publish(String path, String recordingId, boolean publish) { + String[] format = getPlaybackFormats(path); + for (int i = 0; i < format.length; i++) { + List<File> recordings = getDirectories(path + File.separatorChar + + format[i]); + for (int f = 0; f < recordings.size(); f++) { + File recording = recordings.get(f); + if (recording.getName().equalsIgnoreCase(recordingId)) { + Recording r = getRecordingInfo(path, recordingId, format[i]); + if (r != null) { + File dest; + if (publish) { + dest = new File(publishedDir + File.separatorChar + + format[i]); + } else { + dest = new File(unpublishedDir + File.separatorChar + + format[i]); + } + if (!dest.exists()) + dest.mkdir(); + boolean moved = recording.renameTo(new File(dest, + recording.getName())); + if (moved) { + log.debug("Recording successfully moved!"); + r.setPublished(publish); + recordingServiceHelper.writeRecordingInfo( + dest.getAbsolutePath() + File.separatorChar + + recording.getName(), r); + } + } + } + } + } + } + + public void delete(String recordingId) { + deleteRecording(recordingId, publishedDir); + deleteRecording(recordingId, unpublishedDir); + } + + private void deleteRecording(String id, String path) { + String[] format = getPlaybackFormats(path); + for (int i = 0; i < format.length; i++) { + List<File> recordings = getDirectories(path + File.separatorChar + + format[i]); + for (int f = 0; f < recordings.size(); f++) { + if (recordings.get(f).getName().equals(id)) { + deleteDirectory(recordings.get(f)); + } + } + } + } + + private void deleteDirectory(File directory) { + /** + * Go through each directory and check if it's not empty. We need to + * delete files inside a directory before a directory can be deleted. + **/ + File[] files = directory.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteDirectory(files[i]); + } else { + files[i].delete(); + } + } + // Now that the directory is empty. Delete it. + directory.delete(); + } + + private List<File> getDirectories(String path) { + // Collection<File> files = FileUtils.listFilesAndDirs(new File(path), + // new NotFileFilter(TrueFileFilter.INSTANCE), + // DirectoryFileFilter.DIRECTORY); + log.debug("getting directories for {}", path); + List<File> files = new ArrayList<File>(); + try { + DirectoryStream<Path> stream = Files.newDirectoryStream(FileSystems + .getDefault().getPath(path)); + Iterator<Path> iter = stream.iterator(); + while (iter.hasNext()) { + Path next = iter.next(); + files.add(next.toFile()); + } + } catch (IOException e) { + e.printStackTrace(); + } + return files; + } + + private String[] getPlaybackFormats(String path) { + List<File> dirs = getDirectories(path); + String[] formats = new String[dirs.size()]; + + for (int i = 0; i < dirs.size(); i++) { + formats[i] = dirs.get(i).getName(); + } + return formats; + } + + public void setRecordingStatusDir(String dir) { + recordStatusDir = dir; + } + + public void setUnpublishedDir(String dir) { + unpublishedDir = dir; + } + + public void setPublishedDir(String dir) { + publishedDir = dir; + } + + public void setRecordingServiceHelper(RecordingServiceHelper r) { + recordingServiceHelper = r; + } } -- GitLab