Initial import.
This commit is contained in:
parent
bce93523ca
commit
d3b4793113
308 changed files with 23679 additions and 0 deletions
106
src/zall/UploadServlet.java
Normal file
106
src/zall/UploadServlet.java
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
package zall;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
|
||||
import zall.bean.Folder;
|
||||
import zall.bean.Image;
|
||||
import zall.bean.User;
|
||||
import zall.bean.Video;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.io.file.FileUtil;
|
||||
import zutil.jee.upload.AjaxFileUpload;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
|
||||
public class UploadServlet extends AjaxFileUpload{
|
||||
private static final Logger logger = LogUtil.getLogger();
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final Set<String> VIDEO_EXT = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(new String[]{
|
||||
"avi","mp4","mpeg","mpeg","divx","xvid","wmv","mov","flv","m4v"
|
||||
})));
|
||||
|
||||
@Override
|
||||
public String getProgressHTML() {
|
||||
return ""+
|
||||
"<DIV class='comment-author vcard'>"+
|
||||
" <IMG src='img/upload.png' class='photo avatar photo' height='80' width='80'>"+
|
||||
" <SPAN class='fn n'>"+
|
||||
" <span class='status'>Unknown</span>: <span class='filename' style='font-weight: normal;'>Unknown</span> - <span class='message' style='font-weight: normal;'>Unknown</span>"+
|
||||
" <div class='progressbar'>"+
|
||||
" <b class='progress' style='width: 0%'> </b>"+
|
||||
" </div>"+
|
||||
" </SPAN>"+
|
||||
"</DIV>"+
|
||||
"<DIV class='comment-meta'>" +
|
||||
" <span class='uploaded'>0 KB</span>/ <span class='total'>0 KB</span> " +
|
||||
" - Speed: <span class='speed'>400 KB/s</span>" +
|
||||
"</DIV> ";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doUpload(HttpServletRequest request, HttpServletResponse response,
|
||||
Map<String,String> fields, List<FileItem> files) throws ServletException{
|
||||
DBConnection db = null;
|
||||
try {
|
||||
HttpSession session = request.getSession();
|
||||
db = Zallery.getDB();
|
||||
User user = (User) session.getAttribute("user");
|
||||
|
||||
// Check if user is authentication
|
||||
if(user != null){
|
||||
Folder folder = Folder.load(db, Long.parseLong( fields.get("folder") ));
|
||||
|
||||
// Handle files
|
||||
for(FileItem item : files){
|
||||
try{
|
||||
String ext = FileUtil.getFileExtension(item.getName()).toLowerCase();
|
||||
if( VIDEO_EXT.contains(ext) ){
|
||||
Video vid = new Video();
|
||||
vid.setTitle( item.getName() );
|
||||
vid.setFolder( folder );
|
||||
vid.setUser( user );
|
||||
vid.setFile( item );
|
||||
vid.save(db);
|
||||
}
|
||||
else{
|
||||
Image img = new Image();
|
||||
img.setTitle( item.getName() );
|
||||
img.setFolder( folder );
|
||||
img.setUser( user );
|
||||
img.setFile( item );
|
||||
img.save(db);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.WARNING, "Error: Creating new Media(\""+item.getName()+"\")", e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
item.delete();
|
||||
}
|
||||
response.getWriter().print("<html>OK</html>");
|
||||
}
|
||||
else
|
||||
response.getWriter().print("<html>Authentication Error</html>");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServletException(e);
|
||||
} finally{
|
||||
if(db != null) db.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
370
src/zall/Zallery.java
Normal file
370
src/zall/Zallery.java
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
package zall;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import zall.bean.Folder;
|
||||
import zall.bean.Image;
|
||||
import zall.bean.Media;
|
||||
import zall.bean.User;
|
||||
import zall.util.Email;
|
||||
import zall.util.facebook.FBUser;
|
||||
import zall.util.facebook.FacebookConnect;
|
||||
import zall.util.msg.UserMessage;
|
||||
import zall.util.msg.UserMessage.MessageType;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
public class Zallery extends HttpServlet{
|
||||
private static Logger logger = LogUtil.getLogger();
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static String WEBSITE_NAME = "Example.com";
|
||||
public static String WEBSITE_URL = "http://example.com";
|
||||
public static String THEME = "";
|
||||
public static String ROOT_PATH = "";
|
||||
public static String DATA_PATH = "";
|
||||
|
||||
/**
|
||||
* Config Options:
|
||||
* <br>- WEBSITE_NAME
|
||||
* <br>- WEBSITE_URL
|
||||
* <br>- SMTP_HOST
|
||||
* <br>- DATA_PATH
|
||||
* <br>- THEME
|
||||
* <br>- FB_APPID
|
||||
* <br>- FB_APPSEC
|
||||
*/
|
||||
public void init(ServletConfig config) throws ServletException {
|
||||
super.init(config);
|
||||
ROOT_PATH = config.getServletContext().getRealPath("/");
|
||||
if( config.getInitParameter("WEBSITE_NAME") != null )
|
||||
WEBSITE_NAME = config.getInitParameter("WEBSITE_NAME");
|
||||
if( config.getInitParameter("WEBSITE_URL") != null ){
|
||||
WEBSITE_URL = config.getInitParameter("WEBSITE_URL");
|
||||
if( WEBSITE_URL.charAt(WEBSITE_URL.length()-1) != '/')
|
||||
WEBSITE_URL += "/";
|
||||
}
|
||||
if( config.getInitParameter("SMTP_HOST") != null )
|
||||
Email.setServer( config.getInitParameter("SMTP_HOST") );
|
||||
if( config.getInitParameter("DATA_PATH") != null )
|
||||
DATA_PATH = config.getInitParameter("DATA_PATH");
|
||||
else
|
||||
throw new ServletException("Missing DATA_PATH parameter!");
|
||||
if( config.getInitParameter("THEME") != null )
|
||||
THEME = config.getInitParameter("THEME");
|
||||
if( config.getInitParameter("FB_APPID") != null &&
|
||||
config.getInitParameter("FB_APPID") != null)
|
||||
FacebookConnect.setApplicationID(
|
||||
config.getInitParameter("FB_APPID"),
|
||||
config.getInitParameter("FB_APPSEC"));
|
||||
|
||||
LogUtil.setLevel("zall", Level.FINEST);
|
||||
//LogUtil.setLevel("zutil", Level.FINEST);
|
||||
}
|
||||
|
||||
public void destroy(){
|
||||
DBBean.cancelGBC();
|
||||
}
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
|
||||
DBConnection db = null;
|
||||
try{
|
||||
doGet(request, response, db = getDB());
|
||||
} finally{
|
||||
if(db != null) db.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws ServletException{
|
||||
try{
|
||||
response.setContentType("text/html");
|
||||
HttpSession session = request.getSession();
|
||||
String page = new File(request.getRequestURI()).getName();
|
||||
request.setAttribute("page", page);
|
||||
User user = (User) session.getAttribute("user");
|
||||
FacebookConnect fbc = (FacebookConnect) session.getAttribute("facebook");
|
||||
if( fbc == null )
|
||||
fbc = FacebookConnect.getConnection( request.getCookies() );
|
||||
String action = request.getParameter("action");
|
||||
if( action == null ) action = "";
|
||||
UserMessage msgs = UserMessage.getUserMessage(session);
|
||||
|
||||
// Take care of facebook open graph
|
||||
if( request.getHeader("User-Agent").startsWith("facebookexternalhit/1.1") && page.startsWith("media") ){
|
||||
PrintWriter out = response.getWriter();
|
||||
out.print("<HTML><HEAD>"+
|
||||
"<!-- Facebook OpenGraph -->"+
|
||||
"<meta property='og:title' content='"+WEBSITE_NAME+"'/>"+
|
||||
"<meta property='og:type' content='album'/>"+
|
||||
"<meta property='fb:app_id' content='"+FacebookConnect.getAplicationId()+"'/>"+
|
||||
"<meta property='og:url' content='"+WEBSITE_URL+"media?type="+request.getParameter("type")+"&id="+request.getParameter("id")+"'/>"+
|
||||
"<meta property='og:image' content='"+WEBSITE_URL+"content?type="+request.getParameter("type")+"&id="+request.getParameter("id")+"&size=small'/>"+
|
||||
"<meta property='og:site_name' content='"+WEBSITE_NAME+"'/>"+
|
||||
"</HEAD></HTML>");
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify email address
|
||||
if( action.equalsIgnoreCase("verfemail") ){
|
||||
User verfuser = User.load(db, Long.parseLong(request.getParameter("id")));
|
||||
if( verfuser.verifyEmail(request.getParameter("hash")) ){
|
||||
ZalleryAjax.sendEmailNewUserToAdmin(verfuser, db);
|
||||
verfuser.save(db);
|
||||
msgs.add(MessageType.INFO, "Your email has been successfully verified.");
|
||||
msgs.add(MessageType.WARNING, "The account is waiting account activation by an admin.");
|
||||
}
|
||||
else
|
||||
msgs.add(MessageType.ERROR, "Email verification failed!");
|
||||
}
|
||||
|
||||
// auth with facebook
|
||||
if( user == null ){
|
||||
if( fbc != null ){
|
||||
FBUser fb_user = fbc.getUser();
|
||||
user = User.loadByFacebook(request, response, db, fb_user.getUID() );
|
||||
// New user?
|
||||
if( user == null ){
|
||||
logger.info("Creating new user from Facebook login.");
|
||||
user = new User();
|
||||
user.setFacebookUid( fb_user.getUID() );
|
||||
user.setName( fb_user.getName() );
|
||||
user.setEmail( "" );
|
||||
user.registerOnHost(request, response, db, false );
|
||||
ZalleryAjax.sendEmailNewUserToAdmin(user, db);
|
||||
msgs.add(MessageType.INFO, "Your account has successfully been created. The account is waiting account activation by an admin.");
|
||||
}
|
||||
logger.info("Used Facebook to auth User: \""+user.getName()+"\".");
|
||||
user.registerOnHost(request, response, db, false );
|
||||
session.setAttribute("user", user);
|
||||
session.setAttribute("facebook", fbc);
|
||||
user.save(db);
|
||||
//if( page.startsWith("login") )
|
||||
response.sendRedirect( "gallery" );
|
||||
//else
|
||||
// response.sendRedirect( page );
|
||||
return;
|
||||
}
|
||||
}
|
||||
// auth with cookie
|
||||
if( user == null ){
|
||||
user = User.loadByCookie(request, db, getCookieValue(request.getCookies(), "sessionHash") );
|
||||
if(user != null){
|
||||
logger.info("Used cookies to auth User: \""+user.getName()+"\".");
|
||||
session.setAttribute("user", user);
|
||||
}
|
||||
}
|
||||
|
||||
if( user == null && ( !page.startsWith("register") && !page.startsWith("login") )){
|
||||
//response.sendRedirect("login?redirect=\""+getUrl(request)+"\"");
|
||||
response.sendRedirect("login");
|
||||
return;
|
||||
}
|
||||
// validate user or Logout
|
||||
if( user != null && ( !user.valid(request) || page.startsWith("logout") )){
|
||||
logger.info("Logging Out User: \""+user.getName()+"\".");
|
||||
session.invalidate();
|
||||
session = request.getSession( true );
|
||||
msgs.setSession( session );
|
||||
if( fbc != null ) fbc.logout( response );
|
||||
user.logout( response );
|
||||
|
||||
if( !user.isEmailVerified() )
|
||||
msgs.add(MessageType.ERROR, "Your email has not been verified!");
|
||||
else if( !user.isEnabled() )
|
||||
msgs.add(MessageType.ERROR, "Your account is disabled! Please contact the website administrator.");
|
||||
else
|
||||
msgs.add(MessageType.WARNING, "Your have been logged out.");
|
||||
user = null;
|
||||
response.sendRedirect("login");
|
||||
return;
|
||||
}
|
||||
|
||||
//**********************************************************
|
||||
String include_jsp = null;
|
||||
if( user != null ){
|
||||
logger.finest("Valid user: \""+user.getName()+"\"");
|
||||
// Register facebook on user
|
||||
if( user.getFacebookUid() == null && fbc != null){
|
||||
FBUser fb_user = fbc.getUser();
|
||||
user.setFacebookUid( fb_user.getUID() );
|
||||
msgs.add(MessageType.INFO, "Facebook connected to your account.");
|
||||
}
|
||||
// Import JSP pages
|
||||
if(page.startsWith("media")){
|
||||
try{
|
||||
if( request.getParameter("id") == null && request.getParameter("type") == null){
|
||||
msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
int id = Integer.parseInt( request.getParameter("id") );
|
||||
Media media = Media.load(db, request.getParameter("type"), id);
|
||||
|
||||
request.setAttribute("media", media);
|
||||
include_jsp = "media.jsp";
|
||||
}catch(NumberFormatException e){ logger.log(Level.FINE, "", e); }
|
||||
}
|
||||
else if(page.startsWith("login")){
|
||||
include_jsp = "login.jsp";
|
||||
}
|
||||
else if(page.startsWith("profile")){
|
||||
if( request.getParameter("id") != null ){
|
||||
User profile_user = User.load(db, Long.parseLong( request.getParameter("id") ));
|
||||
if( user.canEdit( profile_user )){
|
||||
request.setAttribute("profile_user", profile_user);
|
||||
include_jsp = "profile.jsp";
|
||||
}else{
|
||||
msgs.add(MessageType.ERROR, "You do not have permission to edit this user.");
|
||||
}
|
||||
}else{
|
||||
request.setAttribute("profile_user", user);
|
||||
include_jsp = "profile.jsp";
|
||||
}
|
||||
}
|
||||
else if(page.startsWith("users")){
|
||||
List<User> users = User.load(db);
|
||||
request.setAttribute("users", users);
|
||||
include_jsp = "users.jsp";
|
||||
}
|
||||
else if(page.startsWith("upload")){
|
||||
List<Folder> dirList = Folder.load(db, user);
|
||||
request.setAttribute("folders", dirList);
|
||||
include_jsp = "upload.jsp";
|
||||
}
|
||||
else if( page.startsWith("slideshow") ){
|
||||
Image image = Image.load(db, Integer.parseInt( request.getParameter("id") ));
|
||||
request.setAttribute("image", image );
|
||||
List<Image> list = Image.loadFolder(db, image.getFolder());
|
||||
|
||||
request.setAttribute("image", image);
|
||||
request.setAttribute("images", list);
|
||||
|
||||
include_jsp = "slideshow.jsp";
|
||||
}
|
||||
else { // if(page.startsWith("gallery"))
|
||||
Folder folder = null;
|
||||
if(request.getParameter("folder") != null && !request.getParameter("folder").equalsIgnoreCase("null"))
|
||||
folder = Folder.load(db, Long.parseLong(request.getParameter("folder")) );
|
||||
else{
|
||||
folder = Folder.loadRoot(db);
|
||||
// Setup new root folder
|
||||
if( folder == null ){
|
||||
folder = Folder.genRoot();
|
||||
folder.save(db);
|
||||
}
|
||||
}
|
||||
List<Media> list = Media.load(db, folder);
|
||||
List<Folder> subFolders = Folder.loadSubFolders(db, folder.getId());
|
||||
|
||||
//session.setAttribute("user", user);
|
||||
request.setAttribute("folder", folder);
|
||||
request.setAttribute("subfolders", subFolders);
|
||||
request.setAttribute("media", list);
|
||||
|
||||
include_jsp = "gallery.jsp";
|
||||
}
|
||||
}
|
||||
else if(page.startsWith("register")){
|
||||
include_jsp = "register.jsp";
|
||||
}
|
||||
else if(page.startsWith("login")){
|
||||
include_jsp = "login.jsp";
|
||||
}
|
||||
else{
|
||||
//response.sendRedirect("login?redirect=\""+getUrl(request)+"\"");
|
||||
response.sendRedirect("login");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
include("header.jsp", request, response);
|
||||
if( include_jsp != null )
|
||||
include(include_jsp, request, response);
|
||||
include("footer.jsp", request, response);
|
||||
} catch (Exception e) {
|
||||
logger.severe(e.getMessage());
|
||||
System.out.flush();
|
||||
throw new ServletException(e);
|
||||
} finally{
|
||||
if(db != null) db.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
|
||||
try {
|
||||
include("ajax", request, response);
|
||||
|
||||
// RequestDispatcher include header read only workaround
|
||||
HttpSession session = request.getSession();
|
||||
User user = (User) session.getAttribute("user");
|
||||
if( user != null ){
|
||||
Cookie c = new Cookie("sessionHash", user.getSessionHash() );
|
||||
c.setMaxAge(5*24*60*60); // 5 days
|
||||
response.addCookie( c );
|
||||
}
|
||||
|
||||
// Do the output
|
||||
doGet(request, response);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.severe(e.getMessage());
|
||||
throw new ServletException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static DBConnection getDB() throws ServletException{
|
||||
try {
|
||||
return new DBConnection("jdbc/mysql");
|
||||
} catch (Exception e) {
|
||||
throw new ServletException(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void include(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
|
||||
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(THEME+"/"+url);
|
||||
if (dispatcher != null)
|
||||
dispatcher.include(request, response);
|
||||
}
|
||||
|
||||
public static String getCookieValue(Cookie[] cookies, String name) {
|
||||
if( cookies == null )
|
||||
return null;
|
||||
for(Cookie cookie : cookies) {
|
||||
if ( name.equals(cookie.getName()) )
|
||||
return cookie.getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getWebsiteName() {
|
||||
return WEBSITE_NAME;
|
||||
}
|
||||
|
||||
public static String getWebsiteURL() {
|
||||
return WEBSITE_URL;
|
||||
}
|
||||
|
||||
// /mywebapp/servlet/MyServlet/a/b;c=123?d=789
|
||||
public static String getUrl(HttpServletRequest req) {
|
||||
String reqUri = req.getRequestURI().toString();
|
||||
String queryString = req.getQueryString(); // d=789
|
||||
if (queryString != null) {
|
||||
reqUri += "?"+queryString;
|
||||
}
|
||||
return reqUri;
|
||||
}
|
||||
}
|
||||
437
src/zall/ZalleryAjax.java
Normal file
437
src/zall/ZalleryAjax.java
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
package zall;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import zall.bean.Comment;
|
||||
import zall.bean.Folder;
|
||||
import zall.bean.Media;
|
||||
import zall.bean.User;
|
||||
import zall.util.Email;
|
||||
import zall.util.Email.ContentType;
|
||||
import zall.util.msg.UserMessage;
|
||||
import zall.util.msg.UserMessage.MessageType;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
public class ZalleryAjax extends HttpServlet{
|
||||
public static final Logger logger = LogUtil.getLogger();
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
|
||||
try {
|
||||
doGet(request, response, response.getWriter());
|
||||
} catch (IOException e) {
|
||||
throw new ServletException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
|
||||
doGet(request, response, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param out is the PrintStream that will be used, no output will be generated if it is null
|
||||
*/
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException{
|
||||
DBConnection db = null;
|
||||
try {
|
||||
HttpSession session = request.getSession();
|
||||
User user = (User) session.getAttribute("user");
|
||||
String action = request.getParameter("action");
|
||||
if( action == null ) action = "";
|
||||
db = Zallery.getDB();
|
||||
UserMessage msgs = UserMessage.getUserMessage(session);
|
||||
|
||||
|
||||
// Login
|
||||
if( action.equalsIgnoreCase("login") ){
|
||||
user = User.load(request, response, db, request.getParameter("email"), request.getParameter("password") );
|
||||
if( user != null ){
|
||||
logger.info("Used user input to auth \""+user.getName()+"\"");
|
||||
session.setAttribute("user", user);
|
||||
if( out != null )
|
||||
out.println("{ }");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\":\"Wrong username or password!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Wrong username or password!");
|
||||
return;
|
||||
}
|
||||
// Register
|
||||
if( action.equalsIgnoreCase("register") ){
|
||||
if( request.getParameter("email") == null ){
|
||||
msgs.add(MessageType.ERROR, "Please provide a valid email!");
|
||||
return;
|
||||
}
|
||||
if( User.emailExists(request.getParameter("email"), db) ){
|
||||
msgs.add(MessageType.ERROR, "An account with that email already exists!");
|
||||
return;
|
||||
}
|
||||
user = new User();
|
||||
user.setEmail( request.getParameter("email") );
|
||||
user.setPassword( request.getParameter("password") );
|
||||
user.setName( request.getParameter("name") );
|
||||
user.save(db);
|
||||
sendEmailVerification( user );
|
||||
logger.info("Registered new user: "+user.getName()+".");
|
||||
session.setAttribute("user", user);
|
||||
if(out != null) out.println("{ \"id\":"+user.getId()+" }");
|
||||
else msgs.add(MessageType.INFO, "Your account has successfully been created. A verification email has been sent to your email, please click the link to continue.");
|
||||
return;
|
||||
}
|
||||
// Verify email address
|
||||
if( action.equalsIgnoreCase("verfemail") ){
|
||||
User verfuser = User.load(db, Long.parseLong(request.getParameter("id")));
|
||||
if( verfuser.verifyEmail(request.getParameter("hash")) ){
|
||||
sendEmailNewUserToAdmin(verfuser, db);
|
||||
verfuser.save(db);
|
||||
if(out != null) out.println("{ }");
|
||||
else msgs.add(MessageType.INFO, "Your email has been successfully verified, the account is waiting account activation by an admin.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\":\"Email verification failed!\" }");
|
||||
else msgs.add(MessageType.ERROR, "Email verification failed!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Other
|
||||
else if( user != null ){
|
||||
// Administration things of users
|
||||
if( user.isSuperUser() && action.equalsIgnoreCase("moduserstat") ){
|
||||
User target_user = User.load(db, Long.parseLong( request.getParameter("id") ) );
|
||||
// Enable user
|
||||
if( request.getParameter("enable") != null ){
|
||||
target_user.setEnabled( true );
|
||||
// Email the user about the activation
|
||||
Email email = new Email("admin@koc.se", target_user.getEmail());
|
||||
email.setSubject("Account activation at "+Zallery.getWebsiteName());
|
||||
email.setContentType(ContentType.HTML);
|
||||
email.setMessage("Your account has now been activated by an admin. You can now login and use the site. " +
|
||||
"<a href='"+Zallery.getWebsiteURL()+"'>"+Zallery.getWebsiteURL()+"</a>");
|
||||
}
|
||||
// Disable user, can not disable one self!
|
||||
else if( request.getParameter("disable") != null && !user.equals( target_user ) )
|
||||
target_user.setEnabled( false );
|
||||
// Promote user to Admin
|
||||
else if( request.getParameter("setadmin") != null )
|
||||
target_user.setSuperUser( true );
|
||||
// Degrade Admin to normal user, can not degrade one self!
|
||||
else if( request.getParameter("unadmin") != null && !user.equals( target_user ) )
|
||||
target_user.setSuperUser( false );
|
||||
else{
|
||||
if( out != null ) out.println("{ }");
|
||||
return;
|
||||
}
|
||||
target_user.save(db);
|
||||
if( out != null )
|
||||
out.println("{ }");
|
||||
else
|
||||
msgs.add(MessageType.INFO, "Account changes saved.");
|
||||
return;
|
||||
}
|
||||
// User profile changes
|
||||
else if( action.equalsIgnoreCase("moduser") ){
|
||||
User target_user = null;
|
||||
if( request.getParameter("id") != null )
|
||||
target_user = User.load(db, Long.parseLong( request.getParameter("id") ) );
|
||||
else // set target user to the logged in user
|
||||
target_user = user;
|
||||
|
||||
if( user.canEdit(target_user) ){
|
||||
if( request.getParameter("email") != null )
|
||||
target_user.setEmail( request.getParameter("email") );
|
||||
if( request.getParameter("password") != null ){
|
||||
if( target_user.getPassword() == null )
|
||||
target_user.setPassword( request.getParameter("password") );
|
||||
else if( request.getParameter("oldPassword") != null )
|
||||
if( target_user.equalsPassword(request.getParameter("oldPassword")) )
|
||||
target_user.setPassword( request.getParameter("password") );
|
||||
else{
|
||||
if(out != null) out.println("{ \"error\": \"Wrong password!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Wrong password!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if( request.getParameter("name") != null )
|
||||
target_user.setName( request.getParameter("name") );
|
||||
target_user.save(db);
|
||||
if( !user.isEmailVerified() )
|
||||
sendEmailVerification( target_user );
|
||||
if( out != null )
|
||||
out.println("{ }");
|
||||
else
|
||||
msgs.add(MessageType.INFO, "Settings saved successfully.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"You are not authorize to change these values!\"}");
|
||||
else msgs.add(MessageType.ERROR, "You are not authorize to change these values!");
|
||||
return;
|
||||
}
|
||||
// Remove user
|
||||
else if( action.equalsIgnoreCase("rmuser") ){
|
||||
User target_user = null;
|
||||
if( request.getParameter("id") != null )
|
||||
target_user = User.load(db, Long.parseLong( request.getParameter("id") ) );
|
||||
else {
|
||||
if(out != null) out.println("{ \"error\": \"Missing parameters!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
|
||||
if( target_user != null ){
|
||||
if( user.isSuperUser() ){
|
||||
target_user.delete(db);
|
||||
|
||||
if( out != null ) out.println("{ }");
|
||||
else msgs.add(MessageType.INFO, "User removed successfully.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"You are not authorize to delete that user!\"}");
|
||||
else msgs.add(MessageType.ERROR, "You are not authorize to delete that user!");
|
||||
}
|
||||
else {
|
||||
if(out != null) out.println("{ \"error\": \"No such user!\"}");
|
||||
else msgs.add(MessageType.ERROR, "No such user!");
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Remove user
|
||||
else if( action.equalsIgnoreCase("sendverfemail") ){
|
||||
User target_user = null;
|
||||
if( request.getParameter("id") != null )
|
||||
target_user = User.load(db, Long.parseLong( request.getParameter("id") ) );
|
||||
else {
|
||||
if(out != null) out.println("{ \"error\": \"Missing parameters!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
|
||||
if( target_user != null ){
|
||||
if( user.isSuperUser() ){
|
||||
sendEmailVerification(target_user);
|
||||
|
||||
logger.info("Verification email sent successfully to: "+user.getEmail());
|
||||
if( out != null ) out.println("{ }");
|
||||
else msgs.add(MessageType.INFO, "Verification email sent successfully.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"You are not authorize send verification emails!\"}");
|
||||
else msgs.add(MessageType.ERROR, "You are not authorize send verification emails!");
|
||||
}
|
||||
else {
|
||||
if(out != null) out.println("{ \"error\": \"No such user!\"}");
|
||||
else msgs.add(MessageType.ERROR, "No such user!");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
///// Media stuff
|
||||
// Comments for media
|
||||
else if( action.equalsIgnoreCase("comment") ){
|
||||
if( request.getParameter("id") == null || request.getParameter("type") == null ){
|
||||
if(out != null) out.println("{ \"error\": \"Missing parameters!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
long id = Long.parseLong(request.getParameter("id"));
|
||||
Media media = Media.load(db, request.getParameter("type"), id);
|
||||
|
||||
Comment cm = new Comment();
|
||||
cm.setUser( user );
|
||||
cm.setMessage( request.getParameter("msg") );
|
||||
media.addComment( cm );
|
||||
media.save( db );
|
||||
|
||||
if( out != null ) out.println("{ }");
|
||||
else msgs.add(MessageType.INFO, "Comment saved.");
|
||||
return;
|
||||
}
|
||||
// Edit media information
|
||||
else if( action.equalsIgnoreCase("modmedia") ){
|
||||
if( request.getParameter("id") == null || request.getParameter("type") == null ){
|
||||
if(out != null) out.println("{ \"error\": \"Missing parameters!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
long id = Long.parseLong(request.getParameter("id"));
|
||||
Media media = Media.load(db, request.getParameter("type"), id);
|
||||
|
||||
if( media != null ){
|
||||
if( user.canEdit(media) ){
|
||||
media.setTitle( request.getParameter("title") );
|
||||
media.setDescription( request.getParameter("description") );
|
||||
media.save(db);
|
||||
|
||||
if(out != null) out.println("{}");
|
||||
else msgs.add(MessageType.INFO, "Item edited successfully.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"You are not authorize to modify this item!\"}");
|
||||
else msgs.add(MessageType.ERROR, "You are not authorize to modify this item!");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"No such item!\"}");
|
||||
else msgs.add(MessageType.ERROR, "The item does not exist!");
|
||||
|
||||
}
|
||||
// Remove media
|
||||
else if( action.equalsIgnoreCase("rmmedia") ){
|
||||
if( request.getParameter("id") == null || request.getParameter("type") == null ){
|
||||
if(out != null) out.println("{ \"error\": \"Missing parameters!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
long id = Long.parseLong(request.getParameter("id"));
|
||||
Media media = Media.load(db, request.getParameter("type"), id);
|
||||
|
||||
if( media != null ){
|
||||
if( user.canEdit(media) ){
|
||||
media.delete( db );
|
||||
|
||||
if(out != null) out.println("{}");
|
||||
else msgs.add(MessageType.INFO, "Item removed successfully.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"You are not authorize to delete the item!\"}");
|
||||
else msgs.add(MessageType.ERROR, "You are not authorize to delete the item!");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"No such item!\"}");
|
||||
else msgs.add(MessageType.ERROR, "The item does not exist!");
|
||||
|
||||
}
|
||||
else if( action.equalsIgnoreCase("rmdir") ){
|
||||
if( request.getParameter("id") == null){
|
||||
if(out != null) out.println("{ \"error\": \"Missing parameters!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Missing parameters!");
|
||||
return;
|
||||
}
|
||||
long id = Long.parseLong(request.getParameter("id"));
|
||||
Folder folder = Folder.load(db, id);
|
||||
|
||||
if( folder != null ){
|
||||
if( !folder.isEmpty(db) ){
|
||||
if(out != null) out.println("{ \"error\": \"Folder is not empty!\"}");
|
||||
else msgs.add(MessageType.ERROR, "Folder is not empty!");
|
||||
} else if( user.canEdit(folder) ){
|
||||
folder.delete( db );
|
||||
if(out != null) out.println("{}");
|
||||
else msgs.add(MessageType.INFO, "Folder removed successfully.");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"You are not authorize to delete this folder!\"}");
|
||||
else msgs.add(MessageType.ERROR, "You are not authorize to delete this folder!");
|
||||
}
|
||||
else if(out != null) out.println("{ \"error\": \"No such folder!\"}");
|
||||
else msgs.add(MessageType.ERROR, "The folder does not exist!");
|
||||
|
||||
}
|
||||
|
||||
// Create Folder
|
||||
else if( action.equalsIgnoreCase("mkdir") ){
|
||||
String path = request.getParameter("dir");
|
||||
Folder folder = Folder.load(db, path, user);
|
||||
logger.info( "Creating new folder: /"+user.getName()+"/"+path );
|
||||
// parent folder
|
||||
if( folder == null ){
|
||||
String[] dirs = path.split("/");
|
||||
Folder parent = Folder.loadRoot(db);
|
||||
if( user.isSuperUser() && path.charAt(0) == '/' )
|
||||
path = "";
|
||||
else{
|
||||
path = "/{NAME}";
|
||||
|
||||
// Get root folder
|
||||
parent = Folder.load(db, path, user); // Get user root folder
|
||||
if( parent == null ){ // Create root folder
|
||||
parent = Folder.loadRoot(db); // get root folder
|
||||
folder = new Folder();
|
||||
folder.setUser( user );
|
||||
folder.setParent( parent );
|
||||
folder.setName( "{NAME}" );
|
||||
folder.save( db );
|
||||
parent = folder;
|
||||
}
|
||||
}
|
||||
|
||||
for(String dir : dirs){
|
||||
if( dir.trim().isEmpty() ) // skip empty names
|
||||
continue;
|
||||
path += "/"+dir;
|
||||
folder = Folder.load(db, path, user);
|
||||
if(folder == null){ // create folder
|
||||
folder = new Folder();
|
||||
folder.setUser( user );
|
||||
folder.setParent( parent );
|
||||
folder.setName( dir );
|
||||
folder.save( db );
|
||||
}
|
||||
parent = folder;
|
||||
}
|
||||
if(out != null) out.print( "{\"id\":"+folder.getId()+", \"name\":\""+folder.getPath()+"\"}" );
|
||||
else msgs.add(MessageType.INFO, "Folder '"+path+"' has been successfully created.!");
|
||||
}
|
||||
else if(out != null) out.println("{\"error\":\"The folder '"+path+"' already exists!\"}");
|
||||
else msgs.add(MessageType.ERROR, "The folder '"+path+"' already exists!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else{
|
||||
// Unauthorized
|
||||
if( out != null ){
|
||||
out.print( "{\"error\":\"Unauthorized user!\"}" );
|
||||
response.setStatus( 401 );
|
||||
}
|
||||
else
|
||||
msgs.add(MessageType.ERROR, "Unauthorized user!");
|
||||
logger.severe("Unauthorized user!");
|
||||
return;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
if( out != null ){
|
||||
out.println("{\"error\":\""+e.getMessage().replaceAll("\"", "\\\"")+"\"}");
|
||||
logger.log(Level.SEVERE, "Exception in ajax page!", e);
|
||||
}
|
||||
else
|
||||
throw new ServletException(e);
|
||||
} finally{
|
||||
if(db != null) db.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void sendEmailVerification(User user) throws IOException{
|
||||
// Email
|
||||
Email smtpEmail = new Email("admin@koc.se", user.getEmail());
|
||||
smtpEmail.setNiceFrom("Koc.se Admin");
|
||||
smtpEmail.setSubject("Registration at "+Zallery.getWebsiteName());
|
||||
smtpEmail.setContentType(ContentType.HTML);
|
||||
smtpEmail.setMessage("You receive this message because you have requested an account" +
|
||||
"<br>at <a href='"+Zallery.getWebsiteURL()+"'>"+Zallery.getWebsiteName()+"</a>. Please click the link to verify your email address: " +
|
||||
"<p><a href='"+Zallery.getWebsiteURL()+"?action=verfemail&id="+user.getId()+"&hash="+user.getEmailVerificationHash()+"'>"+Zallery.getWebsiteURL()+"?action=verfemail&id="+user.getId()+"&hash="+user.getEmailVerificationHash()+"</a>" +
|
||||
"<p> You will have to wait for an admin to activate your account after you have verified your email.");
|
||||
smtpEmail.send();
|
||||
}
|
||||
|
||||
public static void sendEmailNewUserToAdmin(User newuser, DBConnection db) throws SQLException, IOException{
|
||||
// Email the admin about new user
|
||||
Email email = new Email("admin@koc.se", "admin@koc.se");
|
||||
email.setNiceFrom("Koc.se Admin");
|
||||
email.setSubject("New user activation request at "+Zallery.getWebsiteName());
|
||||
email.setContentType(ContentType.HTML);
|
||||
email.setMessage("A new user has registered for an account at " +
|
||||
"<a href='"+Zallery.getWebsiteURL()+"'>"+Zallery.getWebsiteName()+"</a>:" +
|
||||
"<p>Email: <b>" + newuser.getEmail() + "</b>" +
|
||||
"<br>Name: <b>" + newuser.getName() + "</b>" +
|
||||
"<br>Facebook: <a href='http://www.facebook.com/profile.php?id="+newuser.getFacebookUid()+"'>"+newuser.getFacebookUid()+"</a>");
|
||||
List<User> admins = User.loadSuperUsers(db);
|
||||
for(User admin : admins){
|
||||
if( admin.isEmailVerified() ){
|
||||
email.setTo( admin.getEmail() );
|
||||
email.send();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
85
src/zall/ZalleryContent.java
Normal file
85
src/zall/ZalleryContent.java
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
package zall;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.fileupload.util.Streams;
|
||||
|
||||
import zall.bean.Image;
|
||||
import zall.bean.Media;
|
||||
import zall.bean.User;
|
||||
import zall.bean.Video;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.io.file.FileUtil;
|
||||
|
||||
public class ZalleryContent extends HttpServlet{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
|
||||
DBConnection db = null;
|
||||
try {
|
||||
HttpSession session = request.getSession();
|
||||
User user = (User) session.getAttribute("user");
|
||||
String size = request.getParameter("size");
|
||||
if( size == null ) size = "";
|
||||
|
||||
if( user != null || size.equalsIgnoreCase("small") ){
|
||||
db = Zallery.getDB();
|
||||
Media media;
|
||||
|
||||
if( "video".equals(request.getParameter("type")) )
|
||||
media = Video.load(db, Integer.parseInt(request.getParameter("id")));
|
||||
else
|
||||
media = Image.load(db, Integer.parseInt(request.getParameter("id")));
|
||||
|
||||
if( media != null ){
|
||||
File file = null;
|
||||
if( size.equalsIgnoreCase( "small" ) )
|
||||
file = media.getFile( Media.Size.SMALL );
|
||||
else if( size.equalsIgnoreCase( "medium" ) )
|
||||
file = media.getFile( Media.Size.MEDIUM );
|
||||
else
|
||||
file = media.getFile( Media.Size.ORIGINAL );
|
||||
|
||||
if( request.getParameter("download") != null )
|
||||
response.setHeader("Content-disposition", "attachment; filename="+media.getTitle()+"."+FileUtil.getFileExtension(file));
|
||||
|
||||
if( file.exists() ){
|
||||
if( "video".equals(request.getParameter("type")) )
|
||||
response.setContentType("video/"+FileUtil.getFileExtension(file));
|
||||
else
|
||||
response.setContentType("image/"+FileUtil.getFileExtension(file));
|
||||
response.setContentLength( (int)file.length() );
|
||||
|
||||
BufferedInputStream in = new BufferedInputStream( new FileInputStream(file) );
|
||||
Streams.copy(in, response.getOutputStream(), false);
|
||||
in.close();
|
||||
}
|
||||
else
|
||||
response.setStatus( 404 );
|
||||
}
|
||||
else{
|
||||
// Page not found
|
||||
response.setStatus( 404 );
|
||||
}
|
||||
|
||||
}
|
||||
else{
|
||||
// Unauthorized
|
||||
response.setStatus( 401 );
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new ServletException(e);
|
||||
} finally{
|
||||
if(db != null) db.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
348
src/zall/ZalleryTranscoder.java
Normal file
348
src/zall/ZalleryTranscoder.java
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
package zall;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
|
||||
import com.xuggle.mediatool.IMediaReader;
|
||||
import com.xuggle.mediatool.IMediaWriter;
|
||||
import com.xuggle.mediatool.MediaToolAdapter;
|
||||
import com.xuggle.mediatool.ToolFactory;
|
||||
import com.xuggle.mediatool.event.AudioSamplesEvent;
|
||||
import com.xuggle.mediatool.event.IAddStreamEvent;
|
||||
import com.xuggle.mediatool.event.IAudioSamplesEvent;
|
||||
import com.xuggle.mediatool.event.IVideoPictureEvent;
|
||||
import com.xuggle.mediatool.event.VideoPictureEvent;
|
||||
import com.xuggle.xuggler.IAudioResampler;
|
||||
import com.xuggle.xuggler.IAudioSamples;
|
||||
import com.xuggle.xuggler.ICodec;
|
||||
import com.xuggle.xuggler.IStreamCoder;
|
||||
import com.xuggle.xuggler.IVideoPicture;
|
||||
import com.xuggle.xuggler.IVideoResampler;
|
||||
|
||||
import zall.bean.Media.Size;
|
||||
import zall.bean.Video;
|
||||
import zutil.StringUtil;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
|
||||
public class ZalleryTranscoder extends HttpServlet{
|
||||
private static final Logger logger = LogUtil.getLogger();
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
// Media Queue
|
||||
private static Queue<Video> transcodingQueue;
|
||||
private static TranscoderThread worker;
|
||||
|
||||
public void init( ServletConfig config ){
|
||||
try{
|
||||
transcodingQueue = new LinkedList<Video>();
|
||||
worker = new TranscoderThread();
|
||||
worker.start();
|
||||
|
||||
// get untranscoded videos
|
||||
DBConnection db = null;
|
||||
try {
|
||||
db = Zallery.getDB();
|
||||
List<Video> incomplete = Video.loadUntransoded( db );
|
||||
synchronized (transcodingQueue) {
|
||||
transcodingQueue.addAll( incomplete );
|
||||
transcodingQueue.notify();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, null, e);
|
||||
}finally{
|
||||
if( db != null ) db.close();
|
||||
}
|
||||
}
|
||||
catch(Exception e){
|
||||
logger.log(Level.SEVERE, "Unable to initialize ZalleryTranscoder!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy( ){
|
||||
worker.abort();
|
||||
}
|
||||
|
||||
|
||||
public static Video getProcessingVideo(){
|
||||
return worker.currentVideo;
|
||||
}
|
||||
|
||||
public static Queue<Video> getQueue(){
|
||||
return transcodingQueue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add a video to the transcoding queue
|
||||
*
|
||||
* @param video is the video to transcode
|
||||
*/
|
||||
public static void addVideo(Video video) {
|
||||
if( transcodingQueue == null ){
|
||||
logger.severe("ZalleryTranscoder not initialized!");
|
||||
return;
|
||||
}
|
||||
if( !transcodingQueue.contains(video) && worker.currentVideo != video ){
|
||||
synchronized (transcodingQueue){
|
||||
transcodingQueue.add( video );
|
||||
transcodingQueue.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the class that is doing the actual work of transcoding videos
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
private static class TranscoderThread extends Thread{
|
||||
private boolean stop;
|
||||
protected long startTime;
|
||||
protected Video currentVideo;
|
||||
|
||||
|
||||
public void run(){
|
||||
logger.info("ZalleryTranscoder thread started.");
|
||||
try {
|
||||
while( true ){
|
||||
// Get video to transcode
|
||||
while( !transcodingQueue.isEmpty() ){
|
||||
currentVideo = transcodingQueue.poll();
|
||||
startTime = System.currentTimeMillis();
|
||||
logger.info("Starting transcoding video(id:"+currentVideo.getId()+")");
|
||||
|
||||
File originalFile = currentVideo.getFile( Size.ORIGINAL );
|
||||
File mediumFile = currentVideo.getFile( Size.MEDIUM );
|
||||
File smallFile = currentVideo.getFile( Size.SMALL );
|
||||
|
||||
///////////// Start Transcoding
|
||||
// create a media reader
|
||||
IMediaReader reader = ToolFactory.makeReader( originalFile.getPath() );
|
||||
reader.addListener(new FrameGrabListener(reader, 0.2));
|
||||
reader.addListener(new ProgressListener(reader));
|
||||
|
||||
VideoTranscoderListener converter = new VideoTranscoderListener(640, 360);
|
||||
reader.addListener(converter);
|
||||
|
||||
// create a media writer
|
||||
IMediaWriter writer = ToolFactory.makeWriter(mediumFile.getPath(), reader);
|
||||
converter.addListener(writer);
|
||||
|
||||
// create a media viewer with stats enabled for debugging
|
||||
// add a viewer to the reader, to see the decoded media
|
||||
//IMediaViewer mediaViewer = ToolFactory.makeViewer(true);
|
||||
//reader.addListener(mediaViewer);
|
||||
//writer.addListener(mediaViewer);
|
||||
|
||||
// read and decode packets from the source file and
|
||||
// and dispatch decoded audio and video to the writer
|
||||
while (reader.readPacket() == null);
|
||||
|
||||
// Incomplete transcoding
|
||||
if( reader.isOpen() ){
|
||||
logger.severe("Transcoding incomplete, removing incomplete files!");
|
||||
reader.close();
|
||||
mediumFile.delete();
|
||||
smallFile.delete();
|
||||
if( stop )
|
||||
return;
|
||||
}
|
||||
else{
|
||||
logger.info("Done transcoding video(id:"+currentVideo.getId()+") time: "+StringUtil.formatTimeToString(System.currentTimeMillis()-startTime));
|
||||
currentVideo.setTranscoded(true);
|
||||
try{
|
||||
DBConnection db = Zallery.getDB();
|
||||
currentVideo.save(db);
|
||||
db.close();
|
||||
}catch(Exception e){
|
||||
logger.log(Level.SEVERE, "Unable to save video bean!", e);
|
||||
}
|
||||
}
|
||||
currentVideo = null;
|
||||
}
|
||||
// Wait for new video to transcode
|
||||
synchronized (transcodingQueue) {
|
||||
transcodingQueue.wait();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(Level.SEVERE, "Transcoding thread has crashed!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void abort(){
|
||||
stop = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class MyVideoListener extends MediaToolAdapter {
|
||||
private Integer width;
|
||||
private Integer height;
|
||||
|
||||
public MyVideoListener(Integer aWidth, Integer aHeight) {
|
||||
this.width = aWidth;
|
||||
this.height = aHeight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAddStream(IAddStreamEvent event) {
|
||||
int streamIndex = event.getStreamIndex();
|
||||
IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
|
||||
if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
|
||||
} else if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
|
||||
streamCoder.setWidth(width);
|
||||
streamCoder.setHeight(height);
|
||||
}
|
||||
super.onAddStream(event);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class VideoTranscoderListener extends MediaToolAdapter{
|
||||
private int width;
|
||||
private int height;
|
||||
|
||||
public VideoTranscoderListener(int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
private IVideoResampler videoResampler = null;
|
||||
private IAudioResampler audioResampler = null;
|
||||
|
||||
IMediaWriter writer;
|
||||
|
||||
@Override
|
||||
public void onAddStream(IAddStreamEvent event) {
|
||||
int streamIndex = event.getStreamIndex();
|
||||
IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
|
||||
if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
|
||||
//writer.addAudioStream(streamIndex, streamIndex, ICodec.ID.CODEC_ID_AAC, 2, 44100);
|
||||
streamCoder.setSampleRate( 44100 );
|
||||
/*
|
||||
streamCoder.setCodec( ICodec.ID.CODEC_ID_AAC );
|
||||
streamCoder.setBitRate( 128 );
|
||||
*/
|
||||
}
|
||||
else if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
|
||||
//writer.addVideoStream(streamIndex, streamIndex, ICodec.ID.CODEC_ID_H264, VIDEO_WIDTH, VIDEO_HEIGHT);
|
||||
streamCoder.setWidth( width );
|
||||
streamCoder.setHeight( height );
|
||||
|
||||
/*
|
||||
streamCoder.setCodec(ICodec.findEncodingCodec( ICodec.ID.CODEC_ID_H264 ));
|
||||
streamCoder.setBitRate( 500000 );
|
||||
int retval = Configuration.configure("/usr/local/xuggler/share/ffmpeg/libx264-superfast.ffpreset", streamCoder);
|
||||
if (retval<0)
|
||||
throw new RuntimeException("cound not cofigure coder from preset file");
|
||||
*/
|
||||
}
|
||||
super.onAddStream(event);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onVideoPicture(IVideoPictureEvent event) {
|
||||
IVideoPicture pic = event.getPicture();
|
||||
if (videoResampler == null) {
|
||||
videoResampler = IVideoResampler.make(width, height, pic.getPixelType(), pic.getWidth(), pic.getHeight(), pic.getPixelType());
|
||||
}
|
||||
IVideoPicture out = IVideoPicture.make(pic.getPixelType(), width, height);
|
||||
videoResampler.resample(out, pic);
|
||||
|
||||
IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out, event.getStreamIndex());
|
||||
super.onVideoPicture(asc);
|
||||
out.delete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAudioSamples(IAudioSamplesEvent event) {
|
||||
IAudioSamples samples = event.getAudioSamples();
|
||||
if (audioResampler == null) {
|
||||
audioResampler = IAudioResampler.make(2, samples.getChannels(), 44100, samples.getSampleRate());
|
||||
}
|
||||
if (event.getAudioSamples().getNumSamples() > 0) {
|
||||
IAudioSamples out = IAudioSamples.make(samples.getNumSamples(), samples.getChannels());
|
||||
audioResampler.resample(out, samples, samples.getNumSamples());
|
||||
|
||||
AudioSamplesEvent asc = new AudioSamplesEvent(event.getSource(), out, event.getStreamIndex());
|
||||
super.onAudioSamples(asc);
|
||||
out.delete();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class ProgressListener extends MediaToolAdapter {
|
||||
private long currentLength;
|
||||
private long totalLength;
|
||||
private int progress = -1;
|
||||
|
||||
public ProgressListener(IMediaReader reader) {
|
||||
if( !reader.isOpen() )
|
||||
reader.open(); // read container
|
||||
this.totalLength = reader.getContainer().getDuration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onVideoPicture(IVideoPictureEvent event) {
|
||||
currentLength = event.getTimeStamp();
|
||||
|
||||
if( (int)(100*getProgress()) != progress ){
|
||||
progress = (int)(100*getProgress());
|
||||
System.out.print("\n"+(int)(100*getProgress())+"% ");
|
||||
}
|
||||
else System.out.print(".");
|
||||
}
|
||||
|
||||
public long getProcessedLength(){
|
||||
return currentLength;
|
||||
}
|
||||
|
||||
public long getTotalLength(){
|
||||
return totalLength;
|
||||
}
|
||||
|
||||
public double getProgress(){
|
||||
if(totalLength > 0)
|
||||
return ((double)currentLength/totalLength);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
class FrameGrabListener extends MediaToolAdapter {
|
||||
private long totalLength;
|
||||
private long grabAt;
|
||||
|
||||
public FrameGrabListener(IMediaReader reader, double at) {
|
||||
if( !reader.isOpen() )
|
||||
reader.open(); // read container
|
||||
this.totalLength = reader.getContainer().getDuration();
|
||||
setAtProgress(at);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onVideoPicture(IVideoPictureEvent event) {
|
||||
long currentLength = event.getTimeStamp();
|
||||
|
||||
if( grabAt > 0 && currentLength > grabAt ){
|
||||
System.out.println("\nScreanshoot!!!");
|
||||
grabAt = -1;
|
||||
}
|
||||
}
|
||||
|
||||
public void setAtProgress(double procent){
|
||||
grabAt = (long)(totalLength * procent);
|
||||
}
|
||||
}
|
||||
|
||||
50
src/zall/bean/Comment.java
Normal file
50
src/zall/bean/Comment.java
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package zall.bean;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Date;
|
||||
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.db.bean.DBBean.*;
|
||||
import zutil.parser.BBCodeParser;
|
||||
|
||||
@DBTable("Comments")
|
||||
public class Comment extends DBBean{
|
||||
private static BBCodeParser parser = null;
|
||||
|
||||
protected User user;
|
||||
protected Date date;
|
||||
protected String message;
|
||||
|
||||
public Comment(){
|
||||
if( parser == null ){
|
||||
parser = new BBCodeParser();
|
||||
}
|
||||
setCurrentDate();
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
public void setMessage(String msg) {
|
||||
if( msg != null ){
|
||||
msg = msg.replaceAll("<", "<");
|
||||
msg = msg.replaceAll(">", ">");
|
||||
this.message = parser.read( msg );
|
||||
}
|
||||
}
|
||||
public void setCurrentDate() {
|
||||
this.date = new Timestamp( System.currentTimeMillis() );
|
||||
}
|
||||
}
|
||||
185
src/zall/bean/Folder.java
Normal file
185
src/zall/bean/Folder.java
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
package zall.bean;
|
||||
|
||||
import java.io.File;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.db.bean.DBBeanSQLResultHandler;
|
||||
import zutil.db.bean.DBBean.*;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
import zall.Zallery;
|
||||
|
||||
@DBTable("Folder")
|
||||
public class Folder extends DBBean{
|
||||
private static final Logger logger = LogUtil.getLogger();
|
||||
|
||||
protected transient String name;
|
||||
protected User user;
|
||||
protected String path;
|
||||
protected Folder parent;
|
||||
protected Timestamp date;
|
||||
|
||||
//@DBLinkTable(name="FolderTree", beanClass=Folder.class, idColumn="parent")
|
||||
//protected LinkedList<Folder> subFolders;
|
||||
|
||||
|
||||
public static Folder load(DBConnection db, Long id) throws SQLException{
|
||||
return load(db, Folder.class, id);
|
||||
}
|
||||
public static List<Folder> loadSubFolders(DBConnection db, Long id) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Folder WHERE parent=?");
|
||||
sql.setLong(1, id);
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(Folder.class, db));
|
||||
}
|
||||
|
||||
public static Folder loadRoot(DBConnection db) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Folder WHERE path=?");
|
||||
sql.setString(1, "/");
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.create(Folder.class, db));
|
||||
}
|
||||
|
||||
public static Folder load(DBConnection db, String path, User user) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Folder WHERE path=? AND user=?");
|
||||
sql.setString(1, path);
|
||||
sql.setLong(2, user.getId());
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.create(Folder.class, db));
|
||||
}
|
||||
|
||||
public static List<Folder> load(DBConnection db, User user) throws SQLException{
|
||||
if( user.getId() == null )
|
||||
return new LinkedList<Folder>();
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Folder WHERE user=?");
|
||||
sql.setLong(1, user.getId() );
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(Folder.class, db));
|
||||
}
|
||||
|
||||
public Folder(){
|
||||
//subFolders = new LinkedList<Folder>();
|
||||
date = new Timestamp( System.currentTimeMillis() );
|
||||
}
|
||||
|
||||
public String getName(){
|
||||
if(name == null){
|
||||
String[] tmp = path.split("/");
|
||||
name = tmp[tmp.length-1];
|
||||
}
|
||||
String tmp = name.replaceAll("\\{NAME\\}", user.getName());
|
||||
return tmp;
|
||||
}
|
||||
public String getUnModName(){
|
||||
if(name == null)
|
||||
getName();
|
||||
return name;
|
||||
}
|
||||
public User getUser(){
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user){
|
||||
this.user = user;
|
||||
}
|
||||
public String getPath(){
|
||||
String tmp = path.replaceAll("\\{NAME\\}", user.getName());
|
||||
return tmp;
|
||||
}
|
||||
public String getUnModPath(){
|
||||
return path;
|
||||
}
|
||||
public void setName(String name){
|
||||
this.name = name;
|
||||
if( parent.path.endsWith("/") )
|
||||
this.path = parent.path+name;
|
||||
else
|
||||
this.path = parent.path+"/"+name;
|
||||
}
|
||||
public void setParent(Folder parent){
|
||||
if( this.parent != parent ){
|
||||
this.parent = parent;
|
||||
//parent.addSubFolder( this );
|
||||
if( parent.path.endsWith("/") )
|
||||
this.path = parent.path+name;
|
||||
else
|
||||
this.path = parent.path+"/"+name;
|
||||
}
|
||||
}
|
||||
public Folder getParent(){
|
||||
return parent;
|
||||
}
|
||||
|
||||
/*public void addSubFolder(Folder f){
|
||||
if( !subFolders.contains(f) ){
|
||||
subFolders.add( f );
|
||||
f.setParent( this );
|
||||
}
|
||||
}*/
|
||||
|
||||
/*public List<Folder> getSubFolders(){
|
||||
return subFolders;
|
||||
}*/
|
||||
|
||||
public Timestamp getDate(){
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param filename is the name of the file
|
||||
* @param size specifies the size of the image
|
||||
* @return a File object that points to the physical file on the disk,
|
||||
* or null if the user or the filename is null
|
||||
*/
|
||||
public File getFile(String filename, Image.Size size){
|
||||
// Zallery not initialized.
|
||||
while( Zallery.DATA_PATH.isEmpty() ){
|
||||
logger.warning("Zallery not initialized or DATA_PATH not set!");
|
||||
try{Thread.sleep(100);}catch(Exception e){}
|
||||
}
|
||||
|
||||
if( user == null || filename == null )
|
||||
return null;
|
||||
StringBuilder tmp = new StringBuilder();
|
||||
tmp.append( Zallery.DATA_PATH );
|
||||
if( tmp.charAt(tmp.length()-1) != File.separatorChar )
|
||||
tmp.append( File.separatorChar );
|
||||
|
||||
tmp.append( size.toString() );
|
||||
//tmp.append( File.separatorChar );
|
||||
//tmp.append( user.getId() );
|
||||
if( path.charAt(0) != '/' )
|
||||
tmp.append( File.separatorChar );
|
||||
|
||||
String tmp_path = path.replaceAll("\\{NAME\\}", ""+user.getId());
|
||||
tmp_path = tmp_path.replaceAll("/", Matcher.quoteReplacement(File.separator));
|
||||
tmp.append( tmp_path );
|
||||
// check if folder exists or else create it
|
||||
File folder = new File(tmp.toString());
|
||||
if( !folder.exists() )
|
||||
if( !folder.mkdirs() ){
|
||||
logger.warning("Unable to create new folders: '"+folder+"'");
|
||||
throw new RuntimeException("Unable to create new folders: '"+folder+"'");
|
||||
}
|
||||
// Add the filename
|
||||
if( tmp.charAt(tmp.length()-1) != File.separatorChar )
|
||||
tmp.append( File.separatorChar );
|
||||
tmp.append(filename);
|
||||
logger.finest( "File path: "+tmp.toString() );
|
||||
return new File(tmp.toString());
|
||||
}
|
||||
|
||||
public static Folder genRoot(){
|
||||
Folder root = new Folder();
|
||||
root.parent = null;
|
||||
root.path = "/";
|
||||
return root;
|
||||
}
|
||||
|
||||
public boolean isEmpty(DBConnection db) throws SQLException {
|
||||
return Folder.loadSubFolders(db, this.getId()).isEmpty() && Media.load(db, this).isEmpty();
|
||||
}
|
||||
}
|
||||
112
src/zall/bean/Image.java
Normal file
112
src/zall/bean/Image.java
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
package zall.bean;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.db.bean.DBBeanSQLResultHandler;
|
||||
import zutil.db.bean.DBBean.*;
|
||||
import zutil.image.ImageUtil;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
@DBTable(value="Image", superBean=true)
|
||||
public class Image extends Media{
|
||||
private static final Logger logger = LogUtil.getLogger();
|
||||
public static final String type = "image";
|
||||
|
||||
@DBLinkTable(table="Comments", beanClass=Comment.class, idColumn="image")
|
||||
private LinkedList<Comment> comments;
|
||||
|
||||
/**
|
||||
* Loads all the Images from a folder
|
||||
*/
|
||||
public static List<Image> loadFolder(DBConnection db, Folder folder) throws SQLException{
|
||||
if( folder == null || folder.getId() == null )
|
||||
return new LinkedList<Image>();
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Image WHERE folder=? ORDER BY date DESC");
|
||||
sql.setLong(1, folder.getId() );
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(Image.class, db));
|
||||
}
|
||||
public static Image load(DBConnection db, long id) throws SQLException{
|
||||
return DBBean.load(db, Image.class, id);
|
||||
}
|
||||
|
||||
|
||||
public Image(){
|
||||
super();
|
||||
comments = new LinkedList<Comment>();
|
||||
}
|
||||
|
||||
public LinkedList<Comment> getComments() {
|
||||
return comments;
|
||||
}
|
||||
public void addComment(Comment cm){
|
||||
comments.add( cm );
|
||||
}
|
||||
|
||||
public void setFile(FileItem item) throws Exception{
|
||||
if( folder == null )
|
||||
throw new Exception("Folder not set for image!");
|
||||
// Generate unique filename
|
||||
filename = genFileName( item.getName() );
|
||||
filename += ".png";
|
||||
File file = folder.getFile( filename, Size.ORIGINAL );
|
||||
|
||||
// Move uploaded file
|
||||
item.write( file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file for the image, and generates an thumbnail if there is no thumbnail
|
||||
*
|
||||
* @param size is the size of the image
|
||||
*/
|
||||
public File getFile(Size size) throws IOException{
|
||||
if( filename != null ){
|
||||
switch( size ){
|
||||
case ORIGINAL:
|
||||
return folder.getFile( filename, Size.ORIGINAL );
|
||||
default:
|
||||
File file = folder.getFile( filename, size );
|
||||
File orgFile = folder.getFile( filename, Size.ORIGINAL );
|
||||
if( !file.exists() ){
|
||||
if(orgFile.exists() && orgFile.canRead() ){
|
||||
// Generate new thumbnail
|
||||
BufferedImage original = ImageIO.read( orgFile );
|
||||
BufferedImage image = null;
|
||||
switch( size ){
|
||||
case SMALL:
|
||||
image = ImageUtil.cropScale(original, 125, 125);
|
||||
break;
|
||||
case MEDIUM:
|
||||
image = ImageUtil.scale(original, 500, 375, true);
|
||||
break;
|
||||
}
|
||||
ImageIO.write(image, "png", file);
|
||||
}
|
||||
else if( !orgFile.exists() )
|
||||
logger.severe("Original image file missing: \""+file.getAbsolutePath()+"\"");
|
||||
else if( orgFile.canRead() )
|
||||
logger.severe("Can not read original image file: \""+file.getAbsolutePath()+"\"");
|
||||
}
|
||||
return file;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
134
src/zall/bean/Media.java
Normal file
134
src/zall/bean/Media.java
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
package zall.bean;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
|
||||
import zutil.Hasher;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
public abstract class Media extends DBBean implements Comparable<Media>{
|
||||
private static final Logger logger = LogUtil.getLogger();
|
||||
|
||||
public static enum Size{
|
||||
ORIGINAL, MEDIUM, SMALL
|
||||
}
|
||||
|
||||
protected Folder folder;
|
||||
protected String filename;
|
||||
/** owner */
|
||||
protected User user;
|
||||
protected String title;
|
||||
protected String description;
|
||||
protected Timestamp date;
|
||||
protected float rating;
|
||||
|
||||
|
||||
/**
|
||||
* Loads all the media in a folder
|
||||
*/
|
||||
public final static List<Media> load(DBConnection db, Folder folder) throws SQLException{
|
||||
List<Image> image = Image.loadFolder(db, folder);
|
||||
List<Video> video = Video.loadFolder(db, folder);
|
||||
|
||||
List<Media> media = new LinkedList<Media>();
|
||||
media.addAll(image);
|
||||
media.addAll(video);
|
||||
Collections.sort( media );
|
||||
return media;
|
||||
}
|
||||
|
||||
public static Media load(DBConnection db, String type, long id) throws SQLException{
|
||||
if( type.equals(Image.type) )
|
||||
return Image.load(db, id);
|
||||
else if( type.equals(Video.type) )
|
||||
return Video.load(db, id);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public Media(){
|
||||
setCurrentDate();
|
||||
}
|
||||
|
||||
|
||||
public String getFilename() {
|
||||
return filename;
|
||||
}
|
||||
public Folder getFolder() {
|
||||
return folder;
|
||||
}
|
||||
public void setFolder(Folder folder) {
|
||||
this.folder = folder;
|
||||
}
|
||||
public void setImageUrl(String filename) {
|
||||
this.filename = filename;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
public void setDescription(String desc) {
|
||||
this.description = desc;
|
||||
}
|
||||
public Timestamp getDate() {
|
||||
return date;
|
||||
}
|
||||
public void setDate(Timestamp date) {
|
||||
this.date = date;
|
||||
}
|
||||
public void setCurrentDate() {
|
||||
this.date = new Timestamp( System.currentTimeMillis() );
|
||||
}
|
||||
|
||||
public String genFileName(String str){
|
||||
return Hasher.MD5( ""+this.getId()+str+user.getName()+date.getTime()+System.currentTimeMillis() );
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int compareTo(Media m) {
|
||||
return this.date.compareTo( m.date );
|
||||
}
|
||||
|
||||
public abstract LinkedList<Comment> getComments();
|
||||
public abstract void addComment(Comment cm);
|
||||
|
||||
public abstract void setFile(FileItem item) throws Exception;
|
||||
|
||||
public abstract File getFile(Size size) throws IOException;
|
||||
|
||||
public abstract String getType();
|
||||
|
||||
public void delete(DBConnection db) throws SQLException{
|
||||
super.delete(db);
|
||||
for( Size s : Size.values() )
|
||||
try {
|
||||
this.getFile(s).delete();
|
||||
logger.finer("Removed media(id: "+this.getId()+") file(size: "+s+")");
|
||||
} catch (IOException e) {
|
||||
logger.log(Level.SEVERE, "Can not delete \""+s+"\" file!", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
310
src/zall/bean/User.java
Normal file
310
src/zall/bean/User.java
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
package zall.bean;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import zall.Zallery;
|
||||
import zutil.Hasher;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.db.bean.DBBeanSQLResultHandler;
|
||||
import zutil.db.bean.DBBean.*;
|
||||
import zutil.db.handler.SimpleSQLHandler;
|
||||
|
||||
@DBTable("User")
|
||||
public class User extends DBBean{
|
||||
public enum AuthType{
|
||||
USER_INPUT, COOKIE, FACEBOOK
|
||||
}
|
||||
public static final long SESSION_TIMEOUT = 1000*60*60*24*3; // 3day ttl
|
||||
|
||||
protected String name;
|
||||
protected String email;
|
||||
protected boolean emailVerified;
|
||||
protected String password;
|
||||
protected String facebookUid;
|
||||
// Date
|
||||
protected Timestamp loginDate;
|
||||
protected transient Timestamp prevLoginDate;
|
||||
// security
|
||||
protected transient AuthType authBy;
|
||||
protected String sessionId;
|
||||
protected String ipHost;
|
||||
protected String sessionHash;
|
||||
|
||||
protected boolean superUser;
|
||||
protected boolean enabled;
|
||||
|
||||
|
||||
public static User load(DBConnection db, Long id) throws SQLException{
|
||||
return load(db, User.class, id);
|
||||
}
|
||||
|
||||
public static List<User> load(DBConnection db) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM User");
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(User.class, db));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Uses normal user and password to get user object,
|
||||
* this function will save the bean
|
||||
*
|
||||
* @param db is the DB connection
|
||||
* @param email is the email of the user
|
||||
* @param password is the password of the user
|
||||
* @param request is the HTTP request object
|
||||
* @return The user object or null if non where found
|
||||
* @throws SQLException
|
||||
*/
|
||||
public static User load(HttpServletRequest request, HttpServletResponse response, DBConnection db, String email, String password ) throws SQLException{
|
||||
if( password==null || password.isEmpty() || password.equalsIgnoreCase("null"))
|
||||
return null;
|
||||
PreparedStatement sql = db.getPreparedStatement(
|
||||
"SELECT * FROM User WHERE email=? AND password=? LIMIT 1");
|
||||
sql.setString(1, email);
|
||||
sql.setString(2, Hasher.MD5( password ));
|
||||
|
||||
User user = DBConnection.exec(sql, DBBeanSQLResultHandler.create(User.class, db));
|
||||
if( user != null ){
|
||||
user.registerOnHost(request, response, db, true );
|
||||
user.save(db);
|
||||
user.setAuthBy( AuthType.USER_INPUT );
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
public static List<User> loadSuperUsers(DBConnection db) throws SQLException {
|
||||
PreparedStatement sql = db.getPreparedStatement(
|
||||
"SELECT * FROM User WHERE superUser=1");
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(User.class, db));
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses a cookie value to get the user object,
|
||||
* this function will save the bean
|
||||
*
|
||||
* @param db is the DB connection
|
||||
* @param hash is the cookie hash
|
||||
* @param request is the HTTP request object
|
||||
* @return The user object or null if non where found
|
||||
* @throws SQLException
|
||||
*/
|
||||
public static User loadByCookie(HttpServletRequest request, DBConnection db, String hash ) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement(
|
||||
"SELECT * FROM User WHERE sessionHash=? LIMIT 1");
|
||||
sql.setString(1, hash);
|
||||
|
||||
User user = DBConnection.exec(sql, DBBeanSQLResultHandler.create(User.class, db));
|
||||
if( user != null &&
|
||||
user.ipHost.equals( request.getLocalName() ) &&
|
||||
user.loginDate.getTime()+SESSION_TIMEOUT > System.currentTimeMillis() ){
|
||||
user.prevLoginDate = user.loginDate;
|
||||
user.loginDate = new Timestamp( System.currentTimeMillis() );
|
||||
user.save(db);
|
||||
user.setAuthBy( AuthType.COOKIE );
|
||||
return user;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses Facebook user id to get a user object,
|
||||
* this function will save the bean
|
||||
*
|
||||
* @param db is the DB connection
|
||||
* @param uid is the Facebook UID(user id)
|
||||
* @return The user object or null if non where found
|
||||
*/
|
||||
public static User loadByFacebook(HttpServletRequest request, HttpServletResponse response, DBConnection db, String uid ) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement(
|
||||
"SELECT * FROM User WHERE facebookUid=? LIMIT 1");
|
||||
sql.setString(1, uid);
|
||||
|
||||
User user = DBConnection.exec(sql, DBBeanSQLResultHandler.create(User.class, db));
|
||||
if( user != null ){
|
||||
user.registerOnHost(request, response, db, false);
|
||||
user.save(db);
|
||||
user.setAuthBy( AuthType.FACEBOOK );
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
public static boolean emailExists(String email, DBConnection db) throws SQLException{
|
||||
PreparedStatement sql = db.getPreparedStatement(
|
||||
"SELECT * FROM User WHERE email=? LIMIT 1");
|
||||
sql.setString(1, email);
|
||||
|
||||
String tmp = DBConnection.exec(sql, new SimpleSQLHandler<String>());
|
||||
return tmp != null;
|
||||
}
|
||||
|
||||
|
||||
public User(){
|
||||
// Default values
|
||||
emailVerified = false;
|
||||
superUser = false;
|
||||
enabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the User to the Host machine that sent the request,
|
||||
* this method alters the bean, so a call to save() is recommended
|
||||
*
|
||||
* @param db is the DB connection
|
||||
* @param request is the request from the Host/Client
|
||||
* @throws SQLException
|
||||
*/
|
||||
public void registerOnHost(HttpServletRequest request, HttpServletResponse response, DBConnection db, boolean cookie) throws SQLException{
|
||||
prevLoginDate = loginDate;
|
||||
loginDate = new Timestamp( System.currentTimeMillis() );
|
||||
sessionId = request.getSession().getId();
|
||||
ipHost = request.getLocalName();
|
||||
sessionHash = Hasher.MD5( ""+sessionId+ipHost+loginDate+password );
|
||||
if( cookie ){
|
||||
Cookie c = new Cookie("sessionHash", sessionHash );
|
||||
c.setMaxAge(5*24*60*60); // 5 days
|
||||
response.addCookie( c );
|
||||
}
|
||||
}
|
||||
|
||||
public void logout(HttpServletResponse response) {
|
||||
Cookie cookie = new Cookie( "sessionHash", null);
|
||||
cookie.setMaxAge( 0 );
|
||||
response.addCookie( cookie );
|
||||
}
|
||||
|
||||
|
||||
public boolean valid(HttpServletRequest request){
|
||||
if( !this.isEnabled() ) return false;
|
||||
switch( authBy ){
|
||||
case USER_INPUT:
|
||||
if( !this.isEmailVerified() ) return false;
|
||||
case COOKIE:
|
||||
return ( sessionHash.equals( Zallery.getCookieValue(request.getCookies(), "sessionHash")) ||
|
||||
loginDate.getTime()+1000 > System.currentTimeMillis() ) &&
|
||||
ipHost.equals( request.getLocalName() ) &&
|
||||
loginDate.getTime()+SESSION_TIMEOUT > System.currentTimeMillis();
|
||||
case FACEBOOK:
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public boolean verifyEmail(String hash) {
|
||||
return emailVerified = getEmailVerificationHash().equals(hash);
|
||||
}
|
||||
public String getEmailVerificationHash(){
|
||||
return Hasher.MD5( "##helloWorld-->2011"+email+name+password );
|
||||
}
|
||||
|
||||
|
||||
public Timestamp getLoginDate() {
|
||||
if( loginDate == null )
|
||||
loginDate = new Timestamp(0);
|
||||
return loginDate;
|
||||
}
|
||||
public void setLoginDate(Timestamp loginDate) {
|
||||
this.loginDate = loginDate;
|
||||
}
|
||||
public Timestamp getPrevLoginDate() {
|
||||
if( loginDate == null )
|
||||
loginDate = new Timestamp(0);
|
||||
return prevLoginDate;
|
||||
}
|
||||
public void setPrevLoginDate(Timestamp prevLoginDate) {
|
||||
this.prevLoginDate = prevLoginDate;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email) {
|
||||
if( this.email != null && this.email.equals(email) )
|
||||
return;
|
||||
emailVerified = false;
|
||||
this.email = email;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = Hasher.MD5( password );
|
||||
}
|
||||
public boolean equalsPassword( String pass ){
|
||||
return Hasher.MD5( pass ).equals( password );
|
||||
}
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
public void setSessionId(String sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
}
|
||||
public String getIpHost() {
|
||||
return ipHost;
|
||||
}
|
||||
public void setIpHost(String ipHost) {
|
||||
this.ipHost = ipHost;
|
||||
}
|
||||
public String getSessionHash() {
|
||||
return sessionHash;
|
||||
}
|
||||
public void setFacebookUid(String uid) {
|
||||
facebookUid = uid;
|
||||
}
|
||||
public String getFacebookUid(){
|
||||
return facebookUid;
|
||||
}
|
||||
public boolean isSuperUser(){
|
||||
return superUser;
|
||||
}
|
||||
public void setSuperUser(boolean superuser){
|
||||
this.superUser = superuser;
|
||||
}
|
||||
public boolean isEnabled(){
|
||||
return enabled;
|
||||
}
|
||||
public void setEnabled(boolean enabled){
|
||||
this.enabled = enabled;
|
||||
}
|
||||
public boolean isEmailVerified(){
|
||||
return emailVerified;
|
||||
}
|
||||
public void setEmailVerified(boolean verified){
|
||||
this.emailVerified = verified;
|
||||
}
|
||||
public void setAuthBy(AuthType authBy){
|
||||
this.authBy = authBy;
|
||||
}
|
||||
public AuthType getAuthBy(){
|
||||
return authBy;
|
||||
}
|
||||
|
||||
public boolean equals(User u){
|
||||
return u != null && this.getId() == u.getId();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return true if the specified user can edit the media
|
||||
*/
|
||||
public boolean canEdit(Media target) {
|
||||
return target != null && (this.isSuperUser() || target.getUser().equals(this));
|
||||
}
|
||||
public boolean canEdit(Folder target) {
|
||||
return target != null && (this.isSuperUser() || this.equals( target.getUser() ));
|
||||
}
|
||||
public boolean canEdit(User target){
|
||||
return this.equals( target ) || this.superUser;
|
||||
}
|
||||
}
|
||||
114
src/zall/bean/Video.java
Normal file
114
src/zall/bean/Video.java
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package zall.bean;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
|
||||
import zall.ZalleryTranscoder;
|
||||
import zutil.db.DBConnection;
|
||||
import zutil.db.bean.DBBean;
|
||||
import zutil.db.bean.DBBeanSQLResultHandler;
|
||||
import zutil.db.bean.DBBean.*;
|
||||
import zutil.io.file.FileUtil;
|
||||
|
||||
@DBTable(value="Video", superBean = true)
|
||||
public class Video extends Media{
|
||||
public static final String type = "video";
|
||||
|
||||
/** The progress of a transcoding in %, 0 if there is no transcoding running **/
|
||||
protected transient int transcodingProgress;
|
||||
/** If the Video is transcoded **/
|
||||
protected boolean transcoded;
|
||||
/** the time length of the video in seconds **/
|
||||
protected long length;
|
||||
|
||||
|
||||
@DBLinkTable(table="Comments", beanClass=Comment.class, idColumn="video")
|
||||
private LinkedList<Comment> comments;
|
||||
|
||||
/**
|
||||
* Loads all the Videos from a folder
|
||||
*/
|
||||
public static List<Video> loadFolder(DBConnection db, Folder folder) throws SQLException{
|
||||
if( folder == null || folder.getId() == null )
|
||||
return new LinkedList<Video>();
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Video WHERE folder=? ORDER BY date DESC");
|
||||
sql.setLong(1, folder.getId() );
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(Video.class, db));
|
||||
}
|
||||
public static List<Video> loadUntransoded(DBConnection db) throws SQLException {
|
||||
PreparedStatement sql = db.getPreparedStatement("SELECT * FROM Video WHERE transcoded=0 ORDER BY date DESC");
|
||||
return DBConnection.exec(sql, DBBeanSQLResultHandler.createList(Video.class, db));
|
||||
}
|
||||
public static Video load(DBConnection db, long id) throws SQLException{
|
||||
return DBBean.load(db, Video.class, id);
|
||||
}
|
||||
|
||||
|
||||
public Video(){
|
||||
super();
|
||||
transcoded = false;
|
||||
comments = new LinkedList<Comment>();
|
||||
}
|
||||
|
||||
public boolean isTranscoded(){
|
||||
return transcoded;
|
||||
}
|
||||
|
||||
public void setTranscoded(boolean transcoded){
|
||||
this.transcoded = transcoded;
|
||||
}
|
||||
|
||||
public void setTranscodingProgress(int trans){
|
||||
transcodingProgress = trans;
|
||||
}
|
||||
|
||||
public int getTranscodingProgress(){
|
||||
return transcodingProgress;
|
||||
}
|
||||
|
||||
public LinkedList<Comment> getComments() {
|
||||
return comments;
|
||||
}
|
||||
public void addComment(Comment cm){
|
||||
comments.add( cm );
|
||||
}
|
||||
|
||||
public void setFile(FileItem item) throws Exception{
|
||||
if( folder == null )
|
||||
throw new Exception("Folder not set for Video!");
|
||||
// Generate unique filename
|
||||
filename = this.genFileName( item.getName() );
|
||||
filename += "."+FileUtil.getFileExtension( item.getName() );
|
||||
// Move uploaded file
|
||||
item.write( folder.getFile( filename, Size.ORIGINAL ) );
|
||||
item.delete();
|
||||
ZalleryTranscoder.addVideo( this );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file for the video
|
||||
*
|
||||
* @param size is the size of the image
|
||||
*/
|
||||
public File getFile(Size size) throws IOException{
|
||||
if( filename != null ){
|
||||
if( size == Size.SMALL )
|
||||
return folder.getFile( FileUtil.changeExtension(filename,"png"), size );
|
||||
else if( size == Size.MEDIUM )
|
||||
return folder.getFile( FileUtil.changeExtension(filename,"mp4"), size );
|
||||
else
|
||||
return folder.getFile( filename, size );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
97
src/zall/util/Email.java
Normal file
97
src/zall/util/Email.java
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package zall.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import sun.net.smtp.SmtpClient;
|
||||
|
||||
/**
|
||||
* Simplifies sending of a email
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
public class Email {
|
||||
public static enum ContentType{
|
||||
PLAIN, HTML
|
||||
}
|
||||
private static final SimpleDateFormat dateFormatter =
|
||||
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
|
||||
private static String host = "localhost";
|
||||
|
||||
private String from;
|
||||
private String niceFrom = null;
|
||||
private String to;
|
||||
private String replyTo = null;
|
||||
private ContentType type = ContentType.PLAIN;
|
||||
private String subject;
|
||||
private String message;
|
||||
|
||||
public Email(String from, String to){
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
}
|
||||
|
||||
|
||||
public void setFrom(String f){
|
||||
from = f;
|
||||
}
|
||||
public void setNiceFrom(String nf){
|
||||
niceFrom = nf;
|
||||
}
|
||||
public void setReplyTo(String rpt){
|
||||
replyTo = rpt;
|
||||
}
|
||||
public void setTo(String t){
|
||||
to = t;
|
||||
}
|
||||
public void setContentType(ContentType t){
|
||||
type = t;
|
||||
}
|
||||
public void setSubject(String s){
|
||||
subject = s;
|
||||
}
|
||||
public void setMessage(String msg){
|
||||
message = msg;
|
||||
}
|
||||
public static void setServer(String host){
|
||||
Email.host = host;
|
||||
}
|
||||
|
||||
|
||||
public void send() throws IOException{
|
||||
if(from == null)
|
||||
throw new IllegalArgumentException("From value missing!");
|
||||
if(to == null)
|
||||
throw new IllegalArgumentException("To value missing!");
|
||||
|
||||
SmtpClient smtp = new SmtpClient( host );
|
||||
smtp.from(from);
|
||||
smtp.to(to);
|
||||
PrintStream msg = smtp.startMessage();
|
||||
|
||||
//************ Headers
|
||||
msg.println("From: "+(niceFrom!=null ? "\""+niceFrom+"\"" : "")+" <"+from+">");
|
||||
msg.println("Reply-To: <"+replyTo+">");
|
||||
if( replyTo != null )
|
||||
msg.println("Reply-To: <"+replyTo+">");
|
||||
msg.println("To: " + to); // so mailers will display the To: address
|
||||
msg.println("Subject: "+subject);
|
||||
// Date
|
||||
msg.println("Date: "+dateFormatter.format(new Date(System.currentTimeMillis())));
|
||||
// Content type
|
||||
switch( type ){
|
||||
case HTML:
|
||||
msg.println("Content-Type: text/html;"); break;
|
||||
default:
|
||||
msg.println("Content-Type: text/plain;"); break;
|
||||
}
|
||||
msg.println();
|
||||
|
||||
//*********** Mesasge
|
||||
msg.println( message );
|
||||
|
||||
smtp.closeServer();
|
||||
}
|
||||
}
|
||||
121
src/zall/util/facebook/FBUser.java
Normal file
121
src/zall/util/facebook/FBUser.java
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
package zall.util.facebook;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import zutil.io.IOUtil;
|
||||
import zutil.log.LogUtil;
|
||||
import zutil.parser.DataNode;
|
||||
import zutil.parser.json.JSONParser;
|
||||
|
||||
/**
|
||||
* This class represent a Facebook user
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
public class FBUser {
|
||||
private static Logger logger = LogUtil.getLogger();
|
||||
|
||||
/** This is the connection to Facebook **/
|
||||
private FacebookConnect fbc;
|
||||
/** the user id of this user */
|
||||
private String uid;
|
||||
|
||||
/* User data */
|
||||
private String name;
|
||||
private String email;
|
||||
private String birthday;
|
||||
private String gender;
|
||||
private String relationship_status;
|
||||
private String website;
|
||||
private int timezone;
|
||||
private String locale;
|
||||
|
||||
|
||||
public FBUser( FacebookConnect fbc, String uid ){
|
||||
this.fbc = fbc;
|
||||
this.uid = uid;
|
||||
|
||||
load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the data of the user in this object
|
||||
*/
|
||||
public void load(){
|
||||
try {
|
||||
InputStream stream = fbc.getServiceURL( uid ).openStream();
|
||||
String data = IOUtil.getContent( stream );
|
||||
JSONParser jp = new JSONParser();
|
||||
DataNode node = jp.read( data );
|
||||
|
||||
logger.finer("User("+uid+") data from Facebook: "+data);
|
||||
|
||||
if( node.get("name") != null )
|
||||
name = node.get("name").getString();
|
||||
if( node.get("email") != null )
|
||||
email = node.get("email").getString();
|
||||
if( node.get("birthday") != null )
|
||||
birthday = node.get("birthday").getString();
|
||||
if( node.get("gender") != null )
|
||||
gender = node.get("gender").getString();
|
||||
if( node.get("relationship_status") != null )
|
||||
relationship_status = node.get("relationship_status").getString();
|
||||
if( node.get("website") != null )
|
||||
website = node.get("website").getString();
|
||||
if( node.get("timezone") != null )
|
||||
timezone = node.get("timezone").getInt();
|
||||
if( node.get("locale") != null )
|
||||
locale = node.get("locale").getString();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The unique user id on Facebook
|
||||
*/
|
||||
public String getUID(){
|
||||
return uid;
|
||||
}
|
||||
|
||||
|
||||
public String getName(){
|
||||
return name;
|
||||
}
|
||||
public String getEmail(){
|
||||
return email;
|
||||
}
|
||||
public String getBirthday(){
|
||||
return birthday;
|
||||
}
|
||||
public String getGender(){
|
||||
return gender;
|
||||
}
|
||||
public String getRelationshipStatus(){
|
||||
return relationship_status;
|
||||
}
|
||||
public String getWebsite(){
|
||||
return website;
|
||||
}
|
||||
public int getTimezone(){
|
||||
return timezone;
|
||||
}
|
||||
public String getLocale(){
|
||||
return locale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an instance of the given UID user class
|
||||
*
|
||||
* @param uid is the id of the user
|
||||
* @return a cached FBUser object or a new one if its not cached
|
||||
*/
|
||||
public static FBUser get( FacebookConnect fbc, String uid ){
|
||||
if( uid == null )
|
||||
return null;
|
||||
return new FBUser( fbc, uid );
|
||||
}
|
||||
}
|
||||
206
src/zall/util/facebook/FacebookConnect.java
Normal file
206
src/zall/util/facebook/FacebookConnect.java
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
package zall.util.facebook;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import zutil.Hasher;
|
||||
import zutil.log.LogUtil;
|
||||
import zutil.parser.Base64Decoder;
|
||||
import zutil.parser.DataNode;
|
||||
import zutil.parser.json.JSONParser;
|
||||
|
||||
/**
|
||||
* This class connects to Facebook and
|
||||
* retrieves information about the user
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
public class FacebookConnect {
|
||||
private static Logger logger = LogUtil.getLogger();
|
||||
|
||||
/** The URL to the Facebook OpenGraph service. (must end with a '/') **/
|
||||
public static final String SERVICE_URL = "https://graph.facebook.com/";
|
||||
|
||||
/** The application id for this application generated by Facebook **/
|
||||
protected static String application_id = null;
|
||||
/** The application secret for this application generated by Facebook **/
|
||||
protected static String application_secret = null;
|
||||
|
||||
|
||||
protected String access_token;
|
||||
protected FBUser user;
|
||||
|
||||
private FacebookConnect( String access_token, String uid ){
|
||||
this.access_token = access_token;
|
||||
user = FBUser.get( this, uid );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the main user
|
||||
*/
|
||||
public FBUser getUser(){
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given user by UID
|
||||
*
|
||||
* @param uid is the user id of the user
|
||||
* @return a FBUser object or null if there is no such user
|
||||
*/
|
||||
public FBUser getUser(String uid){
|
||||
return FBUser.get( this, uid );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The access token for this session
|
||||
*/
|
||||
protected String getAccessToken(){
|
||||
return access_token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a url for calling the Facebook OpenGraph API
|
||||
*
|
||||
* @param page is the page ex. a UID
|
||||
* @return A URL to the service
|
||||
* @throws MalformedURLException
|
||||
*/
|
||||
protected URL getServiceURL(String page) throws MalformedURLException{
|
||||
return getServiceURL(page, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a url for calling the Facebook OpenGraph API
|
||||
*
|
||||
* @param page is the page ex. a UID
|
||||
* @param params is URL parameters ex. "?name=lol" or "&name=lol&lol=name" or "name=lol" etc...
|
||||
* @return A URL to the service
|
||||
* @throws MalformedURLException
|
||||
*/
|
||||
protected URL getServiceURL(String page, String params) throws MalformedURLException{
|
||||
StringBuilder url = new StringBuilder( SERVICE_URL );
|
||||
url.append( page );
|
||||
url.append( '?' );
|
||||
url.append( "access_token=" );
|
||||
url.append( access_token );
|
||||
|
||||
if( params != null && !params.isEmpty() ){
|
||||
if( params.charAt(0) == '?' )
|
||||
params = params.substring( 1 );
|
||||
if( params.charAt(0) != '&' )
|
||||
url.append( '&' );
|
||||
|
||||
url.append( params );
|
||||
}
|
||||
return new URL( url.toString() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the static values for this application
|
||||
* @param id is the application id for this application generated by Facebook
|
||||
* @param secret is the application secret for this application generated by Facebook
|
||||
*/
|
||||
public static void setApplicationID(String id, String secret){
|
||||
application_id = id;
|
||||
application_secret = secret;
|
||||
}
|
||||
|
||||
public static String getAplicationId() {
|
||||
return application_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of the FacebookConnect for the logged in user
|
||||
* or null if the creation was unsuccessful.
|
||||
*
|
||||
* @param cookies is the cookies from the client
|
||||
* @return A new FacebookConnect object or null if the creation was unsuccessful
|
||||
*/
|
||||
public static FacebookConnect getConnection( Cookie[] cookies ){
|
||||
if( cookies == null ){
|
||||
logger.severe("Cookie is not set!");
|
||||
return null;
|
||||
}
|
||||
|
||||
String cookie_name = "fbsr_" + application_id;
|
||||
// Find the cookie
|
||||
for(Cookie cookie : cookies) {
|
||||
if ( cookie_name.equals(cookie.getName()) ){
|
||||
// remove the trailing "
|
||||
String value = cookie.getValue();
|
||||
return getConnection( value );
|
||||
}
|
||||
}
|
||||
System.out.println("Facebook Nothing here!");
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of the FacebookConnect for the logged in user
|
||||
* or null if the creation was unsuccessful.
|
||||
*
|
||||
* @param value is the string value from facebook
|
||||
* @return A new FacebookConnect object or null if the creation was unsuccessful
|
||||
*/
|
||||
public static FacebookConnect getConnection( String value ){
|
||||
if( application_id == null ){
|
||||
logger.severe("Application_id is not set!");
|
||||
return null;
|
||||
}
|
||||
if( application_secret == null ){
|
||||
logger.severe("Application_secret is not set!");
|
||||
return null;
|
||||
}
|
||||
|
||||
value = value.trim();
|
||||
if( value.isEmpty() )
|
||||
return null;
|
||||
value = value.replaceAll("-", "+");
|
||||
value = value.replaceAll("_", "/");
|
||||
|
||||
// Parse the attributes
|
||||
String[] attrib = value.split("\\.", 2);
|
||||
String signature = Base64Decoder.decodeToHex( attrib[0] );
|
||||
System.out.println( signature );
|
||||
attrib[1] = Base64Decoder.addPadding( attrib[1] );
|
||||
String data = Base64Decoder.decode( attrib[1] );
|
||||
JSONParser json = new JSONParser();
|
||||
DataNode map = json.read( data );
|
||||
System.out.println(map);
|
||||
|
||||
if ( !map.getString("algorithm").equalsIgnoreCase("HMAC-SHA256") ) {
|
||||
logger.severe("Unknown algorithm: '"+map.getString("algorithm")+"' Expected 'HMAC-SHA256'");
|
||||
return null;
|
||||
}
|
||||
// Check hash signature
|
||||
String local_sig = Hasher.HMAC_SHA256( attrib[1], application_secret );
|
||||
System.out.println(local_sig);
|
||||
if ( !signature.equals( local_sig )) {
|
||||
logger.severe("Bad Signed JSON signature: '"+signature+"' Expected '"+local_sig+"'");
|
||||
return null;
|
||||
}
|
||||
|
||||
//if( map.containsKey( "access_token" ) )
|
||||
// return new FacebookConnect( map.get( "access_token" ), map.get( "uid" ) );
|
||||
//return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method remove the cookie from the user by setting the MaxAge to -1
|
||||
*
|
||||
* @param response is the response that the cookie will be added to
|
||||
*/
|
||||
public void logout(HttpServletResponse response) {
|
||||
Cookie cookie = new Cookie( "fbsr_" + application_id, null);
|
||||
cookie.setMaxAge( 0 );
|
||||
cookie.setPath("/");
|
||||
response.addCookie( cookie );
|
||||
}
|
||||
|
||||
}
|
||||
24
src/zall/util/msg/AjaxUserMessageServlet.java
Normal file
24
src/zall/util/msg/AjaxUserMessageServlet.java
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package zall.util.msg;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* This class reads a get request and returns all messages
|
||||
* to that user as JSON.
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
public class AjaxUserMessageServlet extends HttpServlet{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Ajax request
|
||||
*/
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
147
src/zall/util/msg/UserMessage.java
Normal file
147
src/zall/util/msg/UserMessage.java
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
package zall.util.msg;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import zutil.log.LogUtil;
|
||||
|
||||
/**
|
||||
* This class represents all the messages to a single user.
|
||||
* The class is implemented as an Iterator.
|
||||
*
|
||||
* <XMP>
|
||||
* Example HTML:
|
||||
*
|
||||
<SCRIPT type="text/javascript">
|
||||
jQuery(document).ready(function(){
|
||||
jQuery(".message").click(function(){
|
||||
jQuery(this).animate({
|
||||
opacity: 0
|
||||
}, 300).animate({
|
||||
height: 0,
|
||||
border: 0
|
||||
}, 300, function(){
|
||||
jQuery(this).css("display","none");
|
||||
});
|
||||
});
|
||||
});
|
||||
</SCRIPT>
|
||||
<div class="menu">
|
||||
<div class="message" style="border: 2px solid #E6E600; padding: 0px; margin: 5px; background: #FFFF99 none repeat scroll 0%; font-size: 11px; color: black; border-radius: 7px;">
|
||||
<center><b>Warning:</b></center>
|
||||
</div>
|
||||
<div class="message" style="border: 2px solid #FF0000; padding: 0px; margin: 5px; background: #FFDDCC none repeat scroll 0%; font-size: 11px; color: black; border-radius: 7px;">
|
||||
<center><b>Error:</b></center>
|
||||
</div>
|
||||
<div class="message" style="border: 2px solid #039C00; padding: 0px; margin: 5px; background: #9BFB66 none repeat scroll 0%; font-size: 11px; color: black; border-radius: 7px;">
|
||||
<center><b>Info:</b></center>
|
||||
</div>
|
||||
</div>
|
||||
*
|
||||
* </XMP>
|
||||
*
|
||||
* @author Ziver
|
||||
*/
|
||||
public class UserMessage{
|
||||
public static final Logger logger = LogUtil.getLogger();
|
||||
public static final String SESSION_USERMESSAGE_KEY = "AJAX_USER_MESSAGES";
|
||||
|
||||
/**
|
||||
* Is the different types of messages
|
||||
*/
|
||||
public enum MessageType{
|
||||
ERROR, WARNING, INFO
|
||||
}
|
||||
/**
|
||||
* This class represents a single message to a user
|
||||
*/
|
||||
protected class Message{
|
||||
MessageType type;
|
||||
String msg;
|
||||
}
|
||||
/** is the queue that contains the messages **/
|
||||
private Queue<Message> msg_queue;
|
||||
/** is the current message **/
|
||||
private Message current;
|
||||
|
||||
|
||||
public UserMessage(){
|
||||
msg_queue = new LinkedList<Message>();
|
||||
}
|
||||
|
||||
//******** Queue methods
|
||||
|
||||
/**
|
||||
* Adds a new message to the queue
|
||||
*
|
||||
* @param type is the type of the message
|
||||
* @param msg is the message itself
|
||||
*/
|
||||
public void add(MessageType type, String msg){
|
||||
Message m = new Message();
|
||||
m.type = type;
|
||||
m.msg = msg;
|
||||
msg_queue.add( m );
|
||||
logger.finer("Queueing(Size: "+msg_queue.size()+") user message: "+type+"= \""+msg+"\"");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return if there is more messages in the queue
|
||||
*/
|
||||
public boolean hasNext(){
|
||||
return msg_queue.size() != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls a new message from the Queue
|
||||
*
|
||||
* @return if the poll was successful
|
||||
*/
|
||||
public boolean next(){
|
||||
boolean tmp = hasNext();
|
||||
current = msg_queue.poll();
|
||||
return tmp;
|
||||
}
|
||||
|
||||
public int size(){
|
||||
return msg_queue.size();
|
||||
}
|
||||
|
||||
public void clear(){
|
||||
msg_queue.clear();
|
||||
}
|
||||
|
||||
//******** Message Methods
|
||||
|
||||
/**
|
||||
* @return the type of the current message
|
||||
*/
|
||||
public MessageType getType(){
|
||||
return current.type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the message of the current one
|
||||
*/
|
||||
public String getMessage(){
|
||||
return current.msg;
|
||||
}
|
||||
|
||||
//******** Static methods
|
||||
|
||||
public static UserMessage getUserMessage(HttpSession session){
|
||||
if( session.getAttribute(SESSION_USERMESSAGE_KEY) == null ){
|
||||
UserMessage msg = new UserMessage();
|
||||
msg.setSession( session );
|
||||
return msg;
|
||||
}
|
||||
return (UserMessage) session.getAttribute(SESSION_USERMESSAGE_KEY);
|
||||
}
|
||||
|
||||
public void setSession(HttpSession session) {
|
||||
session.setAttribute(SESSION_USERMESSAGE_KEY, this);
|
||||
}
|
||||
}
|
||||
1441
src/zall/util/test/Converter.java
Normal file
1441
src/zall/util/test/Converter.java
Normal file
File diff suppressed because it is too large
Load diff
10
src/zall/util/test/FacebookTester.java
Normal file
10
src/zall/util/test/FacebookTester.java
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
package zall.util.test;
|
||||
|
||||
import zall.util.facebook.FacebookConnect;
|
||||
|
||||
public class FacebookTester {
|
||||
public static void main(String[] args){
|
||||
FacebookConnect.setApplicationID("110543555676926", "5b2dd75314a2fd58b080b06a19b55713");
|
||||
FacebookConnect.getConnection("rZtSPvnBVqNi8hnjJuIffghIvQdq56yaLh1FiP-KybQ.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImNvZGUiOiJBUUJnR3ZtNzVfLXIyVU9iSU4wdnJ4N2pMYVRicVpLdVprdE1xQXVWMHBxUjZMcGkzTDJXVEtYV3BxQmJ5MjByX1pnSFo1dDJLX3lGTENFRTJ3Sko1ek8tbHU2Z3Eyb2xfaDB4WGNneW9OTHNRODBsR2tpMG1hVFdSV083a2VfOUlPb0puYkVqajVSdnhyYW03UW9DOHRkRUEtS2NRZE1DUmptd1kzeHNSNFVsUDBuOE9fblFLa1RUbldYNjY0XzR5UEUiLCJpc3N1ZWRfYXQiOjEzMzU3OTQ4MDcsInVzZXJfaWQiOiIxMTg3MDk1NTIyIn0");
|
||||
}
|
||||
}
|
||||
174
src/zall/util/test/Transcoder.java
Normal file
174
src/zall/util/test/Transcoder.java
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
package zall.util.test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import com.xuggle.mediatool.IMediaReader;
|
||||
import com.xuggle.mediatool.IMediaWriter;
|
||||
import com.xuggle.mediatool.MediaListenerAdapter;
|
||||
import com.xuggle.mediatool.MediaToolAdapter;
|
||||
import com.xuggle.mediatool.ToolFactory;
|
||||
import com.xuggle.mediatool.event.IAddStreamEvent;
|
||||
import com.xuggle.mediatool.event.IVideoPictureEvent;
|
||||
import com.xuggle.mediatool.event.VideoPictureEvent;
|
||||
import com.xuggle.xuggler.Configuration;
|
||||
import com.xuggle.xuggler.ICodec;
|
||||
import com.xuggle.xuggler.IContainer;
|
||||
import com.xuggle.xuggler.IStream;
|
||||
import com.xuggle.xuggler.IStreamCoder;
|
||||
import com.xuggle.xuggler.IVideoPicture;
|
||||
import com.xuggle.xuggler.IVideoResampler;
|
||||
|
||||
public class Transcoder {
|
||||
public static void main(String[] args){
|
||||
File originalFile = new File( "C:\\Users\\Ziver\\Desktop\\Downloads\\test2.mp4" );
|
||||
File mediumFile = new File( "C:\\Users\\Ziver\\Desktop\\Downloads\\temp\\test2_medium.mp4" );
|
||||
File smallFile = new File( "C:\\Users\\Ziver\\Desktop\\Downloads\\temp\\test2_small.png" );
|
||||
|
||||
///////////// Start Transcoding
|
||||
// create a media reader
|
||||
IMediaReader reader = ToolFactory.makeReader( originalFile.getPath() );
|
||||
reader.open();
|
||||
|
||||
// create a media writer
|
||||
IMediaWriter mediaWriter = ToolFactory.makeWriter(mediumFile.getPath(), reader);
|
||||
// add a writer to the reader, to create the output file
|
||||
reader.addListener(mediaWriter);
|
||||
|
||||
mediaWriter.addListener(new Resizer(450, 295));
|
||||
mediaWriter.addListener(new CodecChanger());
|
||||
mediaWriter.addListener(new ProgressListener(reader.getContainer()));
|
||||
|
||||
// create a media viewer with stats enabled for debugging
|
||||
//IMediaViewer mediaViewer = ToolFactory.makeViewer(true);
|
||||
// add a viewer to the reader, to see the decoded media
|
||||
//reader.addListener(mediaViewer);
|
||||
|
||||
// read and decode packets from the source file and
|
||||
// and dispatch decoded audio and video to the writer
|
||||
while (reader.readPacket() == null);
|
||||
|
||||
// Incomplete transcoding
|
||||
if( reader.isOpen() ){
|
||||
System.out.println("Transcoding incomplete, removing incomplete files!");
|
||||
reader.close();
|
||||
mediumFile.delete();
|
||||
smallFile.delete();
|
||||
}
|
||||
|
||||
System.out.println("Done!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Resizer extends MediaToolAdapter {
|
||||
private Integer width;
|
||||
private Integer height;
|
||||
|
||||
private IVideoResampler videoResampler = null;
|
||||
|
||||
public Resizer(Integer aWidth, Integer aHeight) {
|
||||
this.width = aWidth;
|
||||
this.height = aHeight;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onVideoPicture(IVideoPictureEvent event) {
|
||||
IVideoPicture pic = event.getPicture();
|
||||
if (videoResampler == null) {
|
||||
videoResampler = IVideoResampler.make(width, height, pic.getPixelType(), pic.getWidth(), pic
|
||||
.getHeight(), pic.getPixelType());
|
||||
}
|
||||
IVideoPicture out = IVideoPicture.make(pic.getPixelType(), width, height);
|
||||
videoResampler.resample(out, pic);
|
||||
|
||||
IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out, event.getStreamIndex());
|
||||
super.onVideoPicture(asc);
|
||||
out.delete();
|
||||
}
|
||||
}
|
||||
|
||||
class ProgressListener extends MediaToolAdapter {
|
||||
private long currentLength;
|
||||
private long totalLength;
|
||||
|
||||
public ProgressListener(IContainer c) {
|
||||
this.totalLength = c.getDuration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onVideoPicture(IVideoPictureEvent event) {
|
||||
currentLength = event.getTimeStamp();
|
||||
System.out.println(currentLength+" / "+totalLength+" - "+getProgress());
|
||||
}
|
||||
|
||||
public long getProcessedLength(){
|
||||
return currentLength;
|
||||
}
|
||||
|
||||
public long getTotalLength(){
|
||||
return totalLength;
|
||||
}
|
||||
|
||||
public int getProgress(){
|
||||
return (int)(((double)currentLength/totalLength)*100);
|
||||
}
|
||||
}
|
||||
|
||||
class CodecChanger extends MediaListenerAdapter {
|
||||
/*
|
||||
* HTML5
|
||||
* video codec - avc1.42E01E i.e. H.264/MPEG-4 AVC
|
||||
* audio codec - mp4a.40.2 i.e. MPEG-4 AAC LC
|
||||
*/
|
||||
|
||||
|
||||
public void onAddStream(IAddStreamEvent event) {
|
||||
// put your stream specific configuration code here
|
||||
// you can get the container from the writer and
|
||||
// get the specific stream from the container using
|
||||
// the stream index in the event
|
||||
int streamIndex = event.getStreamIndex();
|
||||
IStream stream = event.getSource().getContainer().getStream(streamIndex);
|
||||
ICodec.Type codecType = stream.getStreamCoder().getCodecType();
|
||||
|
||||
if(codecType == ICodec.Type.CODEC_TYPE_AUDIO){
|
||||
applyAudioSettings(stream);
|
||||
} else {
|
||||
applyVideoSettings(stream);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyVideoSettings(IStream stream) {
|
||||
IStreamCoder coder = stream.getStreamCoder();
|
||||
coder.setCodec(ICodec.ID.CODEC_ID_H264);
|
||||
coder.setBitRate( 500000 );
|
||||
|
||||
//IVideoResampler.make(outWidth, outHeight, outContainer.getPixelType(), inContainer.getWidth(), inContainer.getHeight(), inContainer.getPixelType());
|
||||
}
|
||||
|
||||
private void applyAudioSettings(IStream stream) {
|
||||
IStreamCoder coder = stream.getStreamCoder();
|
||||
// ICodec.ID.CODEC_ID_MP3
|
||||
coder.setCodec( ICodec.ID.CODEC_ID_AAC );
|
||||
//coder.setSampleRate( 44000 );
|
||||
coder.setBitRate( 128 );
|
||||
|
||||
//IAudioResampler.make(out.getChannels(), in.getChannels(), out.getSampleRate(), in.getSampleRate());
|
||||
}
|
||||
}
|
||||
|
||||
class SetVideoTranscodeListener extends MediaToolAdapter {
|
||||
@Override
|
||||
public void onAddStream(IAddStreamEvent event) {
|
||||
int streamIndex = event.getStreamIndex();
|
||||
IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
|
||||
|
||||
if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
|
||||
streamCoder.setCodec(ICodec.findEncodingCodec(ICodec.ID.CODEC_ID_H264));
|
||||
int retval = Configuration.configure("/usr/local/xuggler/share/ffmpeg/libx264-superfast.ffpreset", streamCoder);
|
||||
if (retval<0)
|
||||
throw new RuntimeException("cound not cofigure coder from preset file");
|
||||
}
|
||||
super.onAddStream(event);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue