package server; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import models.Configuration; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.apache.thrift.TException; import org.openslx.imagemaster.thrift.iface.UserInfo; import org.openslx.sat.thrift.iface.Image; import org.openslx.sat.thrift.iface.Lecture; import org.openslx.sat.thrift.iface.Person; import org.openslx.sat.thrift.iface.Server; import org.openslx.sat.thrift.iface.TUploadFinishException; import org.openslx.sat.thrift.iface.TUploadRejectedException; import org.openslx.sat.thrift.iface.TransferInformation; import org.openslx.sat.thrift.version.Version; import sql.SQL; import util.Constants; import util.FileSystem; import util.Formatter; import fileserv.ActiveUpload; import fileserv.FileServer; public class ServerHandler implements Server.Iface { private static final Logger log = Logger.getLogger(ServerHandler.class); private static final SQL sql = new SQL(); private static final FileServer fileServer = FileServer.instance(); @Override public String finishImageUpload(String imageName, String description, boolean license, boolean internet, long shareMode, String os, String uploadToken) throws TException { ActiveUpload upload = fileServer.getUploadByToken(uploadToken); if (upload == null) { log.warn("A client called finishImageUpload, but the given token is unknown"); throw new TUploadFinishException("Your upload token is invalid"); } if (!upload.isComplete()) { log.warn("A client called finishImageUpload for an upload that is still running"); throw new TUploadFinishException("Cannot finish upload: Still in progress..."); } // We need an owner for the upload to handle it properly UserInfo user = upload.getOwner(); if (user == null) { log.warn("A client called finishImageUpload, the uploadToken was valid, but the upload doesn't have an owner"); throw new TUploadFinishException("Your upload doesn't have an owner. (This should not happen!)"); } // We also need a temp file File file = upload.getDestinationFile(); if (file == null || !file.getName().endsWith(Constants.INCOMPLETE_UPLOAD_SUFFIX)) { log.warn("A client called finishImageUpload, but there is no temp file involved or it has the wrong extension (" + file + ")"); throw new TUploadFinishException("Your upload doesn't have a matching temp file on the server."); } // Ready to go. First step: Rename temp file to something usable File destination = new File(file.getParent(), Formatter.vmName(user, imageName)); // Sanity check: destination should be a sub directory of the vmStorePath String relPath = FileSystem.getRelativePath(destination, Configuration.getVmStoreBasePath()); if (relPath == null) { log.warn(destination.getAbsolutePath() + " is not a subdir of " + Configuration.getVmStoreBasePath().getAbsolutePath()); throw new TUploadFinishException( "Your file lies outside of the vm store directory (This is a server side issue)."); } // Execute rename boolean ret = false; Exception renameException = null; try { ret = file.renameTo(destination); } catch (Exception e) { ret = false; renameException = e; } if (!ret) { // Rename failed :-( log.warn("Could not rename '" + file.getAbsolutePath() + "' to '" + destination.getAbsolutePath() + "'", renameException); } // Now insert meta data into DB final String imageUuid = UUID.randomUUID().toString(); final String mode; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } // OS impl Select and write // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden: // 'Windows 7 32 bit" // TODO: Might be the biggest mess around here. We should define OS types on the // master server in the future and have them synced to the satellite. String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", "")); ret = sql.writeNewImageData(user.userId, license, internet, imageName, description, relPath, upload.getSize(), mode, pk_os, imageUuid); if (!ret) throw new TUploadFinishException( "Image uploaded successfully, but could not be inserted into data base."); return imageUuid; } @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionWrite(String userID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageListPermissionWrite(ui.getUserId()); } return null; } @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionRead(String userID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageListPermissionRead(ui.getUserId()); } return null; } @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionLink(String userID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageListPermissionLink(ui.getUserId()); } return null; } @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionAdmin(String userID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageListPermissionAdmin(ui.getUserId()); } return null; } @Override public List getImageListAllTemplates(String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageListAllTemplates(); } return null; } @Override public List getAllOS(String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getAllOS(); } return null; } // UserInfo does not return the institution, so in this case, the local // method is prepared, but not yet executed, as the institution has to be // added to UserInfo (or selected by institutionID) // TODO: What is this even supposed to do? // institutionID is a member of UserInfo, and the master server // implements a method called getOrganizations, so you can map the ID to a // name.... !? Also why the hell is this using a map instead of a class? @Override public Map getPersonData(String Vorname, String Nachname, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { Map map = new HashMap<>(); map.put("mail", ui.getEMail()); map.put("Nachname", ui.getLastName()); map.put("Vorname", ui.getFirstName()); Map tempMap = new HashMap<>(); tempMap = sql.getPersonData(Vorname, Nachname); map.put("Hochschule", tempMap.get("Hochschule")); return map; } return null; } @Override public void setPerson(String userID, String token, String institution) throws TException { // TODO: Again, what's going on with institution as a parameter here? It's part of the UserInfo... UserInfo ui = SessionManager.get(token); if (ui != null) { sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), institution); } } @Override public boolean writeLecturedata(String name, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageID, String token, String Tel, String Fak, String lectureID, String university) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // TODO: Check if the user has the permissions to set this lecture's meta data... Map map = new HashMap(); int imageversion = 0; String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(ui.getEMail(), ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); map = sql.getImageIDandVersion(imageID); // pk_image = map.get("GUID"); imageversion = Integer.parseInt(map.get("version")); sql.setLectureData(pk_person, imageID, imageversion, name, desc, shortdesc, startDate, endDate, isActive, lectureID); } return false; } @Override public Map getImageData(String imageid, String imageversion, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageData(imageid, imageversion); } return null; } @Override public boolean updateImageData(String userToken, String imageId, String newName, String desc, boolean license, boolean internet, long shareMode, String os) throws TException { UserInfo ui = SessionManager.get(userToken); if (ui != null) { final String mode; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", "")); // do database update - if successful then delete old file from // drive return sql.updateImageData(newName, desc, license, internet, imageId, mode, pk_os); } return false; } @Override public List getLectureList(String token) throws TException { if (authenticated(token)) { // log.info("returning LectureList"); return sql.getLectureList(); } return null; } @Override public List getLectureListPermissionRead(String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // log.info("returning LectureListRead"); return sql.getLectureListPermissionRead(ui.getUserId()); } return null; }// end getLectureListPermissionRead @Override public List getLectureListPermissionWrite(String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // log.info("returning LectureListWrite"); return sql.getLectureListPermissionWrite(ui.getUserId()); } return null; }// end getLectureListPermissionRead @Override public List getLectureListPermissionAdmin(String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // log.info("returning LectureListAdmin"); return sql.getLectureListPermissionAdmin(ui.getUserId()); } return null; }// end getLectureListPermissionRead @Override public boolean updateLecturedata(String name, String newName, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageid, String imageversion, String token, String Tel, String Fak, String id, String university) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { sql.updateLectureData(imageid, imageversion, ui.getLastName(), newName, desc, shortdesc, startDate, endDate, isActive, id); } return false; } @Override public boolean deleteImage(String imageId, String imageVersion, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui == null) return false; // TODO: Has user permissions to delete this file? String stringFile = sql.getFile(imageId, imageVersion); if (stringFile == null) return false; log.info("File to Delete: " + stringFile); if (sql.deleteImage(imageId, imageVersion)) { log.info("Image '" + imageId + "' and permissions successfully deleted."); } File tmpFile = new File(Configuration.getVmStoreBasePath(), stringFile); try { log.info("Absolute Path used for deletion: " + tmpFile.getCanonicalPath()); } catch (IOException e1) { } if (tmpFile.isFile()) { log.warn(".... file does not exist!"); } else { try { // File wird von Server gelöscht FileUtils.forceDelete(tmpFile); } catch (IOException e) { log.info("Failed to execute deleteImage.", e); } } return true; } @Override public boolean connectedToLecture(String id, String version, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // TODO: Permissions return sql.connectedToLecture(id, version); } return true; } @Override public boolean deleteLecture(String id, String token) throws TException { boolean success = false; UserInfo ui = SessionManager.get(token); if (ui != null) { // TODO: Permissions if (sql.deleteLecture(id) == true) { success = true; log.info("Lecture '" + id + "' and permissions successfully deleted."); } } return success; } @Override public List getAllUniversities(String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // TODO: Sync with list from master server (.getOrganizations() - call every now and then and add to local DB) return sql.getAllUniversities(); } return null; } @Override public Map getLectureData(String lectureid, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getLectureData(lectureid); } return null; } public static int nthIndexOf(final String string, final String searchToken, final int index) { int j = 0; for (int i = 0; i < index; i++) { j = string.indexOf(searchToken, j + 1); if (j == -1) break; } return j; } @Override public boolean checkUser(String username, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.checkUser(username); } return false; } @Override public boolean createUser(String token, String university) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { // TODO: Do not use university param... String pk_institution = sql.setInstitution(university); sql.setPerson(ui.getEMail(), ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); return true; } return false; } @Override public boolean writeImageRights(String imageID, String token, String role, String university, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { String pk_image = null; Map map = new HashMap(); String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); map = sql.getImageIDandVersion(imageID); pk_image = map.get("GUID"); if (role.equals("Dozent")) { int read = 1; int write = 1; // int changePermission=0; int admin = 1; int linkallowed = 1; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } else if (role.equals("Admin")) { int read = 1; int write = 1; // int changePermission=1; int admin = 1; int linkallowed = 1; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } else { int read = 1; int write = 0; // int changePermission=0; int admin = 0; int linkallowed = 0; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } log.info("Written image rights"); return true; } return false; } @Override public boolean writeLectureRights(String lectureID, String role, String token, String university, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); // pk_lecture = sql.getLectureID(lectureID); if (role.equals("Dozent")) { int read = 1; int write = 1; // int changePermission=0; int admin = 1; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, lectureID, roleID, read, write, admin); } else if (role.equals("Admin")) { int read = 1; int write = 1; // int changePermission=1; int admin = 1; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, lectureID, roleID, read, write, admin); } else { int read = 0; int write = 0; // int changePermission=0; int admin = 0; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, lectureID, roleID, read, write, admin); } return true; } return false; } @Override public List getAllOtherSatelliteUsers(List userID, String token) throws TException { // TODO: Like we couldn't filter the current user on the client side... UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getAllOtherSatelliteUsers(userID); // return null; } return null; } // set permissions for users which are !=userID @Override public boolean writeAdditionalImageRights(String imageID, String userID, boolean isRead, boolean isWrite, boolean isLinkAllowed, boolean isAdmin, String token) throws TException { boolean success = false; UserInfo ui = SessionManager.get(token); if (ui != null) { sql.writeAdditionalImageRights(imageID, userID, isRead, isWrite, isLinkAllowed, isAdmin); log.info("Written additional image rights for " + userID); } return success; } @Override public boolean writeAdditionalLectureRights(String lectureID, String userID, boolean isRead, boolean isWrite, boolean isAdmin, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { sql.writeAdditionalLectureRights(lectureID, userID, isRead, isWrite, isAdmin); log.info("Written additional lecture rights for " + userID); return true; } return false; } @Override public List getPermissionForUserAndImage(String token, String imageID, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getPermissionForUserAndImage(userID, imageID); } return null; } @Override public List getPermissionForUserAndLecture(String token, String lectureID, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getPermissionForUserAndLecture(userID, lectureID); } return null; } @Override public void deleteAllAdditionalImagePermissions(String imageID, String token, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { sql.deleteAllAdditionalImagePermissions(imageID, userID); } return; } @Override public void deleteAllAdditionalLecturePermissions(String lectureID, String token, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { sql.deleteAllAdditionalLecturePermissions(lectureID, userID); } return; } @Override public List getImageList(String userID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getImageList(userID); } return null; } @Override public List getAdditionalImageContacts(String imageID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getAdditionalImageContacts(imageID); } return null; } @Override public String getOsNameForGuestOs(String guestOS, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getOsNameForGuestOs(guestOS); } return null; } @Override public Map getItemOwner(String itemID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.getItemOwner(itemID); } return null; } @Override public boolean userIsImageAdmin(String imageID, String token, String userID) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.userIsImageAdmin(userID, imageID); } return false; } @Override public boolean userIsLectureAdmin(String userID, String lectureID, String token) throws TException { UserInfo ui = SessionManager.get(token); if (ui != null) { return sql.userIsLectureAdmin(userID, lectureID); } return false; } @Override public String getInstitutionByID(String institutionID) throws TException { // TODO Auto-generated method stub return "-institution-"; } @Override public long getVersion() throws TException { return Version.VERSION; } @Override public TransferInformation requestUpload(String userToken, long fileSize, List blockHashes) throws TException { UserInfo ui = SessionManager.get(userToken); if (ui == null) return null; String transferToken; try { transferToken = fileServer.createNewUserUpload(ui, fileSize, blockHashes); } catch (Exception e) { log.warn("Cannot accept upload request from user " + Formatter.userFullName(ui), e); if (e instanceof TException) throw (TException) e; throw new TUploadRejectedException(e.getMessage()); } return new TransferInformation(transferToken, fileServer.getPlainPort(), fileServer.getSslPort()); } @Override public void cancelUpload(String uploadToken) throws TException { // TODO Auto-generated method stub } @Override public TransferInformation requestDownload(String userToken, String imageId) throws TException { // TODO Auto-generated method stub return null; } @Override public void cancelDownload(String downloadToken) throws TException { // TODO Auto-generated method stub } @Override public boolean updateImageFile(String uploadToken, String imageId) throws TException { // TODO Auto-generated method stub return false; } @Override public boolean authenticated(String token) throws TException { // TODO Auto-generated method stub return false; } @Override public boolean setSessionInvalid(String token) throws TException { // TODO Auto-generated method stub return false; } }// end class