package org.netevolved.twilio; import java.net.URI; import java.util.ArrayList; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.entermediadb.asset.Asset; import org.entermediadb.asset.MediaArchive; import org.ijsolutions.testbench.TestBench; import org.json.simple.JSONObject; import org.openedit.CatalogEnabled; import org.openedit.Data; import org.openedit.ModuleManager; import org.openedit.WebPageRequest; import org.openedit.users.User; import com.twilio.Twilio; import com.twilio.base.ResourceSet; import com.twilio.jwt.accesstoken.AccessToken; import com.twilio.jwt.accesstoken.VideoGrant; import com.twilio.rest.api.v2010.account.Call; import com.twilio.rest.api.v2010.account.Conference; import com.twilio.rest.api.v2010.account.Conference.Status; import com.twilio.rest.video.v1.Room; import com.twilio.rest.video.v1.room.Participant; import com.twilio.type.PhoneNumber; public class TwilioManager implements CatalogEnabled { private static final Log log = LogFactory.getLog(TwilioManager.class); protected String fieldCatalogId; protected ModuleManager fieldModuleManager; protected boolean fieldInitialized; protected ArrayList fieldParticipants; public boolean isInitialized() { return fieldInitialized; } public void setInitialized(boolean inInitialized) { fieldInitialized = inInitialized; } public String getCatalogId() { return fieldCatalogId; } public void setCatalogId(String inCatalogId) { fieldCatalogId = inCatalogId; } public ModuleManager getModuleManager() { return fieldModuleManager; } public void setModuleManager(ModuleManager inModuleManager) { fieldModuleManager = inModuleManager; } protected TestBench getTestBench() { TestBench archive = (TestBench) getModuleManager().getBean(getCatalogId(), "testBench"); return archive; } protected String getAccountId() { return getTestBench().getSetting("twilioaccountid"); } protected String getSecret() { return getTestBench().getSetting("twiliosecret"); } protected String getKey() { return getTestBench().getSetting("twiliokey"); } // https://www.twilio.com/blog/2015/05/getting-started-with-twilio-video.html public String getRoomToken(String inUser, String inRoom, String roomtype) throws Exception { init(); Room room = null; try { room = Room.fetcher(inRoom).fetch(); } catch (Exception e) { log.info("room didn't exist"); } if (room == null) { if ("peer".equals(roomtype)) { room = Room.creator().setEnableTurn(true).setRecordParticipantsOnConnect(false) // .setStatusCallback(URI.create("http://example.org")) .setType(Room.RoomType.PEER_TO_PEER).setUniqueName(inRoom).create(); } else if ("group".equals(roomtype)) { room = Room.creator().setEnableTurn(true).setRecordParticipantsOnConnect(false) // .setStatusCallback(URI.create("http://example.org")) .setType(Room.RoomType.GROUP).setUniqueName(inRoom).create(); } else if ("smallgroup".equals(roomtype)) { room = Room.creator().setEnableTurn(true).setRecordParticipantsOnConnect(false) // .setStatusCallback(URI.create("http://example.org")) .setType(Room.RoomType.GROUP_SMALL).setUniqueName(inRoom).create(); } } // Create a VideoGrant final VideoGrant grant = new VideoGrant(); grant.setRoom(inRoom); // Create an Access Token String accountId = getAccountId(); String key = getKey(); String secret = getSecret(); AccessToken token = new AccessToken.Builder(accountId, key, secret).identity(inUser) // Set the Identity of this // token .grant(grant) // Grant access to Video .build(); // Serialize the token as a JWT String jwt = token.toJwt(); return jwt; } public String getRoomToken(User inUser, String inRoom, String roomtype) throws Exception { return getRoomToken(inUser.getId(), inRoom, roomtype); } public String getRoomToken(User inUser, String inRoom) throws Exception { // Room room = Room.creator() // .setEnableTurn(true) // //.setStatusCallback(URI.create("http://example.org")) // .setType(Room.RoomType.PEER_TO_PEER) // .setUniqueName(inRoom) // .create(); // // Create a VideoGrant final VideoGrant grant = new VideoGrant(); grant.setRoom(inRoom); // Create an Access Token String accountId = getAccountId(); String key = getKey(); String secret = getSecret(); AccessToken token = new AccessToken.Builder(accountId, key, secret).identity(inUser.getId()) // Set the Identity // of this token .grant(grant) // Grant access to Video .build(); // Serialize the token as a JWT String jwt = token.toJwt(); return jwt; } public String getRoomToken(String inId, String inRoom) throws Exception { // Create a VideoGrant final VideoGrant grant = new VideoGrant(); grant.setRoom(inRoom); // Create an Access Token String accountId = getAccountId(); String key = getKey(); String secret = getSecret(); AccessToken token = new AccessToken.Builder(accountId, key, secret).identity(inId) // Set the Identity of this // token .grant(grant) // Grant access to Video .build(); // Serialize the token as a JWT String jwt = token.toJwt(); return jwt; } public void init() { String key = getKey(); String secret = getSecret(); Twilio.init(key, secret); } public JSONObject getRoomStatus(TestBench inBench, String inRoomid) { init(); // Room room = Room.fetcher(inRoomid).fetch(); JSONObject roominfo = new JSONObject(); MediaArchive archive = inBench.getMediaArchive(); ResourceSet participants = Participant.reader(inRoomid).setStatus(Participant.Status.CONNECTED) .read(); for (Iterator iterator = participants.iterator(); iterator.hasNext();) { JSONObject userinfo = new JSONObject(); Participant participant = (Participant) iterator.next(); String id = participant.getIdentity(); User user = getTestBench().getUserManager().getUser(id); log.info("Found user:" + user); userinfo.put("userid", id); userinfo.put("name", user.getScreenName()); Asset asset = archive.getAssetBySourcePath("profiles/" + user.getId() + "/profilepic"); if (asset != null) { userinfo.put("profilephoto", asset.getId()); userinfo.put("profilesourcepath", asset.getSourcePath()); } roominfo.put(id, userinfo); } return roominfo; } public void closeRoom(String inRoomId) { init(); Room room = null; try { room = Room.fetcher(inRoomId).fetch(); } catch (Exception e) { log.info("room didn't exist"); return; } Room.updater(inRoomId, Room.RoomStatus.COMPLETED).update(); } public void makeCall() throws Exception { Twilio.init("AC8c64bbf35a22f949c611c1a4a7ae95e9", "409cb196dc812a62a7952e830afaa07e"); String from = "+17053151000"; String to = "+15193871007"; Call call = Call .creator(new PhoneNumber(to), new PhoneNumber(from), new URI("https://oneliveweb.com/twiliotest.xml")) .create(); System.out.println(call.getSid()); } public void handleIncomingCall(WebPageRequest inReq) { // https://stackoverflow.com/questions/28621852/with-twilio-is-it-possible-to-receive-user-input-during-a-conference-call String code = inReq.findValue("Digits"); log.info(code); log.info(inReq.getRequestParameter("From")); log.info(inReq.getRequestParameter("CallSid")); CallParticipant participant = loadCallParticipant(inReq); muteCallParticipant(participant); // // // example // // // // String message = // "You are about to join the Rapid Response conference." + "Press 1 to join as a listener." // + "Press 2 to join as a speaker." + "Press 3 to join as the moderator."; // // Say sayMessage = new Say.Builder(message).build(); // Gather gather = new Gather.Builder() // .action("/conference/connect") // .method(Method.POST) // .say(sayMessage) // .build(); // // VoiceResponse voiceResponse = new VoiceResponse.Builder().gather(gather).build(); // // // // Render TwiML as XML // inReq.getResponse().setContentType("text/xml"); // // try { // String xml = twiml.toXml(); // inReq.putPageValue("xml", xml); // } catch (TwiMLException e) { // e.printStackTrace(); // } } public ArrayList getParticipants() { if (fieldParticipants == null) { fieldParticipants = new ArrayList(); } return fieldParticipants; } public void setParticipants(ArrayList inParticipants) { fieldParticipants = inParticipants; } public CallParticipant loadCallParticipant(WebPageRequest inReq) { String from = inReq.getRequestParameter("From"); String callSid = inReq.getRequestParameter("CallSid"); CallParticipant participant = null; for (Iterator iterator = getParticipants().iterator(); iterator.hasNext();) { CallParticipant callParticipant = (CallParticipant) iterator.next(); if (callSid.equals(callParticipant.getCallSid())) { participant = callParticipant; } } if (participant == null) { log.info("creating new participant for " + callSid); participant = new CallParticipant(); getParticipants().add(participant); } participant.setCallSid(callSid); if (participant.getUser() == null) { if (from != null) { // User user = getTestBench().getUserByPhone("phone", from); User user = null; if (user != null) { participant.setUser(user); } } } String planid = inReq.findValue("planid"); if (planid != null) { participant.setProperty("planid", planid); } String classid = inReq.findValue("classid"); if (classid != null) { participant.setProperty("classid", classid); } inReq.putPageValue("callparticipant", participant); return participant; } public String findConferenceSid(String inId) { Twilio.init("AC8c64bbf35a22f949c611c1a4a7ae95e9", "409cb196dc812a62a7952e830afaa07e"); ResourceSet conferences = Conference.reader().setFriendlyName("example").setStatus(Status.IN_PROGRESS).limit(20).read(); for (Conference record : conferences) { String sid = record.getSid(); return sid; } return null; } public void authenticatePhone(WebPageRequest inReq) { String from = inReq.getRequestParameter("From"); String callSid = inReq.getRequestParameter("CallSid"); CallParticipant participant = loadCallParticipant(inReq); String code = inReq.findValue("Digits"); log.info(code); TestBench bench = getTestBench(); String lg = inReq.findValue("classid"); Data participantprofile = bench.getMediaArchive().query("studentclasses").exact("learninggroup", lg) .exact("dialincode", code).searchOne(); if (participantprofile != null) { User user = bench.getUserManager().getUser(participantprofile.get("userprofile")); participant.setUser(user); log.info("found participant: " + user); } else { log.info("No participant found"); } inReq.putPageValue("callparticipant", participant); } public void muteCallParticipant(CallParticipant inParticipant) { try { Twilio.init("AC8c64bbf35a22f949c611c1a4a7ae95e9", "409cb196dc812a62a7952e830afaa07e"); com.twilio.rest.api.v2010.account.conference.Participant part = com.twilio.rest.api.v2010.account.conference.Participant .updater(findConferenceSid(inParticipant.getCallSid()), inParticipant.getCallSid()).setMuted(true) .update(); inParticipant.setMuted(true); } catch (Exception e) { log.info("Could not mute user: " + inParticipant.getUser()); } } public void hangUp(CallParticipant inParticipant) { com.twilio.rest.api.v2010.account.conference.Participant .deleter(findConferenceSid(inParticipant.getCallSid()), inParticipant.getCallSid()).delete(); } public void unmuteCallParticipant(CallParticipant inParticipant) { try { com.twilio.rest.api.v2010.account.conference.Participant part = com.twilio.rest.api.v2010.account.conference.Participant .updater(findConferenceSid(inParticipant.getCallSid()), inParticipant.getCallSid()).setMuted(false) .update(); inParticipant.setMuted(false); } catch (Exception e) { log.info("Could not mute user: " + inParticipant.getUser()); } } public void muteCallParticipant(String inUserId) { CallParticipant participant = getCallParticipant(inUserId); if (participant != null) { muteCallParticipant(participant); } } public void unmuteCallParticipant(String inUserId) { CallParticipant participant = getCallParticipant(inUserId); if (participant != null) { unmuteCallParticipant(participant); } } public void muteCallParticipants() { for (Iterator iterator = getParticipants().iterator(); iterator.hasNext();) { CallParticipant callParticipant = (CallParticipant) iterator.next(); muteCallParticipant(callParticipant); } } public void unmuteCallParticipants() { for (Iterator iterator = getParticipants().iterator(); iterator.hasNext();) { CallParticipant callParticipant = (CallParticipant) iterator.next(); unmuteCallParticipant(callParticipant); } } public CallParticipant getCallParticipant(String inUserId) { for (Iterator iterator = getParticipants().iterator(); iterator.hasNext();) { CallParticipant callParticipant = (CallParticipant) iterator.next(); if (callParticipant.getUser() != null && callParticipant.getUser().getId().equals(inUserId)) { return callParticipant; } } return null; } public boolean isUserConnected(String inUserid) { CallParticipant participant = getCallParticipant(inUserid); return participant != null; } public boolean isMuted(String inId) { CallParticipant callParticipant = getCallParticipant(inId); if (callParticipant == null) { return false; } return callParticipant.isMuted(); } }