From f89b15833089c9f4076e9a7592eae1c3c92ec36b Mon Sep 17 00:00:00 2001 From: Pierre-Luc Paour Date: Fri, 18 Jun 2010 15:37:31 +0000 Subject: [PATCH] Initial commit of GR3, probably very broken. I'll move to GIT soon, promise :-) --- build.xml | 27 - com/gallery/GalleryRemote/CoreUtils.java | 4 +- com/gallery/GalleryRemote/GRApplet.java | 9 +- com/gallery/GalleryRemote/GRAppletMini.java | 22 +- com/gallery/GalleryRemote/GRScreenSaver.java | 138 -- com/gallery/GalleryRemote/GalleryComm.java | 276 +-- com/gallery/GalleryRemote/GalleryComm2.java | 1676 ----------------- com/gallery/GalleryRemote/GalleryComm2_5.java | 186 -- com/gallery/GalleryRemote/GalleryComm3.java | 329 ++++ .../GalleryRemote/GalleryCommTest.java | 35 + com/gallery/GalleryRemote/GalleryRemote.java | 2 +- .../GalleryRemoteScreenSaver.java | 253 --- com/gallery/GalleryRemote/MainFrame.java | 44 +- com/gallery/GalleryRemote/NewAlbumDialog.java | 6 +- .../GalleryRemote/PictureInspector.java | 4 +- com/gallery/GalleryRemote/SlideshowFrame.java | 8 +- com/gallery/GalleryRemote/model/Album.java | 63 +- com/gallery/GalleryRemote/model/Gallery.java | 391 +--- .../GalleryRemote/model/GalleryItem.java | 85 +- com/gallery/GalleryRemote/model/Picture.java | 8 +- .../prefs/GalleryEditorDialog.java | 176 +- .../GalleryRemote/prefs/PreferenceNames.java | 12 +- com/gallery/GalleryRemote/prefs/URLPanel.java | 15 +- .../GalleryRemote/prefs/panes.properties | 4 +- .../resources/GRResources.properties | 22 - .../GalleryRemote/util/ImageUtils.java | 2 +- .../GalleryRemote/util/PostChangeLog.java | 209 -- 27 files changed, 588 insertions(+), 3418 deletions(-) delete mode 100644 com/gallery/GalleryRemote/GRScreenSaver.java delete mode 100644 com/gallery/GalleryRemote/GalleryComm2.java delete mode 100644 com/gallery/GalleryRemote/GalleryComm2_5.java create mode 100644 com/gallery/GalleryRemote/GalleryComm3.java create mode 100644 com/gallery/GalleryRemote/GalleryCommTest.java delete mode 100644 com/gallery/GalleryRemote/GalleryRemoteScreenSaver.java delete mode 100644 com/gallery/GalleryRemote/util/PostChangeLog.java diff --git a/build.xml b/build.xml index 3887962..0348c95 100644 --- a/build.xml +++ b/build.xml @@ -294,13 +294,6 @@ tofile="${install}/staging/GalleryRemote.${version}.Win32.NoVM.exe"/> - - - - - @@ -317,26 +310,6 @@ tofile="${install}/staging/GalleryRemote.${version}.Win32.NoVM.exe"/> description="Run all the tasks for a nightly build" /> - - - - - - - - - - - - - - - - - - - Property nsis.path not found. Please copy diff --git a/com/gallery/GalleryRemote/CoreUtils.java b/com/gallery/GalleryRemote/CoreUtils.java index f29c381..9ac59d8 100644 --- a/com/gallery/GalleryRemote/CoreUtils.java +++ b/com/gallery/GalleryRemote/CoreUtils.java @@ -195,8 +195,8 @@ public Component getListCellRendererComponent( } } - if (p.getCaption() != null && getIcon() != null) { - text.append("

").append(p.getEscapedCaption()).append("

"); + if (p.getDescription() != null && getIcon() != null) { + text.append("

").append(p.getEscapedDescription()).append("

"); } text.append(""); diff --git a/com/gallery/GalleryRemote/GRApplet.java b/com/gallery/GalleryRemote/GRApplet.java index 5091f6f..2ba68c1 100644 --- a/com/gallery/GalleryRemote/GRApplet.java +++ b/com/gallery/GalleryRemote/GRApplet.java @@ -10,9 +10,6 @@ import java.net.MalformedURLException; import java.util.Locale; -import HTTPClient.CookieModule; -import HTTPClient.Cookie; - /** * Created by IntelliJ IDEA. * User: paour @@ -202,7 +199,7 @@ protected AppletInfo getGRAppletInfo() { if (urlFull == null) { // old versions of Gallery, or bad urlFull info.gallery.setType(Gallery.TYPE_STANDALONE); - info.gallery.setStUrlString(url); + info.gallery.setUrlString(url); } info.gallery.setUserAgent(userAgent); @@ -216,7 +213,7 @@ protected AppletInfo getGRAppletInfo() { } info.slideshowFrom = slideshowFrom; - CookieModule.discardAllCookies(); + /*CookieModule.discardAllCookies(); if (cookieName != null) { Cookie cookie = new Cookie(cookieName, cookieValue, cookieDomain, cookiePath, null, false); Log.log(Log.LEVEL_TRACE, MODULE, "Adding cookie: " + cookie); @@ -231,7 +228,7 @@ protected AppletInfo getGRAppletInfo() { Log.log(Log.LEVEL_TRACE, MODULE, "Adding cookie: " + cookie1); CookieModule.addCookie(cookie1); cookieNum++; - } + }*/ return info; } diff --git a/com/gallery/GalleryRemote/GRAppletMini.java b/com/gallery/GalleryRemote/GRAppletMini.java index cbdee7e..ede56e1 100644 --- a/com/gallery/GalleryRemote/GRAppletMini.java +++ b/com/gallery/GalleryRemote/GRAppletMini.java @@ -7,7 +7,6 @@ import com.gallery.GalleryRemote.util.GRI18n; import com.gallery.GalleryRemote.util.DialogUtil; import com.gallery.GalleryRemote.prefs.PreferenceNames; -import com.gallery.GalleryRemote.util.OsShutdown; import javax.swing.*; import javax.swing.event.DocumentListener; @@ -181,23 +180,6 @@ public void setInProgress(boolean inProgress) { jThumbnails.setEnabled(!inProgress); this.inProgress = inProgress; - - if (! inProgress && hasHadPictures) { - // probably finished uploading... - try { - // no update for G2 and for embedded applets (non-embedded applets are TYPE_STANDALONE) - if (! (gallery.getComm(null) instanceof GalleryComm2_5) && gallery.getType() != Gallery.TYPE_APPLET) { - getAppletContext().showDocument(new URL(getCodeBase().toString() + "add_photos_refresh.php"), "hack"); - } - - // use Java to Javascript scripting - g2Feedback("doneUploading", new Object[] {}); - } catch (MalformedURLException e) { - Log.logException(Log.LEVEL_ERROR, MODULE, e); - } - - hasHadPictures = false; - } } public void addPictures(File[] files, int index, boolean select) { @@ -417,7 +399,7 @@ public void textUpdate(DocumentEvent e) { if (p != null) { if (e.getDocument() == jCaption.getDocument()) { - p.setCaption(jCaption.getText()); + p.setDescription(jCaption.getText()); } else { Iterator i = jExtrafields.iterator(); while (i.hasNext()) { @@ -449,7 +431,7 @@ public void valueChanged(ListSelectionEvent e) { jExtrafield.setBackground(UIManager.getColor("TextField.inactiveBackground")); } } else { - jCaption.setText(p.getCaption()); + jCaption.setText(p.getDescription()); jCaption.setEditable(true); jCaption.setBackground(UIManager.getColor("TextField.background")); diff --git a/com/gallery/GalleryRemote/GRScreenSaver.java b/com/gallery/GalleryRemote/GRScreenSaver.java deleted file mode 100644 index b797d1c..0000000 --- a/com/gallery/GalleryRemote/GRScreenSaver.java +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) 2004-2005 Sun Microsystems, Inc. All rights reserved. Use is -// subject to license terms. -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the Lesser GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -// USA - -package com.gallery.GalleryRemote; - -import org.jdesktop.jdic.screensaver.SimpleScreensaver; - -import java.awt.*; - -import com.gallery.GalleryRemote.util.ImageLoaderUtil; -import com.gallery.GalleryRemote.util.HTMLEscaper; -import com.gallery.GalleryRemote.prefs.PreferenceNames; - -/** - * Screensaver that shows a Gallery slideshow - * - * @author Pierre-Luc Paour - */ -public class GRScreenSaver - extends SimpleScreensaver implements PreferenceNames { - public static final String MODULE = "ScreenSaver"; - String coreClass = "com.gallery.GalleryRemote.GalleryRemoteScreenSaver"; - boolean hasStarted = false; - GalleryRemoteScreenSaver grss; - int paintPass = 0; - int thickness = 1; - - /** - * Initialize this screen saver - */ - public void init() { - if (!hasStarted) { - GalleryRemote.createInstance(coreClass, null); - hasStarted = true; - grss = (GalleryRemoteScreenSaver) GalleryRemote._().getCore(); - grss.setContext(getContext()); - GalleryRemote._().initializeGR(); - - thickness = GalleryRemote._().properties.getIntProperty(SLIDESHOW_FONTTHICKNESS, 1); - } - } - - /** - * Paint the next frame - */ - public void paint(Graphics g) { - //Log.log(Log.LEVEL_TRACE, MODULE, "Paint"); - if (paintPass < 10) { - paintPass++; - - Component c = getContext().getComponent(); - ImageLoaderUtil.setSlideshowFont(c); - g.setFont(c.getFont()); - String message = grss.hasSettings?"Preparing slideshow...":"Please pick the Settings for your Gallery"; - - int width = (int) c.getBounds().getWidth(); - int height = (int) c.getBounds().getHeight(); - ImageLoaderUtil.paintAlignedOutline( - g, - message, - width / 2, - height / 2, - thickness, - 20, - width); - - return; - } - - if (grss.newImage) { - /*if (firstPaint) { - firstPaint = false; - Component c = getContext().getComponent(); - ImageLoaderUtil.setSlideshowFont(c); - g.setFont(c.getFont()); - }*/ - - grss.newImage = false; - - Log.log(Log.LEVEL_TRACE, MODULE, "Really Paint!"); - Component c = getContext().getComponent(); - Image img = grss.loader.imageShowNow; - - int width = (int) c.getBounds().getWidth(); - int height = (int) c.getBounds().getHeight(); - int dx = (width - img.getWidth(c)) / 2; - int dy = (height - img.getHeight(c)) / 2; - g.drawImage(img, dx, dy, c); - - g.setColor(GalleryRemote._().properties.getColorProperty(PreferenceNames.SLIDESHOW_COLOR)); - g.fillRect(0, 0, dx, height); - g.fillRect(width - dx, 0, width, height); - g.fillRect(dx, 0, width - dx, dy); - g.fillRect(dx, height - dy, width - dx, height); - - String caption = - ImageLoaderUtil.stripTags(HTMLEscaper.unescape(grss.loader.pictureShowNow.getCaption())); - - if (caption != null && caption.length() != 0) { - ImageLoaderUtil.paintAlignedOutline( - g, - caption, - width / 2, - height - 10, - thickness, - 30, - width); - } - } - } - - public void destroy() { - GalleryRemote._().getCore().shutdown(); - - // for the screensaver, it makes sense to keep the temp files around, they'll come useful again... - //ImageUtils.purgeTemp(); - - Log.log(Log.LEVEL_INFO, MODULE, "Shutting down log"); - Log.shutdown(); - - super.destroy(); - } -} diff --git a/com/gallery/GalleryRemote/GalleryComm.java b/com/gallery/GalleryRemote/GalleryComm.java index 3fae2ef..8662737 100644 --- a/com/gallery/GalleryRemote/GalleryComm.java +++ b/com/gallery/GalleryRemote/GalleryComm.java @@ -21,25 +21,32 @@ package com.gallery.GalleryRemote; -import HTTPClient.*; import com.gallery.GalleryRemote.model.Album; import com.gallery.GalleryRemote.model.Picture; import com.gallery.GalleryRemote.model.Gallery; -import com.gallery.GalleryRemote.prefs.GalleryProperties; import com.gallery.GalleryRemote.prefs.PreferenceNames; -import com.gallery.GalleryRemote.util.GRI18n; +import org.apache.http.HttpException; +import org.apache.http.HttpRequest; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.ProxySelectorRoutePlanner; +import org.apache.http.impl.conn.SingleClientConnManager; +import org.apache.http.protocol.HTTP; +import org.apache.http.protocol.HttpContext; +import org.apache.http.protocol.RequestUserAgent; -import javax.swing.*; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; import javax.net.ssl.TrustManager; -import java.awt.*; import java.io.IOException; +import java.net.ProxySelector; import java.net.URL; -import java.net.UnknownHostException; +import java.security.NoSuchAlgorithmException; import java.util.StringTokenizer; -import java.util.Properties; /** * This interface is a temporary mechanism to let us use version @@ -60,6 +67,10 @@ public abstract class GalleryComm implements PreferenceNames { protected boolean isLoggedIn = false; protected boolean triedLogin = false; + DefaultHttpClient httpclient; + Gallery g; + StatusUpdate su; + /* ------------------------------------------------------------------------- * STATIC INITIALIZATON */ @@ -68,20 +79,6 @@ public abstract class GalleryComm implements PreferenceNames { /* Enable customized AuthorizePopup */ AuthorizePopup.enable(); - /* Configures HTTPClient to accept all cookies - * this should be done at least once per GalleryRemote - * invokation */ - CookieModule.setCookiePolicyHandler(new CookiePolicyHandler() { - public boolean acceptCookie(Cookie cookie, RoRequest req, RoResponse resp) { - Log.log(Log.LEVEL_TRACE, MODULE, "Accepting cookie: " + cookie); - return true; - } - - public boolean sendCookie(Cookie cookie, RoRequest req) { - Log.log(Log.LEVEL_TRACE, MODULE, "Sending cookie: " + cookie); - return true; - } - }); // http://cvs.sourceforge.net/viewcvs.py/jameleon/jameleon/src/java/net/sf/jameleon/util/JsseSettings.java?rev=1.4&view=markup // http://tp.its.yale.edu/pipermail/cas/2004-March/000348.html @@ -113,11 +110,48 @@ public void checkServerTrusted( } } + protected GalleryComm(Gallery g, StatusUpdate su) { + if (g == null) { + throw new IllegalArgumentException("Must supply a non-null gallery."); + } + + this.g = g; + this.su = su; + + SingleClientConnManager cm = null; + + if (g.getUrl().getProtocol().equals("https")) { + try { + SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(new Scheme("https", sf, 443)); + cm = new SingleClientConnManager(schemeRegistry); + } catch (NoSuchAlgorithmException e) { + Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + } + } + + httpclient = new DefaultHttpClient(cm); + + ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( + httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); + httpclient.setRoutePlanner(routePlanner); + + httpclient.removeRequestInterceptorByClass(RequestUserAgent.class); + final String ua = g.getUserAgent(); + httpclient.addRequestInterceptor(new HttpRequestInterceptor() { + public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { + request.setHeader(HTTP.USER_AGENT, ua); + } + }); + + } + /** * Causes the GalleryComm instance to upload the pictures in the * associated Gallery to the server. - * - * @param su an instance that implements the StatusUpdate interface. + * @param su an instance of StatusUpdate + * @param async whether to run the action asynchronously */ public void uploadFiles(StatusUpdate su, boolean async) { throw new RuntimeException("This method is not available on this protocol"); @@ -176,7 +210,7 @@ public void incrementViewCount(StatusUpdate su, Picture p) { public void logOut() { Log.log(Log.LEVEL_INFO, MODULE, "Logging out and clearing cookies"); isLoggedIn = false; - CookieModule.discardAllCookies(); + httpclient.getCookieStore().clear(); } public boolean isLoggedIn() { @@ -198,192 +232,8 @@ public static boolean wasAuthFailure() { return lastRespCode == 401; } - public static GalleryComm getCommInstance(StatusUpdate su, URL url, Gallery g) { - try { - GalleryProperties p = GalleryRemote._().properties; - - // set proxy info - String proxyList = System.getProperty("javaplugin.proxy.config.list"); - - String proxyHost = null; - int proxyPort = 80; - String proxyUsername = null; - String proxyPassword = null; - - // Prepare to get info from the plugin in Java 4, 5 or 6 - Class proxyHelperClass = null; - Object proxyHelper; - Class proxyInfoClass = null; - Object proxyInfo = null; - try { - Log.log(Log.LEVEL_TRACE, MODULE, - "Trying Java 5 and 6 proxy class (sun.plugin.net.proxy.PluginAutoProxyHandler)"); - - // this class is not signed by Gallery, so we can't use the secure instantiation - proxyHelperClass = Class.forName("sun.plugin.net.proxy.PluginAutoProxyHandler"); - // this class is not signed by Gallery, so we can't use the secure instantiation - proxyInfoClass = Class.forName("com.sun.deploy.net.proxy.ProxyInfo"); - - proxyHelper = proxyHelperClass.newInstance(); - Object[] proxyInfoArray = (Object[]) proxyHelperClass.getMethod("getProxyInfo", - new Class[] { URL.class }).invoke(proxyHelper, new Object[] { url }); - - if (proxyInfoArray != null && proxyInfoArray.length != 0) { - proxyInfo = proxyInfoArray[0]; - } - } catch (Throwable e) { - Log.log(Log.LEVEL_TRACE, MODULE, "Failed instantiation " + e); - } - - if (proxyHelperClass == null) { - try { - Log.log(Log.LEVEL_TRACE, MODULE, - "Trying Java 4 proxy class (sun.plugin.net.proxy.PluginProxyManager)"); - - // this class is not signed by Gallery, so we can't use the secure instantiation - proxyHelperClass = Class.forName("sun.plugin.net.proxy.PluginProxyManager"); - // this class is not signed by Gallery, so we can't use the secure instantiation - proxyInfoClass = Class.forName("sun.plugin.net.proxy.ProxyInfo"); - - proxyHelper = proxyHelperClass.newInstance(); - proxyInfo = proxyHelperClass.getMethod("getProxyInfo", - new Class[] { URL.class }).invoke(proxyHelper, new Object[] { url }); - } catch (Throwable e) { - Log.log(Log.LEVEL_TRACE, MODULE, "Failed instantiation " + e); - } - } - - if (proxyInfo != null) { - try { - Log.log(Log.LEVEL_TRACE, MODULE, "Got proxy info from Java plugin: " + proxyInfo); - - proxyPort = ((Integer) proxyInfoClass.getMethod("getPort", null).invoke(proxyInfo, null)).intValue(); - - // Plugins 4, 5 and 6 work differently... - try { - proxyHost = (String) proxyInfoClass.getMethod("getProxy", null).invoke(proxyInfo, null); - } catch(NoSuchMethodException e) { - proxyHost = (String) proxyInfoClass.getMethod("getHost", null).invoke(proxyInfo, null); - } - } catch (Throwable e) { - Log.log(Log.LEVEL_TRACE, MODULE, "Failed instantiation" + e); - } - } - - if (proxyHost == null && proxyList != null && proxyList.length() != 0) { - try { - proxyList = proxyList.toUpperCase(); - Log.log(Log.LEVEL_TRACE, MODULE, "Plugin Proxy Config List Property: " + proxyList); - // 6.0.0 1/14/03 1.3.1_06 appears to omit HTTP portion of reported proxy list... Mod to accomodate this... - // Expecting proxyList of "HTTP=XXX.XXX.XXX.XXX:Port" OR "XXX.XXX.XXX.XXX:Port" & assuming HTTP... - - if (proxyList.indexOf("HTTP=") != -1) { - proxyHost = proxyList.substring(proxyList.indexOf("HTTP=")+5, proxyList.indexOf(":")); - } else { - proxyHost = proxyList.substring(0, proxyList.indexOf(":")); - } - int endOfPort = proxyList.indexOf(","); - if (endOfPort < 1) endOfPort = proxyList.length(); - proxyPort = Integer.parseInt(proxyList.substring(proxyList.indexOf(":")+1,endOfPort)); - Log.log(Log.LEVEL_TRACE, MODULE, "proxy " + proxyHost+" port " + proxyPort); - } - catch (Exception e) { - Log.log(Log.LEVEL_TRACE, MODULE, "Exception during failover auto proxy detection" ); - Log.logException(Log.LEVEL_ERROR, MODULE, e); - proxyHost = null; - } - } else if (p.getBooleanProperty(USE_PROXY)) { - proxyHost = p.getProperty(PROXY_HOST); - try { - proxyPort = p.getIntProperty(PROXY_PORT); - } catch (NumberFormatException e) { - } - - proxyUsername = p.getProperty(PROXY_USERNAME); - - if (proxyUsername != null && proxyUsername.length() > 0) { - proxyPassword = p.getBase64Property(PROXY_PASSWORD); - } - } - - if (proxyHost != null) { - Log.log(Log.LEVEL_TRACE, MODULE, "Setting proxy to " + proxyHost + ":" + proxyPort); - - HTTPConnection.setProxyServer(proxyHost, proxyPort); - - if (proxyUsername != null && proxyUsername.length() > 0) { - Log.log(Log.LEVEL_TRACE, MODULE, "Setting proxy auth to " + proxyUsername + ":" + proxyPassword); - AuthorizationInfo.addBasicAuthorization(proxyHost, proxyPort, "", - proxyUsername, proxyPassword); - } - - // also set Java URLConnection proxy - Properties sprops = System.getProperties(); - sprops.setProperty("http.proxySet", "true"); - sprops.setProperty("http.proxyHost", proxyHost); - sprops.setProperty("http.proxyPort", ""+proxyPort); - } else { - HTTPConnection.setProxyServer(null, 0); - Log.log(Log.LEVEL_TRACE, MODULE, "No proxy"); - } - - // create a connection - HTTPConnection mConnection = new HTTPConnection(url); - addUserInfo(url); - String userAgent = g.getUserAgent(); - if (userAgent != null) { - mConnection.setDefaultHeaders(new NVPair[] { new NVPair("User-Agent", userAgent) }); - } - - if (g.getType() == Gallery.TYPE_STANDALONE) { - // assemble the URL - String urlPath = url.getFile(); - - if (g.forceGalleryVersion == 0 || g.forceGalleryVersion == 1) { - Log.log(Log.LEVEL_TRACE, MODULE, "Trying protocol 2 for " + url); - // Test GalleryComm2 - String urlPath2 = urlPath + ((urlPath.endsWith("/")) ? GalleryComm2.SCRIPT_NAME : "/" + GalleryComm2.SCRIPT_NAME); - if (tryComm(su, mConnection, urlPath2, null)) { - Log.log(Log.LEVEL_TRACE, MODULE, "Server has protocol 2"); - return new GalleryComm2(g); - } - } - - if (g.forceGalleryVersion == 0 || g.forceGalleryVersion == 2) { - Log.log(Log.LEVEL_TRACE, MODULE, "Trying protocol 2.5 for " + url); - // Test GalleryComm2 - String urlPath2_5 = urlPath + ((urlPath.endsWith("/")) ? GalleryComm2_5.SCRIPT_NAME : "/" + GalleryComm2_5.SCRIPT_NAME); - StringBuffer sb = new StringBuffer(); - if (tryComm(su, mConnection, urlPath2_5, sb)) { - if (sb != null && sb.indexOf("ERROR_PERMISSION_DENIED") == -1) { - Log.log(Log.LEVEL_TRACE, MODULE, "Server has protocol 2.5"); - return new GalleryComm2_5(g); - } else { - // G2 remote module is deactivated - su.error(GRI18n.getString(MODULE, "g2.moduleDisabled")); - } - } - } - - /*Log.log(Log.LEVEL_TRACE, MODULE, "Trying protocol 1 for " + url); - // Test GalleryComm1 - // BUT: only if first try was not status code 401 = authorization failure - String scriptName = "gallery_remote.php"; - String urlPath1 = urlPath + ((urlPath.endsWith("/")) ? scriptName : "/" + scriptName); - if (lastRespCode != 401 && tryComm(su, mConnection, urlPath1)) { - Log.log(Log.LEVEL_TRACE, MODULE, "Server has protocol 1"); - - // todo: Alert, we don't support protocol 1 any more. - }*/ - } else { - // if Gallery is embedded, only support protocol 2 - return new GalleryComm2(g); - } - } catch (HTTPClient.ProtocolNotSuppException e) { - Log.logException(Log.LEVEL_ERROR, MODULE, e); - } - - return null; + public static GalleryComm getCommInstance(StatusUpdate su, Gallery g) { + return new GalleryComm3(g, su); } public static void addUserInfo(URL url) { @@ -407,7 +257,7 @@ public static void addUserInfo(URL url) { AuthorizePopup.hackPassword = null; } - private static boolean tryComm(StatusUpdate su, HTTPConnection mConnection, String urlPath, StringBuffer content) { + /*private static boolean tryComm(StatusUpdate su, HttpClient mConnection, String urlPath, StringBuffer content) { try { HTTPResponse rsp; @@ -463,5 +313,5 @@ private static boolean tryComm(StatusUpdate su, HTTPConnection mConnection, Stri } return false; - } -} + }*/ +} \ No newline at end of file diff --git a/com/gallery/GalleryRemote/GalleryComm2.java b/com/gallery/GalleryRemote/GalleryComm2.java deleted file mode 100644 index ef75548..0000000 --- a/com/gallery/GalleryRemote/GalleryComm2.java +++ /dev/null @@ -1,1676 +0,0 @@ -/* -* Gallery Remote - a File Upload Utility for Gallery -* -* Gallery - a web based photo album viewer and editor -* Copyright (C) 2000-2001 Bharat Mediratta -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 2 of the License, or (at -* your option) any later version. -* -* This program is distributed in the hope that it will be useful, but -* WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program; if not, write to the Free Software -* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ - -package com.gallery.GalleryRemote; - -import HTTPClient.*; -import com.gallery.GalleryRemote.model.Album; -import com.gallery.GalleryRemote.model.Gallery; -import com.gallery.GalleryRemote.model.Picture; -import com.gallery.GalleryRemote.prefs.GalleryProperties; -import com.gallery.GalleryRemote.prefs.PreferenceNames; -import com.gallery.GalleryRemote.util.GRI18n; -import com.gallery.GalleryRemote.util.HTMLEscaper; -import com.gallery.GalleryRemote.util.UrlMessageDialog; -import com.gallery.GalleryRemote.util.NaturalOrderComparator; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.net.SocketException; -import java.net.URL; -import java.net.MalformedURLException; -import java.util.*; - -/** - * The GalleryComm2 class implements the client side of the Gallery remote - * protocol - * version 2. - * - * @author jackodog - * @author paour - * @author Tim Miller - */ -public class GalleryComm2 extends GalleryComm implements GalleryComm2Consts, - GalleryCommCapabilities, PreferenceNames { - /* Implementation notes: One GalleryComm2 instance is needed per Gallery - * server (since the protocol only logs into each server once). So the - * constructor requires a Gallery instance and is immutable with respect - * to it. - */ - - - /* ------------------------------------------------------------------------- - * CLASS CONSTANTS - */ - - /** Module name for logging. */ - private static final String MODULE = "GalComm2"; - - /** Remote scriptname that provides version 2 of the protocol on the server. */ - public static final String SCRIPT_NAME = "gallery_remote2.php"; - - protected String scriptName = SCRIPT_NAME; - - - /* ------------------------------------------------------------------------- - * INSTANCE VARIABLES - */ - - /** The gallery this GalleryComm2 instance is attached to. */ - protected final Gallery g; - - /** - * The minor revision of the server (2.x) - * Use this to decide whether some functionality - * should be disabled (because the server would not understand. - */ - protected int serverMinorVersion = 0; - - private static int[] capabilities1; - private static int[] capabilities2; - private static int[] capabilities5; - private static int[] capabilities7; - private static int[] capabilities9; - private static int[] capabilities13; - private static int[] capabilities14; - private static int[] capabilities15; - - - /* ------------------------------------------------------------------------- - * CONSTRUCTION - */ - - /** - * Create an instance of GalleryComm2 by supplying an instance of Gallery. - */ - protected GalleryComm2(Gallery g) { - if (g == null) { - throw new IllegalArgumentException("Must supply a non-null gallery."); - } - - this.g = g; - - /* Initialize the capabilities array with what protocol 2.0 supports. - * Once we're logged in and we know what the minor revision of the - * protocol is, we'll be able to add more capabilities, such as - * CAPA_NEW_ALBUM (since 2.1) */ - capabilities = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO}; - capabilities1 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM}; - capabilities2 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE}; - capabilities5 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FORCE_FILENAME}; - capabilities7 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FORCE_FILENAME, CAPA_MOVE_ALBUM}; - capabilities9 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FORCE_FILENAME, CAPA_MOVE_ALBUM, CAPA_FETCH_ALBUM_IMAGES}; - capabilities13 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FORCE_FILENAME, CAPA_MOVE_ALBUM, CAPA_FETCH_ALBUM_IMAGES, - CAPA_FETCH_ALBUMS_TOO, CAPA_FETCH_NON_WRITEABLE_ALBUMS}; - capabilities14 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FORCE_FILENAME, CAPA_MOVE_ALBUM, CAPA_FETCH_ALBUM_IMAGES, - CAPA_FETCH_ALBUMS_TOO, CAPA_FETCH_NON_WRITEABLE_ALBUMS, CAPA_FETCH_HONORS_HIDDEN}; - capabilities15 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FORCE_FILENAME, CAPA_MOVE_ALBUM, CAPA_FETCH_ALBUM_IMAGES, - CAPA_FETCH_ALBUMS_TOO, CAPA_FETCH_NON_WRITEABLE_ALBUMS, CAPA_FETCH_HONORS_HIDDEN, - CAPA_IMAGE_MAX_SIZE}; - - // the algorithm for search needs the ints to be sorted. - Arrays.sort(capabilities); - Arrays.sort(capabilities1); - Arrays.sort(capabilities2); - Arrays.sort(capabilities5); - Arrays.sort(capabilities7); - Arrays.sort(capabilities9); - Arrays.sort(capabilities13); - Arrays.sort(capabilities14); - Arrays.sort(capabilities15); - } - - - /* ------------------------------------------------------------------------- - * PUBLIC INSTANCE METHODS - */ - - /** - * Causes the GalleryComm2 instance to upload the pictures in the - * associated Gallery to the server. - * - * @param su an instance that implements the StatusUpdate interface. - */ - public void uploadFiles(StatusUpdate su, boolean async) { - UploadTask uploadTask = new UploadTask(su); - doTask(uploadTask, async); - } - - /** - * Causes the GalleryComm2 instance to fetch the albums contained by - * associated Gallery from the server. - * - * @param su an instance that implements the StatusUpdate interface. - */ - public void fetchAlbums(StatusUpdate su, boolean async) { - doTask(new AlbumListTask(su), async); - } - - /** - * Causes the GalleryComm2 instance to fetch the album properties - * for the given Album. - * - * @param su an instance that implements the StatusUpdate interface. - */ - public void albumProperties(StatusUpdate su, Album a, boolean async) { - doTask(new AlbumPropertiesTask(su, a), async); - } - - /** - * Causes the GalleryComm instance to create a new album as a child of - * the specified album (or at the root if album is null) - */ - public String newAlbum(StatusUpdate su, Album parentAlbum, - String newAlbumName, String newAlbumTitle, - String newAlbumDesc, boolean async) { - NewAlbumTask newAlbumTask = new NewAlbumTask(su, parentAlbum, newAlbumName, - newAlbumTitle, newAlbumDesc); - doTask(newAlbumTask, async); - - return newAlbumTask.getNewAlbumName(); - } - - public void fetchAlbumImages(StatusUpdate su, Album a, boolean recusive, boolean async, int maxPictures, boolean random) { - FetchAlbumImagesTask fetchAlbumImagesTask = new FetchAlbumImagesTask(su, - a, recusive, maxPictures, random); - doTask(fetchAlbumImagesTask, async); - } - - public boolean moveAlbum(StatusUpdate su, Album a, Album newParent, boolean async) { - MoveAlbumTask moveAlbumTask = new MoveAlbumTask(su, a, newParent); - doTask(moveAlbumTask, async); - - return moveAlbumTask.getSuccess(); - } - - public void login(StatusUpdate su) { - LoginTask loginTask = new LoginTask(su); - doTask(loginTask, false); - } - - /* ------------------------------------------------------------------------- - * UTILITY METHODS - */ - void doTask(GalleryTask task, boolean async) { - if (async) { - Thread t = new Thread(task); - t.start(); - } else { - task.run(); - } - } - - void status(StatusUpdate su, int level, String message) { - Log.log(Log.LEVEL_INFO, MODULE, message); - su.updateProgressStatus(level, message); - } - - void error(StatusUpdate su, String message) { - status(su, StatusUpdate.LEVEL_GENERIC, message); - su.error(message); - } - - void trace(String message) { - Log.log(Log.LEVEL_TRACE, MODULE, message); - } - - - /* ------------------------------------------------------------------------- - * INNER CLASSES - */ - - /** - * This class serves as the base class for each GalleryComm2 task. - */ - abstract class GalleryTask implements Runnable { - StatusUpdate su; - HTTPConnection mConnection; - boolean interrupt = false; - boolean terminated = false; - Thread thread = null; - - public GalleryTask(StatusUpdate su) { - if (su == null) { - this.su = new StatusUpdateAdapter() { - }; - } else { - this.su = su; - } - } - - public void run() { - thread = Thread.currentThread(); - su.setInProgress(true); - if (!isLoggedIn) { - if (!login()) { - Log.log(Log.LEVEL_TRACE, MODULE, "Failed to log in to " + g.toString()); - su.setInProgress(false); - return; - } - - isLoggedIn = true; - } else { - Log.log(Log.LEVEL_TRACE, MODULE, "Still logged in to " + g.toString()); - } - - runTask(); - - cleanUp(); - } - - public void interrupt() { - thread.interrupt(); - interrupt = true; - } - - public void cleanUp() { - su.setInProgress(false); - terminated = true; - } - - abstract void runTask(); - - private boolean login() { - Object[] params = {g.toString()}; - status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "logIn", params)); - - if (g.getType() != Gallery.TYPE_STANDALONE && g.getType() != Gallery.TYPE_APPLET) { - try { - requestResponse(null, null, g.getLoginUrl(scriptName), false, su, this, null); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.getMessage()}; - error(su, GRI18n.getString(MODULE, "errReq", params2)); - } - } - - // setup protocol parameters - String username = g.getUsername(); - String password = g.getPassword(); - - if ((username == null || username.length() == 0) - && ! g.cookieLogin) { - username = (String) JOptionPane.showInputDialog( - GalleryRemote._().getMainFrame(), - GRI18n.getString(MODULE, "usernameLbl"), - GRI18n.getString(MODULE, "username"), - JOptionPane.PLAIN_MESSAGE, - null, - null, - null); - - if (username != null) { - g.setUsername(username); - } - } - - if (username != null && (password == null || password.length() == 0)) { - password = (String) JOptionPane.showInputDialog( - GalleryRemote._().getMainFrame(), - GRI18n.getString(MODULE, "passwdLbl"), - GRI18n.getString(MODULE, "passwd"), - JOptionPane.PLAIN_MESSAGE, - null, - null, - null); - - g.setPassword(password); - } - - NVPair form_data[] = { - new NVPair("cmd", "login"), - new NVPair("protocol_version", PROTOCOL_VERSION), - null, - null - }; - - if (username != null) { - form_data[2] = new NVPair("uname", username); - Log.log(Log.LEVEL_TRACE, MODULE, "login parameters: " + Arrays.asList(form_data)); - form_data[3] = new NVPair("password", password); - } else { - Log.log(Log.LEVEL_TRACE, MODULE, "login parameters: " + Arrays.asList(form_data)); - } - - form_data = fudgeFormParameters(form_data); - - // make the request - try { - triedLogin = true; - - // load and validate the response - Properties p = requestResponse(form_data, null, g.getGalleryUrl(scriptName), true, su, this, true, null); - if (GR_STAT_SUCCESS.equals(p.getProperty("status")) - || GR_STAT_LOGIN_MISSING.equals(p.getProperty("status"))) { - status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "loggedIn")); - try { - String serverVersion = p.getProperty("server_version"); - int i = serverVersion.indexOf("."); - serverMinorVersion = Integer.parseInt(serverVersion.substring(i + 1)); - - Log.log(Log.LEVEL_TRACE, MODULE, "Server minor version: " + serverMinorVersion); - - handleCapabilities(); - } catch (Exception e) { - Log.log(Log.LEVEL_ERROR, MODULE, "Malformed server_version: " + p.getProperty("server_version")); - Log.logException(Log.LEVEL_ERROR, MODULE, e); - } - return true; - } else if (GR_STAT_PASSWD_WRONG.equals(p.getProperty("status"))) { - error(su, GRI18n.getString(MODULE, "usrpwdErr")); - return false; - } else { - Object[] params2 = {p.getProperty("status_text")}; - error(su, GRI18n.getString(MODULE, "loginErr", params2)); - return false; - } - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.getMessage()}; - error(su, GRI18n.getString(MODULE, "errReq", params2)); - } - - return false; - } - } - - class LoginTask extends GalleryTask { - LoginTask(StatusUpdate su) { - super(su); - } - - void runTask() {} - } - - /** - * An extension of GalleryTask to handle uploading photos. - */ - class UploadTask extends GalleryTask { - MyTransferListener transferListener; - - UploadTask(StatusUpdate su) { - super(su); - } - - void runTask() { - ArrayList pictures = g.getAllUploadablePictures(); - - // get total file size - long totalSize = 0; - Iterator iter = pictures.iterator(); - while (iter.hasNext()) { - Picture p = (Picture) iter.next(); - totalSize += p.getFileSize(); - } - - transferListener = new MyTransferListener(su); - transferListener.sizeAllFiles = totalSize; - transferListener.numberAllFiles = pictures.size(); - - su.startProgress(StatusUpdate.LEVEL_UPLOAD_ALL, 0, 100, GRI18n.getString(MODULE, "upPic"), false); - - if (su instanceof UploadProgress) { - ((UploadProgress) su).setCancelListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upStop")); - su.setUndetermined(StatusUpdate.LEVEL_UPLOAD_ALL, true); - interrupt(); - long startTime = System.currentTimeMillis(); - - while (!terminated && System.currentTimeMillis() < startTime + 10000) { - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - } - } - - if (!terminated) { - Log.log(Log.LEVEL_ERROR, "Thread would not terminate properly: killing it"); - thread.stop(); - - // since we killed the thread, it's not going to clean up after itself - cleanUp(); - } - - ((UploadProgress) su).done(); - } - }); - } - - // upload each file, one at a time - boolean allGood = true; - //int uploadedCount = 0; - iter = pictures.iterator(); - while (iter.hasNext() /*&& allGood*/ && !interrupt) { - Picture p = (Picture) iter.next(); - - /*Object[] params = { - p.toString(), - new Integer((uploadedCount + 1)), - new Integer(pictures.size()), - new Integer((int) ((transferListener.sizeFilesDone + transferListener.sizeThisFile) / 1024 / 1024)), - new Integer((int) (transferListener.sizeAllFiles / 1024 / 1024)), - transferListener.getProjectedTimeLeft() - }; - su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upStatus", params));*/ - - allGood = uploadPicture(p, p); - - //su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ALL, ++uploadedCount); - - if (allGood) { - p.getParentAlbum().removePicture(p); - } - } - - if (allGood) { - su.stopProgress(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upComplete")); - - if (su instanceof UploadProgress) { - if (((UploadProgress) su).isShutdown()) { - GalleryRemote._().getCore().shutdown(true); - } - } - - g.setDirty(false); - - GalleryRemote._().getCore().flushMemory(); - } else { - su.stopProgress(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upFailed")); - } - } - - boolean uploadPicture(Picture p, Picture picture) { - try { - boolean utf8 = p.getParentAlbum().getGallery().getGalleryVersion() == 2; - boolean escapeCaptions = !utf8 && GalleryRemote._().properties.getBooleanProperty(HTML_ESCAPE_CAPTIONS); - transferListener.currentFile = p.toString(); - - if (utf8) { - Log.log(Log.LEVEL_INFO, MODULE, "Will upload using UTF-8 for text data"); - } - - status(su, StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upPrep")); - - // can't set null as an NVPair value - String caption = p.getCaption(); - caption = (caption == null) ? "" : caption; - - if (escapeCaptions) { - caption = HTMLEscaper.escape(caption); - } - - // setup the protocol parameters - NVPair[] opts = { - new NVPair("cmd", "add-item"), - new NVPair("protocol_version", PROTOCOL_VERSION), - new NVPair("set_albumName", p.getParentAlbum().getName()), - new NVPair("caption", caption, utf8?"UTF-8":null), - new NVPair("force_filename", p.getSource().getName()), - null - }; - - // set auto-rotate only if we do the rotation in GR, otherwise we'd be overriding the server setting - if (p.getAngle() != 0) { - opts[5] = new NVPair("auto_rotate", "no"); - } - - // set up extra fields - if (p.getExtraFieldsMap() != null && p.getExtraFieldsMap().size() > 0) { - ArrayList optsList = new ArrayList(Arrays.asList(opts)); - - Iterator it = p.getExtraFieldsMap().keySet().iterator(); - while (it.hasNext()) { - String name = (String) it.next(); - String value = p.getExtraField(name); - - if (value != null) { - if (escapeCaptions) { - value = HTMLEscaper.escape(value); - } - - optsList.add(new NVPair("extrafield." + name, value, utf8?"UTF-8":null)); - } - } - - opts = (NVPair[]) optsList.toArray(opts); - } - - Log.log(Log.LEVEL_TRACE, MODULE, "add-item parameters: " + Arrays.asList(opts)); - - // setup the multipart form data - NVPair[] afile = {new NVPair("userfile", p.getUploadSource().getAbsolutePath())}; - NVPair[] hdrs = new NVPair[1]; - byte[] data = Codecs.mpFormDataEncode(fudgeFormParameters(opts), fudgeParameters(afile), hdrs); - - // load and validate the response - Properties props = requestResponse(hdrs, data, g.getGalleryUrl(scriptName), true, su, this, transferListener); - if (props.getProperty("status").equals(GR_STAT_SUCCESS)) { - status(su, StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upSucc")); - String newItemName = props.getProperty("item_name"); - if (newItemName != null) { - su.doneUploading(newItemName, picture); - } - return true; - } else { - Object[] params = {props.getProperty("status_text")}; - error(su, GRI18n.getString(MODULE, "upErr", params)); - return false; - } - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params = {gr2e.getMessage()}; - error(su, p.toString() + ": " + GRI18n.getString(MODULE, "error", params)); - } catch (SocketException swe) { - Log.logException(Log.LEVEL_ERROR, MODULE, swe); - Object[] params = {swe.toString()}; - error(su, p.toString() + ": " + GRI18n.getString(MODULE, "confErr", params)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params = {ioe.toString()}; - error(su, p.toString() + ": " + GRI18n.getString(MODULE, "error", params)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params = {me.getMessage()}; - error(su, p.toString() + ": " + GRI18n.getString(MODULE, "errReq", params)); - } - - return false; - } - } - - /** - * An extension of GalleryTask to handle fetching albums. - */ - class AlbumListTask extends GalleryTask { - - AlbumListTask(StatusUpdate su) { - super(su); - } - - void runTask() { - su.startProgress(StatusUpdate.LEVEL_BACKGROUND, 0, 10, GRI18n.getString(MODULE, "albmFtchng", new Object[] {g.toString()}), true); - - try { - long startTime = System.currentTimeMillis(); - - if (serverMinorVersion < 2) { - list20(); - } else { - list22(); - } - - // tell the tree to reload - g.reload(); - - Log.log(Log.LEVEL_INFO, MODULE, "execution time for AlbumList: " + (System.currentTimeMillis() - startTime)); - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - - su.stopProgress(StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "fetchComplete")); - } - - private void list20() throws IOException, ModuleException { - // setup the protocol parameters - NVPair form_data[] = { - new NVPair("cmd", "fetch-albums"), - new NVPair("protocol_version", PROTOCOL_VERSION) - }; - Log.log(Log.LEVEL_TRACE, MODULE, "fetchAlbums parameters: " + Arrays.asList(form_data)); - - form_data = fudgeFormParameters(form_data); - - // load and validate the response - Properties p = requestResponse(form_data, su, this); - if (p.getProperty("status").equals(GR_STAT_SUCCESS)) { - ArrayList mAlbumList = new ArrayList(); - - // parse and store the data - int albumCount = Integer.parseInt(p.getProperty("album_count")); - - HashMap ref2parKey = new HashMap(); - HashMap ref2album = new HashMap(); - - Album rootAlbum = g.createRootAlbum(); - - for (int i = 1; i < albumCount + 1; i++) { - Album a = new Album(g); - a.setSuppressEvents(true); - - String nameKey = "album.name." + i; - String titleKey = "album.title." + i; - String parentKey = "album.parent." + i; - String permsAddKey = "album.perms.add." + i; - String permsWriteKey = "album.perms.write." + i; - String permsDelItemKey = "album.perms.del_item." + i; - String permsDelAlbKey = "album.perms.del_alb." + i; - String permsCreateSubKey = "album.perms.create_sub." + i; - String infoExtraFieldsKey = "album.info.extrafields." + i; - - a.setCanAdd(isTrue(p.getProperty(permsAddKey))); - a.setCanWrite(isTrue(p.getProperty(permsWriteKey))); - a.setCanDeleteFrom(isTrue(p.getProperty(permsDelItemKey))); - a.setCanDeleteThisAlbum(isTrue(p.getProperty(permsDelAlbKey))); - a.setCanCreateSubAlbum(isTrue(p.getProperty(permsCreateSubKey))); - a.setExtraFieldsString(HTMLEscaper.unescape(p.getProperty(infoExtraFieldsKey))); - - a.setName(p.getProperty(nameKey)); - a.setTitle(HTMLEscaper.unescape(p.getProperty(titleKey))); - - a.setSuppressEvents(false); - mAlbumList.add(a); - - // map album ref nums to albums - ref2album.put("" + i, a); - - // map album refs to parent refs - String parentRefS = p.getProperty(parentKey); - int parentRef = Integer.parseInt(parentRefS); - if (parentRef != 0) { - ref2parKey.put("" + i, parentRefS); - } else { - rootAlbum.add(a); - } - } - - // link albums to parents - for (int i = 1; i < albumCount + 1; i++) { - String parentKey = (String) ref2parKey.get("" + i); - if (parentKey != null) { - Album a = (Album) ref2album.get("" + i); - if (a != null) { - Album pa = (Album) ref2album.get(parentKey); - pa.add(a); - } - } - } - - status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms")); - - //g.setAlbumList(mAlbumList); - } else { - Object[] params = {p.getProperty("status_text")}; - error(su, GRI18n.getString(MODULE, "error", params)); - } - } - - private void list22() throws IOException, ModuleException { - // setup the protocol parameters - NVPair form_data[] = { - new NVPair("cmd", "fetch-albums-prune"), - new NVPair("protocol_version", PROTOCOL_VERSION) - }; - Log.log(Log.LEVEL_TRACE, MODULE, "fetchAlbums parameters: " + Arrays.asList(form_data)); - - form_data = fudgeFormParameters(form_data); - - // load and validate the response - GalleryProperties p = requestResponse(form_data, su, this); - if (p.getProperty("status").equals(GR_STAT_SUCCESS)) { - ArrayList albums = new ArrayList(); - - // parse and store the data - int albumCount = Integer.parseInt(p.getProperty("album_count")); -// System.err.println( "### albumCount = " + albumCount ); - HashMap name2parentName = new HashMap(); - HashMap name2album = new HashMap(); - - Album rootAlbum = g.createRootAlbum(); - - for (int i = 1; i < albumCount + 1; i++) { - Album a = new Album(g); - a.setSuppressEvents(true); - - String nameKey = "album.name." + i; - String titleKey = "album.title." + i; - String parentKey = "album.parent." + i; - String permsAddKey = "album.perms.add." + i; - String permsWriteKey = "album.perms.write." + i; - String permsDelItemKey = "album.perms.del_item." + i; - String permsDelAlbKey = "album.perms.del_alb." + i; - String permsCreateSubKey = "album.perms.create_sub." + i; - String infoExtraFieldKey = "album.info.extrafields." + i; - - a.setCanAdd(isTrue(p.getProperty(permsAddKey))); - a.setCanWrite(isTrue(p.getProperty(permsWriteKey))); - a.setCanDeleteFrom(isTrue(p.getProperty(permsDelItemKey))); - a.setCanDeleteThisAlbum(isTrue(p.getProperty(permsDelAlbKey))); - a.setCanCreateSubAlbum(isTrue(p.getProperty(permsCreateSubKey))); - - String name = p.getProperty(nameKey); - a.setName(name); - a.setTitle(HTMLEscaper.unescape(p.getProperty(titleKey))); - a.setExtraFieldsString(HTMLEscaper.unescape(p.getProperty(infoExtraFieldKey))); - - a.setSuppressEvents(false); - - albums.add(a); - - // map album names to albums - name2album.put(name, a); - - // map album refs to parent refs - String parentName = p.getProperty(parentKey); - - if (parentName == null) { - Log.log(Log.LEVEL_ERROR, MODULE, "Gallery error: the album " + name + - " doesn't have a parent. You should delete it, the album database " + - "is corrupted because of it."); - - } else if (parentName.equals(name)) { - Log.log(Log.LEVEL_ERROR, MODULE, "Gallery error: the album " + name + - " is its own parent. You should delete it, the album database " + - "is corrupted because of it."); - - parentName = null; - } - - if (parentName != null && parentName.length() > 0 && !parentName.equals("0")) { - name2parentName.put(name, parentName); - } else { - rootAlbum.add(a); - } - } - - Log.log(Log.LEVEL_TRACE, MODULE, "Created " + albums.size() + " albums"); - - // link albums to parents - Iterator it = name2parentName.keySet().iterator(); - while (it.hasNext()) { - String name = (String) it.next(); - String parentName = (String) name2parentName.get(name); - Album child = (Album) name2album.get(name); - Album parent = (Album) name2album.get(parentName); - - if (child != null && parent != null) { - parent.add(child); - } - } - - Log.log(Log.LEVEL_TRACE, MODULE, "Linked " + name2parentName.size() + " albums to their parents"); - - // reorder - Collections.sort(albums, new NaturalOrderComparator()); - Collections.reverse(albums); - ArrayList orderedAlbums = new ArrayList(); - int depth = 0; - while (!albums.isEmpty()) { - it = albums.iterator(); - while (it.hasNext()) { - Album a = (Album) it.next(); - - try { - if (a.getAlbumDepth() == depth) { - it.remove(); - a.sortSubAlbums(); - - Album parentAlbum = a.getParentAlbum(); - if (parentAlbum == null) { - orderedAlbums.add(0, a); - } else { - int i = orderedAlbums.indexOf(parentAlbum); - orderedAlbums.add(i + 1, a); - } - } - } catch (IllegalArgumentException e) { - it.remove(); - Log.log(Log.LEVEL_TRACE, MODULE, "Gallery server album list is corrupted: " + - "album " + a.getName() + " has a bad containment hierarchy."); - - /*JOptionPane.showMessageDialog(GalleryRemote.getInstance().mainFrame, - GRI18n.getString(MODULE, "fixCorrupted", new String[] { - a.getTitle(), - a.getGallery().getGalleryUrl(a.getName()).toString()}), - GRI18n.getString(MODULE, "fixCorruptedTitle"), - JOptionPane.ERROR_MESSAGE);*/ - - if (! GalleryRemote._().properties.getBooleanProperty(SUPPRESS_WARNING_CORRUPTED)) { - UrlMessageDialog md = new UrlMessageDialog( - GRI18n.getString(MODULE, "fixCorrupted", new String[] { - a.getTitle(), - a.getGallery().getGalleryUrl(a.getName()).toString()}), - a.getGallery().getGalleryUrl(GRI18n.getString(MODULE, "fixCorruptedUrl", new String[] { - a.getName()} )).toString(), - null); - - if (md.dontShow()) { - GalleryRemote._().properties.setBooleanProperty(SUPPRESS_WARNING_CORRUPTED, true); - } - } - - // This doesn't work: there's a problem with the connection (maybe not re-entrant...) - //if (answer == JOptionPane.YES_OPTION) { - //a.moveAlbumTo(su, null); - //moveAlbum(su, a, null, true); - //} - } - } - - depth++; - } - - rootAlbum.setCanCreateSubAlbum(p.getBooleanProperty("can_create_root", false)); - - Log.log(Log.LEVEL_TRACE, MODULE, "Ordered " + orderedAlbums.size() + " albums"); - - status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms")); - - //g.setAlbumList(orderedAlbums); - } else { - Object[] params = {p.getProperty("status_text")}; - error(su, GRI18n.getString(MODULE, "error", params)); - } - } - } - - /** - * An extension of GalleryTask to handle getting album information. - */ - class AlbumPropertiesTask extends GalleryTask { - Album a; - - AlbumPropertiesTask(StatusUpdate su, Album a) { - super(su); - this.a = a; - } - - void runTask() { - status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "getAlbmInfo", new String[] { a.toString() })); - - try { - // setup the protocol parameters - NVPair form_data[] = { - new NVPair("cmd", "album-properties"), - new NVPair("protocol_version", PROTOCOL_VERSION), - new NVPair("set_albumName", a.getName()) - }; - Log.log(Log.LEVEL_TRACE, MODULE, "album-info parameters: " + Arrays.asList(form_data)); - - form_data = fudgeFormParameters(form_data); - - // load and validate the response - GalleryProperties p = requestResponse(form_data, su, this); - if (p.getProperty("status").equals(GR_STAT_SUCCESS)) { - // parse and store the data - int autoResize = p.getIntProperty("auto_resize"); - int maxSize = p.getIntProperty("max_size", 0); - - // use larger of intermediate and max size - a.setServerAutoResize(autoResize>maxSize?autoResize:maxSize); - - String extrafields = p.getProperty("extrafields"); - a.setExtraFieldsString(extrafields); - - status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "ftchdAlbmProp")); - - } else { - error(su, "Error: " + p.getProperty("status_text")); - } - - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - } - } - - /** - * An extension of GalleryTask to handle creating a new album. - */ - class NewAlbumTask extends GalleryTask { - Album parentAlbum; - String albumName; - String albumTitle; - String albumDesc; - private String newAlbumName; - - NewAlbumTask(StatusUpdate su, Album parentAlbum, String albumName, - String albumTitle, String albumDesc) { - super(su); - this.parentAlbum = parentAlbum; - this.albumName = albumName; - this.albumTitle = albumTitle; - this.albumDesc = albumDesc; - } - - void runTask() { - status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "newAlbm", new Object[] { albumName, g.toString() })); - - boolean escapeCaptions = GalleryRemote._().properties.getBooleanProperty(HTML_ESCAPE_CAPTIONS); - boolean utf8 = !escapeCaptions && parentAlbum.getGallery().getGalleryVersion() == 2; - - if (utf8) { - Log.log(Log.LEVEL_INFO, MODULE, "Will upload using UTF-8 for text data"); - } - - // if the parent is null (top-level album), set the album name to an illegal name so it's set to null - // by Gallery. Using an empty string doesn't work, because then the HTTP parameter is not - // parsed, and the session album is kept the same as before (from the cookie). - String parentAlbumName = (parentAlbum == null) ? "hack_null_albumName" : parentAlbum.getName(); - - if (escapeCaptions) { - albumTitle = HTMLEscaper.escape(albumTitle); - albumDesc = HTMLEscaper.escape(albumDesc); - } - - try { - // setup the protocol parameters - NVPair form_data[] = { - new NVPair("cmd", "new-album"), - new NVPair("protocol_version", PROTOCOL_VERSION), - new NVPair("set_albumName", parentAlbumName), - new NVPair("newAlbumName", albumName), - new NVPair("newAlbumTitle", albumTitle, utf8?"UTF-8":null), - new NVPair("newAlbumDesc", albumDesc, utf8?"UTF-8":null) - }; - - form_data = fudgeFormParameters(form_data); - - Log.log(Log.LEVEL_TRACE, MODULE, "new-album parameters: " + Arrays.asList(form_data)); - - Properties p; - if (utf8) { - // force using mime-multipart so we can use UTF-8 - NVPair[] hdrs = new NVPair[1]; - byte[] data = Codecs.mpFormDataEncode(form_data, new NVPair[0], hdrs); - - // load and validate the response - p = requestResponse(hdrs, data, g.getGalleryUrl(scriptName), true, su, this, null); - } else { - // normal request - p = requestResponse(form_data, su, this); - } - - if (p.getProperty("status").equals(GR_STAT_SUCCESS)) { - status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "crateAlbmOk")); - newAlbumName = p.getProperty("album_name"); - } else { - Object[] params2 = {p.getProperty("status_text")}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - } - - public String getNewAlbumName() { - return newAlbumName; - } - } - - /** - * An extension of GalleryTask to handle getting album information. - */ - class FetchAlbumImagesTask extends GalleryTask { - Album a; - boolean recursive = false; - int maxPictures = 0; - boolean random = false; - - FetchAlbumImagesTask(StatusUpdate su, Album a, boolean recursive, int maxPictures, boolean random) { - super(su); - - this.a = a; - this.recursive = recursive; - this.maxPictures = maxPictures; - this.random = random; - } - - void runTask() { - su.startProgress(StatusUpdate.LEVEL_GENERIC, 0, 10, GRI18n.getString(MODULE, "fetchAlbImages", - new String[]{a.getName()}), true); - - try { - ArrayList newPictures = new ArrayList(); - fetch(a, a.getName(), newPictures); - - a.setHasFetchedImages(true); - boolean isDirty = a.getGallery().isDirty(); - a.addPictures(newPictures); - a.getGallery().setDirty(isDirty); - GalleryRemote._().getCore().preloadThumbnails(newPictures.iterator()); - - su.stopProgress(StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "fetchAlbImagesDone", - new String[]{"" + newPictures.size()})); - } catch (GR2Exception e) { - error(su, GRI18n.getString(MODULE, "error", new String[] {e.getMessage()})); - su.stopProgress(StatusUpdate.LEVEL_GENERIC, e.getMessage()); - } - - } - - private void fetch(Album a, String albumName, ArrayList newPictures) - throws GR2Exception { - su.updateProgressStatus(StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "fetchAlbImages", - new String[]{albumName})); - - try { - // setup the protocol parameters - NVPair[] form_data = new NVPair[] { - new NVPair("cmd", "fetch-album-images"), - new NVPair("protocol_version", PROTOCOL_VERSION), - new NVPair("set_albumName", albumName), - new NVPair("albums_too", recursive?"yes":"no"), - new NVPair("random", random?"yes":"no"), - new NVPair("limit", maxPictures + ""), - new NVPair("extrafields", "yes") - }; - - Log.log(Log.LEVEL_TRACE, MODULE, "fetch-album-images parameters: " + - Arrays.asList(form_data)); - - form_data = fudgeFormParameters(form_data); - - // load and validate the response - GalleryProperties p = requestResponse(form_data, su, this); - if (p.getProperty("status").equals(GR_STAT_SUCCESS)) { - // parse and store the data - int numImages = p.getIntProperty("image_count"); - String baseUrl = p.getProperty("baseurl"); - - try { - if (baseUrl == null) { - Log.log(Log.LEVEL_TRACE, MODULE, "Gallery root, baseurl is null"); - } else { - // verify that baseUrl is a valid URL (don't remove) - new URL(baseUrl); - } - } catch (MalformedURLException e) { - Log.log(Log.LEVEL_TRACE, MODULE, "baseurl is relative, tacking on Gallery URL (only works for standalone)"); - URL tmpUrl = new URL(g.getStUrlString()); - baseUrl = new URL(tmpUrl.getProtocol(), tmpUrl.getHost(), tmpUrl.getPort(), baseUrl).toString(); - } - - String caption = p.getProperty("album.caption"); - if (caption != null) { - a.setCaption(caption); - } - - String extraFieldsString = p.getProperty("album.extrafields"); - if (extraFieldsString != null) { - a.setExtraFieldsString(extraFieldsString); - } - - int width; - int height; - ArrayList extraFields = a.getExtraFields(); - for (int i = 1; i <= numImages; i++) { - if (maxPictures> 0 && newPictures.size() >= maxPictures) { - Log.log(Log.LEVEL_TRACE, MODULE, "Fetched maximum of " + maxPictures + - " pictures: stopping."); - break; - } - - String subAlbumName = p.getProperty("album.name." + i); - boolean subAlbumHidden = p.getBooleanProperty("album.hidden." + i, false); - - if (subAlbumName != null) { - if (!subAlbumHidden) { - fetch(a, subAlbumName, newPictures); - } - } else { - Picture picture = new Picture(g); - picture.setOnline(true); - - String rawName = p.getProperty("image.name." + i); - if (rawName != null) { - picture.setUrlFull(new URL(baseUrl + rawName)); - width = p.getIntProperty("image.raw_width." + i, 0); - height = p.getIntProperty("image.raw_height." + i, 0); - picture.setSizeFull(new Dimension(width, height)); - picture.setFileSize(p.getIntProperty("image.raw_filesize." + i)); - - picture.setUniqueId(a.getName() + '_' + rawName); - picture.setItemId(rawName); - } - - String forceExtension = p.getProperty("image.forceExtension." + i); - if (forceExtension != null) { - picture.setForceExtension(forceExtension); - } - - String resizedName = p.getProperty("image.resizedName." + i); - if (resizedName != null) { - picture.setUrlResized(new URL(baseUrl + resizedName)); - width = p.getIntProperty("image.resized_width." + i); - height = p.getIntProperty("image.resized_height." + i); - picture.setSizeResized(new Dimension(width, height)); - } - - picture.setUrlThumbnail(new URL(baseUrl + p.getProperty("image.thumbName." + i))); - width = p.getIntProperty("image.thumb_width." + i); - height = p.getIntProperty("image.thumb_height." + i); - picture.setSizeThumbnail(new Dimension(width, height)); - - int resizedNum = p.getIntProperty("image.resizedNum." + i, 0); - for (int j = 1; j <= resizedNum; j++) { - resizedName = p.getProperty("image.resized." + j + ".name." + i); - width = p.getIntProperty("image.resized." + j + ".width." + i); - height = p.getIntProperty("image.resized." + j + ".height." + i); - picture.addResizedDerivative(new URL(baseUrl + resizedName), new Dimension(width, height)); - } - - picture.setCaption(p.getProperty("image.caption." + i)); - - String title = p.getProperty("image.title." + i); - if (title != null) { - picture.setName(title); - } - - if (extraFields != null) { - for (Iterator it = extraFields.iterator(); it.hasNext();) { - String name = (String) it.next(); - String value = p.getProperty("image.extrafield." + name + "." + i); - - if (value != null) { - picture.setExtraField(name, value); - } - } - } - - picture.setHidden(p.getBooleanProperty("image.hidden." + i, false)); - - picture.setAlbumOnServer(a); - picture.setIndexOnServer(i - 1); - - if (!picture.isHidden() && !(rawName == null && resizedName == null)) { - // don't add the picture if the current user can't get access to it - newPictures.add(picture); - } - } - } - } else { - throw new GR2Exception(p.getProperty("error")); - } - - /*} catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2));*/ - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - } - } - - /** - * An extension of GalleryTask to handle moving an album. - */ - class MoveAlbumTask extends GalleryTask { - Album a; - Album newParent; - boolean success = false; - - MoveAlbumTask(StatusUpdate su, Album a, Album newParent) { - super(su); - this.a = a; - this.newParent = newParent; - } - - void runTask() { - String newParentName; - String destAlbumName; - - if (newParent != null) { - newParentName = destAlbumName = newParent.getName(); - } else { - newParentName = GRI18n.getString(MODULE, "rootAlbum"); - destAlbumName = "0"; - } - - status(su, StatusUpdate.LEVEL_GENERIC, - GRI18n.getString(MODULE, "moveAlbum", - new String[]{a.getName(), newParentName})); - - try { - // setup the protocol parameters - NVPair form_data[] = { - new NVPair("cmd", "move-album"), - new NVPair("protocol_version", PROTOCOL_VERSION), - new NVPair("set_albumName", a.getName()), - new NVPair("set_destalbumName", destAlbumName) - }; - Log.log(Log.LEVEL_TRACE, MODULE, "move-album parameters: " + - Arrays.asList(form_data)); - - form_data = fudgeFormParameters(form_data); - - // load and validate the response - GalleryProperties p = requestResponse(form_data, su, this); - if (p.getProperty("status").equals(GR_STAT_SUCCESS)) { - status(su, StatusUpdate.LEVEL_GENERIC, - GRI18n.getString(MODULE, "moveAlbumDone")); - - success = true; - } else { - error(su, "Error: " + p.getProperty("status_text")); - } - - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - } - - public boolean getSuccess() { - return success; - } - } - - boolean isTrue(String s) { - return s != null && s.equals("true"); - } - - /** - * POSTSs a request to the Gallery server with the given form data. - */ - GalleryProperties requestResponse(NVPair form_data[], StatusUpdate su, GalleryTask task) - throws ModuleException, IOException { - return requestResponse(form_data, null, g.getGalleryUrl(scriptName), true, su, task, null); - } - - GalleryProperties requestResponse(NVPair form_data[], URL galUrl, StatusUpdate su, GalleryTask task) - throws ModuleException, IOException { - return requestResponse(form_data, null, galUrl, true, su, task, null); - } - - GalleryProperties requestResponse(NVPair form_data[], byte[] data, URL galUrl, boolean checkResult, - StatusUpdate su, GalleryTask task, MyTransferListener transferListener) - throws ModuleException, IOException { - return requestResponse(form_data, data, galUrl, checkResult, su, task, false, transferListener); - } - - /** - * POSTs a request to the Gallery server with the given form data. If data is - * not null, a multipart MIME post is performed. - */ - GalleryProperties requestResponse(NVPair form_data[], byte[] data, URL galUrl, boolean checkResult, - StatusUpdate su, GalleryComm2.GalleryTask task, boolean alreadyRetried, - MyTransferListener transferListener) - throws ModuleException, IOException { - // assemble the URL - String urlPath = galUrl.getFile(); - Log.log(Log.LEVEL_TRACE, MODULE, "Connecting to: " + galUrl); - Log.log(Log.LEVEL_TRACE, MODULE, "Path: " + urlPath); - - if (data != null) { - su.startProgress(StatusUpdate.LEVEL_UPLOAD_ONE, 0, 0, GRI18n.getString(MODULE, "upStart"), false); - } - - // create a connection - HTTPConnection mConnection = new HTTPConnection(galUrl); - - // set the user-agent for all requests - // also try to disable pipelining, to help with uploading large numbers of files - ArrayList nvPairs = new ArrayList(); - - nvPairs.add(new NVPair("Connection", "close")); - - // If Gallery specified the user agent, then we'll use that. If not, we'll let - // HTTPClient choose a default agent. - String userAgent = g.getUserAgent(); - if (userAgent != null) { - nvPairs.add(new NVPair("User-Agent", userAgent)); - } - - mConnection.setDefaultHeaders((NVPair[]) nvPairs.toArray(new NVPair[nvPairs.size()])); - Log.log(Log.LEVEL_TRACE, MODULE, "Extra headers: " + nvPairs); - - if (g.getForceProtocolEncoding() != null) { - mConnection.setForceCharset(g.getForceProtocolEncoding()); - } - - // Markus Cozowicz (mc@austrian-mint.at) 2003/08/24 - HTTPResponse rsp; - - // post multipart if there is data - if (data == null) { - if (form_data == null) { - rsp = mConnection.Get(urlPath); - } else { - rsp = mConnection.Post(urlPath, form_data); - } - } else { - rsp = mConnection.Post(urlPath, data, form_data, transferListener); - } - - //Log.log(Log.LEVEL_TRACE, MODULE, "Request body: " + new String(rsp.request.getData())); - - // handle 30x redirects - if (rsp.getStatusCode() >= 300 && rsp.getStatusCode() < 400) { - // retry, the library will have fixed the URL - status(su, StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "redirect")); - if (data == null) { - if (form_data == null) { - rsp = mConnection.Get(urlPath); - } else { - rsp = mConnection.Post(urlPath, form_data); - } - } else { - rsp = mConnection.Post(urlPath, data, form_data, transferListener); - } - } - - // handle response - if (rsp.getStatusCode() >= 300) { - Object[] params = {new Integer(rsp.getStatusCode()), rsp.getReasonLine()}; - throw new GR2Exception(GRI18n.getString(MODULE, "httpPostErr", params)); - } else { - Log.log(Log.LEVEL_TRACE, MODULE, "Content-type: " + rsp.getHeader("Content-type")); - - // load response - String response; - try { - response = rsp.getText().trim(); - } catch (ParseException e) { - Log.log(Log.LEVEL_ERROR, MODULE, "HTTPClient failed to parse response, getting data instead of text"); - response = new String(rsp.getData()).trim(); - } - Log.log(Log.LEVEL_TRACE, MODULE, response); - - if (checkResult) { - // validate response - int i = response.indexOf(PROTOCOL_MAGIC); - - if (i == -1) { - if (alreadyRetried) { - // failed one time too many - Object[] params = {galUrl.toString()}; - throw new GR2Exception(GRI18n.getString(MODULE, "gllryNotFound", params)); - } else { - // try again - Log.log(Log.LEVEL_INFO, MODULE, "Request failed the first time: trying again..."); - return requestResponse(form_data, data, galUrl, checkResult, su, task, true, transferListener); - } - } else if (i > 0) { - response = response.substring(i); - Log.log(Log.LEVEL_TRACE, MODULE, "Short response: " + response); - } - - GalleryProperties p = new GalleryProperties(); - p.load(response); - - // catch session expiration problems - if (!alreadyRetried && !g.cookieLogin && g.getUsername() != null && g.getUsername().length() != 0 - && p.getProperty("debug_user_already_logged_in") != null - && ! "1".equals(p.getProperty("debug_user_already_logged_in"))) { - Log.log(Log.LEVEL_INFO, MODULE, "The session seems to have expired: trying to login and retry..."); - - if (task.login()) { - return requestResponse(form_data, data, galUrl, checkResult, su, task, true, transferListener); - } else { - Log.log(Log.LEVEL_INFO, MODULE, "Login attempt unsuccessful"); - } - } - - //mConnection.stop(); - - su.stopProgress(StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "addImgOk")); - - g.setAuthToken(p.getProperty("auth_token")); - - return p; - } else { - su.stopProgress(StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "addImgErr")); - - return null; - } - } - } - - public NVPair[] fudgeFormParameters(NVPair[] form_data) { - return form_data; - } - - public NVPair[] fudgeParameters(NVPair[] data) { - return data; - } - - void handleCapabilities() { - if (serverMinorVersion >= 15) { - capabilities = capabilities15; - } else if (serverMinorVersion >= 14) { - capabilities = capabilities14; - } else if (serverMinorVersion >= 13) { - capabilities = capabilities13; - } else if (serverMinorVersion >= 9) { - capabilities = capabilities9; - } else if (serverMinorVersion >= 7) { - capabilities = capabilities7; - } else if (serverMinorVersion >= 5) { - capabilities = capabilities5; - } else if (serverMinorVersion >= 2) { - capabilities = capabilities2; - } else if (serverMinorVersion == 1) { - capabilities = capabilities1; - } - } - - class MyTransferListener implements TransferListener { - StatusUpdate su; - java.text.DecimalFormat df = new java.text.DecimalFormat("##,##0"); - java.text.DecimalFormat ff = new java.text.DecimalFormat("##,##0.0"); - - String currentFile; - - long sizeAllFiles; - long transferredFilesDone = 0; - long transferredThisFile = 0; - - int numberAllFiles; - int numberFilesDone = 0; - - long timeStarted = 0; - double kbPerSecond = 0; - - MyTransferListener(StatusUpdate su) { - this.su = su; - } - - public void dataTransferred(int transferredThisFile, int sizeThisFile, double kbPerSecond) { - this.transferredThisFile = transferredThisFile; - - Object[] params = { - df.format(transferredThisFile / 1024), - df.format(sizeThisFile / 1024), - ff.format(kbPerSecond / 1024.0)}; - - su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "trnsfrStat", params)); - su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ONE, transferredThisFile); - - params = new Object[] { - currentFile, - new Integer(numberFilesDone + 1), - new Integer(numberAllFiles), - new Integer((int) ((transferredFilesDone + transferredThisFile) / 1024 / 1024)), - new Integer((int) (sizeAllFiles / 1024 / 1024)), - getProjectedTimeLeft() - }; - su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upStatus", params)); - su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ALL, (int) ((transferredFilesDone + transferredThisFile) * 100 / sizeAllFiles)); - } - - public void transferStart(int sizeThisFile) { - this.transferredThisFile = sizeThisFile; - if (timeStarted == 0) { - timeStarted = System.currentTimeMillis(); - } - - su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ONE, 0, sizeThisFile); - } - - public void transferEnd(int sizeThisFile) { - transferredFilesDone += sizeThisFile; - this.transferredThisFile = 0; - numberFilesDone++; - - su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upCompSrvrProc")); - su.setUndetermined(StatusUpdate.LEVEL_UPLOAD_ONE, true); - } - - public String getProjectedTimeLeft() { - int secondsLeft = getProjectedSecondsLeft(); - - if (secondsLeft == -1) { - return ""; - } else if (secondsLeft >= 120) { - Object[] params = { new Integer(secondsLeft / 60) }; - return GRI18n.getString(MODULE, "minutesLeft", params); - } else { - Object[] params = { new Integer(secondsLeft) }; - return GRI18n.getString(MODULE, "secondsLeft", params); - } - } - - public int getProjectedSecondsLeft() { - long timeNow = System.currentTimeMillis(); - - if (timeStarted == 0 || timeNow - timeStarted < 500) { - // just starting, unknown average speed - return -1; - } - - // average the current speed and the speed since start - double denom = (kbPerSecond + ((transferredFilesDone + transferredThisFile) / (timeNow - timeStarted) * 1000)) / 2; - - if (denom == 0) { - return -1; - } - - return (int) ((sizeAllFiles - transferredFilesDone - transferredThisFile) / denom); - } - } - - /* ------------------------------------------------------------------------- - * MAIN METHOD (test only) - */ - /*public static void main( String [] args ) { - - try { - StatusUpdate su = new StatusUpdateAdapter(){}; - Gallery g = new Gallery(); - g.setStUrlString( "http://www.deathcult.com/gallery/" ); - g.setUsername( "ted" ); - g.setPassword( "1qwe2asd" ); - g.setStatusUpdate( su ); - GalleryComm2 gc = new GalleryComm2( g ); - gc.fetchAlbums( su, false ); - - //try { Thread.sleep( 10000 ); } catch ( InterruptedException ie ) {} - - ArrayList albumList = g.getAlbumList(); - System.err.println( "albumList size = " + albumList.size() ); - for ( int i = 0; i < albumList.size(); i++ ) { - Album a = (Album)albumList.get( i ); - a.fetchAlbumProperties( su ); - //try { Thread.sleep( 500 ); } catch ( InterruptedException ie ) {} - } - - //try { Thread.sleep( 10000 ); } catch ( InterruptedException ie ) {} - - ArrayList albumList2 = g.getAlbumList(); - System.err.println( "albumList2 size = " + albumList2.size() ); - for ( int i = 0; i < albumList2.size(); i++ ) { - Album a = (Album)albumList2.get( i ); - System.err.println( a.getName() + " srv_rsz = " + a.getServerAutoResize() ); - } - - } catch ( MalformedURLException mue ) { - - } - }*/ -} diff --git a/com/gallery/GalleryRemote/GalleryComm2_5.java b/com/gallery/GalleryRemote/GalleryComm2_5.java deleted file mode 100644 index 0a4e746..0000000 --- a/com/gallery/GalleryRemote/GalleryComm2_5.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Created by IntelliJ IDEA. - * User: paour - * Date: Mar 17, 2004 - * Time: 4:20:46 PM - */ -package com.gallery.GalleryRemote; - -import com.gallery.GalleryRemote.model.Gallery; -import com.gallery.GalleryRemote.model.Picture; -import com.gallery.GalleryRemote.model.Album; -import com.gallery.GalleryRemote.prefs.GalleryProperties; -import com.gallery.GalleryRemote.util.GRI18n; -import HTTPClient.NVPair; -import HTTPClient.ModuleException; - -import java.net.URL; -import java.io.IOException; -import java.util.Arrays; - -public class GalleryComm2_5 extends GalleryComm2 { - private static final String MODULE = "GalComm2"; - - /** Remote scriptname that provides version 2 of the protocol on the server. */ - public static final String SCRIPT_NAME = "main.php?g2_controller=remote.GalleryRemote&g2_form[cmd]=no-op"; - - public static final boolean ZEND_DEBUG = false; - - private static int[] capabilities2; - private static int[] capabilities3; - private static int[] capabilities4; - private static int[] capabilities6; - private static int[] capabilities7; - private static int[] capabilities8; - private static int[] capabilities9; - - protected GalleryComm2_5(Gallery g) { - super(g); - - scriptName = "main.php"; - - capabilities2 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_FETCH_ALBUMS_PRUNE}; - capabilities3 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE}; - capabilities4 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_NEW_ALBUM, CAPA_FETCH_ALBUMS_PRUNE, - CAPA_FETCH_ALBUM_IMAGES, CAPA_FORCE_FILENAME}; - capabilities6 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_IMAGE_MAX_SIZE, CAPA_NEW_ALBUM, - CAPA_FETCH_ALBUMS_PRUNE, CAPA_FETCH_ALBUM_IMAGES, CAPA_FORCE_FILENAME}; - capabilities7 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_IMAGE_MAX_SIZE, CAPA_NEW_ALBUM, - CAPA_FETCH_ALBUMS_PRUNE, CAPA_FETCH_ALBUM_IMAGES, CAPA_FORCE_FILENAME, - CAPA_INCREMENT_VIEW_COUNT}; - capabilities8 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_IMAGE_MAX_SIZE, CAPA_NEW_ALBUM, - CAPA_FETCH_ALBUMS_PRUNE, CAPA_FETCH_ALBUM_IMAGES, CAPA_FORCE_FILENAME, - CAPA_INCREMENT_VIEW_COUNT, CAPA_FETCH_ALBUMS_TOO}; - capabilities9 = new int[]{CAPA_UPLOAD_FILES, CAPA_FETCH_ALBUMS, CAPA_UPLOAD_CAPTION, - CAPA_FETCH_HIERARCHICAL, CAPA_ALBUM_INFO, CAPA_IMAGE_MAX_SIZE, CAPA_NEW_ALBUM, - CAPA_FETCH_ALBUMS_PRUNE, CAPA_FETCH_ALBUM_IMAGES, CAPA_FORCE_FILENAME, - CAPA_INCREMENT_VIEW_COUNT, CAPA_FETCH_ALBUMS_TOO, CAPA_FETCH_RANDOM}; - - Arrays.sort(capabilities2); - Arrays.sort(capabilities3); - Arrays.sort(capabilities4); - Arrays.sort(capabilities6); - Arrays.sort(capabilities7); - Arrays.sort(capabilities8); - Arrays.sort(capabilities9); - - g.setGalleryVersion(2); - } - - public void incrementViewCount(StatusUpdate su, Picture p) { - doTask(new IncrementViewCountTask(su, p), true); - } - - /** - * An extension of GalleryTask to handle moving an album. - */ - class IncrementViewCountTask extends GalleryTask { - Picture p; - - IncrementViewCountTask(StatusUpdate su, Picture p) { - super(su); - this.p = p; - } - - void runTask() { - try { - // setup the protocol parameters - NVPair form_data[] = { - new NVPair("cmd", "increment-view-count"), - new NVPair("protocol_version", PROTOCOL_VERSION), - new NVPair("itemId", p.getItemId()), - }; - Log.log(Log.LEVEL_TRACE, MODULE, "increment-view-count parameters: " + - Arrays.asList(form_data)); - - form_data = fudgeFormParameters(form_data); - - // load and validate the response - GalleryProperties p = requestResponse(form_data, su, this); - } catch (GR2Exception gr2e) { - Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); - Object[] params2 = {gr2e.getMessage()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (IOException ioe) { - Log.logException(Log.LEVEL_ERROR, MODULE, ioe); - Object[] params2 = {ioe.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } catch (ModuleException me) { - Log.logException(Log.LEVEL_ERROR, MODULE, me); - Object[] params2 = {me.toString()}; - error(su, GRI18n.getString(MODULE, "error", params2)); - } - } - } - - public NVPair[] fudgeParameters(NVPair[] data) { - NVPair[] data_modified = new NVPair[data.length]; - for (int i = 0; i < data.length; i++) { - NVPair nvPair = data[i]; - data_modified[i] = new NVPair("g2_" + nvPair.getName(), nvPair.getValue(), nvPair.safeGetEncoding()); - } - - return data_modified; - } - - public NVPair[] fudgeFormParameters(NVPair form_data[]) { - NVPair[] form_data_modified; - if (ZEND_DEBUG) { - form_data_modified = new NVPair[form_data.length + 7]; - } else { - form_data_modified = new NVPair[form_data.length + 2]; - } - - for (int i = 0; i < form_data.length; i++) { - if (form_data[i] != null) { - form_data_modified[i] = new NVPair("g2_form[" + form_data[i].getName() + "]", form_data[i].getValue(), form_data[i].safeGetEncoding()); - } else { - form_data_modified[i] = null; - } - } - - form_data_modified[form_data.length] = new NVPair("g2_controller", "remote.GalleryRemote"); - if (g.getAuthToken() != null) { - form_data_modified[form_data.length + 1] = new NVPair("g2_authToken", g.getAuthToken()); - } - - if (ZEND_DEBUG) { - form_data_modified[form_data.length + 2] = new NVPair("start_debug", "1"); - form_data_modified[form_data.length + 3] = new NVPair("debug_port", "10000"); - form_data_modified[form_data.length + 4] = new NVPair("debug_host", "172.16.1.35,127.0.0.1"); - form_data_modified[form_data.length + 5] = new NVPair("send_sess_end", "1"); - //form_data_modified[form_data.length + 5] = new NVPair("debug_no_cache", "1077182887875"); - //form_data_modified[form_data.length + 6] = new NVPair("debug_stop", "1"); - form_data_modified[form_data.length + 6] = new NVPair("debug_url", "1"); - } - - Log.log(Log.LEVEL_TRACE, MODULE, "Overriding form data: " + Arrays.asList(form_data_modified)); - - return form_data_modified; - } - - void handleCapabilities() { - if (serverMinorVersion >= 9) { - capabilities = capabilities9; - } else if (serverMinorVersion >= 8) { - capabilities = capabilities8; - } else if (serverMinorVersion >= 7) { - capabilities = capabilities7; - } else if (serverMinorVersion >= 6) { - capabilities = capabilities6; - } else if (serverMinorVersion >= 4) { - capabilities = capabilities4; - } else if (serverMinorVersion >= 3) { - capabilities = capabilities3; - } else { - capabilities = capabilities2; - } - } - -} diff --git a/com/gallery/GalleryRemote/GalleryComm3.java b/com/gallery/GalleryRemote/GalleryComm3.java new file mode 100644 index 0000000..43adfe5 --- /dev/null +++ b/com/gallery/GalleryRemote/GalleryComm3.java @@ -0,0 +1,329 @@ +package com.gallery.GalleryRemote; + +import com.gallery.GalleryRemote.model.Gallery; +import com.gallery.GalleryRemote.model.Album; +import com.gallery.GalleryRemote.util.GRI18n; +import com.gallery.GalleryRemote.util.NaturalOrderComparator; +import com.gallery.GalleryRemote.util.UrlMessageDialog; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.message.BasicNameValuePair; +import org.json.simple.parser.ContentHandler; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.*; +import java.net.URL; +import java.util.*; + +public class GalleryComm3 extends GalleryComm { + private static final String MODULE = "GalComm3"; + + private static String api = "index.php/rest/"; + + public GalleryComm3(Gallery g, StatusUpdate su) { + super(g, su); + } + + public void fetchAlbums(StatusUpdate su, boolean async) { + doTask(new AlbumListTask(su), async); + } + + /* ------------------------------------------------------------------------- + * UTILITY METHODS + */ + void doTask(GalleryTask task, boolean async) { + if (async) { + Thread t = new Thread(task); + t.start(); + } else { + task.run(); + } + } + + void status(StatusUpdate su, int level, String message) { + Log.log(Log.LEVEL_INFO, MODULE, message); + su.updateProgressStatus(level, message); + } + + void error(StatusUpdate su, String message) { + status(su, StatusUpdate.LEVEL_GENERIC, message); + su.error(message); + } + + void trace(String message) { + Log.log(Log.LEVEL_TRACE, MODULE, message); + } + + /* ------------------------------------------------------------------------- + * INNER CLASSES + */ + + /** + * An extension of GalleryTask to handle fetching albums. + */ + class AlbumListTask extends GalleryTask { + AlbumListTask(StatusUpdate su) { + super(su); + } + + void runTask() { + su.startProgress(StatusUpdate.LEVEL_BACKGROUND, 0, 10, GRI18n.getString(MODULE, "albmFtchng", new Object[] {g.toString()}), true); + + long startTime = System.currentTimeMillis(); + + try { + list(); + } catch (IOException e) { + Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + } + + // tell the tree to reload + g.reload(); + + Log.log(Log.LEVEL_INFO, MODULE, "execution time for AlbumList: " + (System.currentTimeMillis() - startTime)); + + su.stopProgress(StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "fetchComplete")); + } + + private void list() throws IOException { + HttpPost post = new HttpPost(g.getUrlString() + api + "item/1"); + List formparams = new ArrayList(); + formparams.add(new BasicNameValuePair("type", "album")); + formparams.add(new BasicNameValuePair("scope", "all")); + UrlEncodedFormEntity entity = null; + try { + entity = new UrlEncodedFormEntity(formparams, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + post.setEntity(entity); + post.setHeader("X-Gallery-Request-Method", "get"); + post.setHeader("X-Gallery-Request-Key", g.getKey()); + + HttpResponse response = httpclient.execute(post); + + if (response.getStatusLine().getStatusCode() == 200) { + HttpEntity rentity = response.getEntity(); + + JSONParser parser = new JSONParser(); + ListContentHandler lch = new ListContentHandler(); + + HashMap url2parentUrl = new HashMap(); + HashMap url2album = new HashMap(); + ArrayList albums = new ArrayList(); + + try { + BufferedReader entityReader = new BufferedReader(new InputStreamReader(rentity.getContent())); + + Album rootAlbum = g.createRootAlbum(); + rootAlbum.setUrl(post.getURI().toString()); + rootAlbum.setSuppressEvents(true); + lch.setAlbum(rootAlbum); + parser.parse(entityReader, lch, true); + rootAlbum.setSuppressEvents(false); + // map album names to albums + url2album.put(rootAlbum.getUrl(), rootAlbum); + url2parentUrl.put(rootAlbum.getUrl(), lch.getParentUrl()); + + while (!lch.isEnd()) { + Album a = g.newAlbum(); + a.setSuppressEvents(true); + lch.setAlbum(a); + parser.parse(entityReader, lch, true); + a.setSuppressEvents(false); + + albums.add(a); + + // map album names to albums + url2album.put(a.getUrl(), a); + url2parentUrl.put(a.getUrl(), lch.getParentUrl()); + } + } catch (ParseException e) { + Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + } + + Log.log(Log.LEVEL_TRACE, MODULE, "Created " + albums.size() + " albums"); + + // link albums to parents + for (Object o : url2parentUrl.keySet()) { + String name = (String) o; + String parentName = url2parentUrl.get(name); + Album child = url2album.get(name); + Album parent = url2album.get(parentName); + + if (child != null && parent != null) { + parent.add(child); + } + } + + Log.log(Log.LEVEL_TRACE, MODULE, "Linked " + url2parentUrl.size() + " albums to their parents"); + + // reorder + Collections.sort(albums, new NaturalOrderComparator()); + Collections.reverse(albums); + ArrayList orderedAlbums = new ArrayList(); + int depth = 0; + while (!albums.isEmpty()) { + Iterator it = albums.iterator(); + while (it.hasNext()) { + Album a = it.next(); + + try { + if (a.getAlbumDepth() == depth) { + it.remove(); + a.sortSubAlbums(); + + Album parentAlbum = a.getParentAlbum(); + if (parentAlbum == null) { + orderedAlbums.add(0, a); + } else { + int i = orderedAlbums.indexOf(parentAlbum); + orderedAlbums.add(i + 1, a); + } + } + } catch (IllegalArgumentException e) { + it.remove(); + Log.log(Log.LEVEL_TRACE, MODULE, "Gallery server album list is corrupted: " + + "album " + a.getName() + " has a bad containment hierarchy."); + } + } + + depth++; + } + + Log.log(Log.LEVEL_TRACE, MODULE, "Ordered " + orderedAlbums.size() + " albums"); + + status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms")); + + //g.setAlbumList(orderedAlbums); + } else { + throw new GR2Exception("Connection error: " + response.getStatusLine().toString()); + } + } + + private class ListContentHandler implements ContentHandler { + private boolean end = false; + private String key; + private Album a; + private String parentUrl = null; + private int curState = 0; // would have used an enum, but can't inside an inner class... + // 0 = init, 1 = root album, 2 = members + + public void setAlbum(Album a) { + this.a = a; + } + + public String getParentUrl() { + return parentUrl; + } + + public boolean isEnd() { + return end; + } + + public void startJSON() throws ParseException, IOException { + end = false; + } + + public void endJSON() throws ParseException, IOException { + end = true; + } + + public boolean primitive(Object value) throws ParseException, IOException { + if (key.equals("title")) { + a.setTitle((String) value); + } else if (key.equals("description")) { + a.setDescription((String) value); + } else if (key.equals("can_edit")) { + a.setCanEdit((Boolean) value); + } else if (curState == 2) { // to change to handle objects in the members array + a.setUrl((String) value); + return false; + } + + return true; + } + + public boolean startArray() throws ParseException, IOException { + return true; + } + + public boolean startObject() throws ParseException, IOException { + return true; + } + + public boolean startObjectEntry(String key) throws ParseException, IOException { + this.key = key; + + if (key.equals("entity")) { + if (curState == 0) { + curState = 1; + } + } else if (key.equals("members")) { + if (curState == 1) { + curState = 2; + return false; + } + } + + return true; + } + + public boolean endArray() throws ParseException, IOException { + return false; + } + + public boolean endObject() throws ParseException, IOException { + return true; + } + + public boolean endObjectEntry() throws ParseException, IOException { + return true; + } + } + } + + /** + * This class serves as the base class for each GalleryComm task. + */ + abstract class GalleryTask implements Runnable { + StatusUpdate su; + boolean interrupt = false; + boolean terminated = false; + Thread thread = null; + + public GalleryTask(StatusUpdate su) { + if (su == null) { + this.su = new StatusUpdateAdapter() { + }; + } else { + this.su = su; + } + } + + public void run() { + thread = Thread.currentThread(); + su.setInProgress(true); + + runTask(); + + cleanUp(); + } + + public void interrupt() { + thread.interrupt(); + interrupt = true; + } + + public void cleanUp() { + su.setInProgress(false); + terminated = true; + } + + abstract void runTask(); + } +} diff --git a/com/gallery/GalleryRemote/GalleryCommTest.java b/com/gallery/GalleryRemote/GalleryCommTest.java new file mode 100644 index 0000000..c9255f7 --- /dev/null +++ b/com/gallery/GalleryRemote/GalleryCommTest.java @@ -0,0 +1,35 @@ +package com.gallery.GalleryRemote; + +import com.gallery.GalleryRemote.model.Gallery; +import org.junit.Before; +import org.junit.Test; + +import java.net.URL; + +/** + * Created by IntelliJ IDEA. + * User: paour + * Date: Jun 18, 2010 + * Time: 4:05:33 PM + */ +public class GalleryCommTest { + public static final String MODULE = "CommTest"; + + @Test + public void testFetchAlbums() throws Exception { + StatusUpdate su = new StatusUpdateAdapter(); + Gallery g = new Gallery(su); + g.setUrlString("http://localhost/~paour/gallery3/"); + Log.log(Log.LEVEL_INFO, MODULE, "Starting fetchAlbums"); + GalleryComm comm = GalleryComm.getCommInstance(su, g); + Log.log(Log.LEVEL_INFO, MODULE, "Starting fetchAlbums"); + comm.fetchAlbums(su, false); + } + + @Before + public void setup() { + GalleryRemote.createInstance("com.gallery.GalleryRemote.GalleryRemoteMainFrame", null); + + GalleryRemote._().initializeGR(); + } +} diff --git a/com/gallery/GalleryRemote/GalleryRemote.java b/com/gallery/GalleryRemote/GalleryRemote.java index 4515962..61e29ca 100644 --- a/com/gallery/GalleryRemote/GalleryRemote.java +++ b/com/gallery/GalleryRemote/GalleryRemote.java @@ -176,7 +176,7 @@ public static boolean createInstance(String className, Applet applet) { return true; } else { - System.err.println("Trying to instanciate Gallery Remote more than once..."); + System.err.println("Trying to instantiate Gallery Remote more than once..."); Thread.dumpStack(); return false; diff --git a/com/gallery/GalleryRemote/GalleryRemoteScreenSaver.java b/com/gallery/GalleryRemote/GalleryRemoteScreenSaver.java deleted file mode 100644 index 53e9f0c..0000000 --- a/com/gallery/GalleryRemote/GalleryRemoteScreenSaver.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.gallery.GalleryRemote; - -import com.gallery.GalleryRemote.util.ImageUtils; -import com.gallery.GalleryRemote.util.ImageLoaderUtil; -import com.gallery.GalleryRemote.prefs.PropertiesFile; -import com.gallery.GalleryRemote.prefs.PreferenceNames; -import com.gallery.GalleryRemote.model.Gallery; -import com.gallery.GalleryRemote.model.Album; -import com.gallery.GalleryRemote.model.Picture; - -import javax.swing.*; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import java.awt.*; -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.net.URL; - -import org.jdesktop.jdic.screensaver.ScreensaverContext; -import org.jdesktop.jdic.screensaver.ScreensaverSettings; - -/** - * Created by IntelliJ IDEA. - * User: paour - * Date: Jan 14, 2004 - */ -public class GalleryRemoteScreenSaver - extends GalleryRemote - implements GalleryRemoteCore, PreferenceNames, ListDataListener, ImageLoaderUtil.ImageLoaderUser { - DefaultComboBoxModel galleries = null; - Gallery gallery; - Album album; - DroppableList jPicturesList; - StatusUpdateAdapter statusUpdate = new StatusUpdateAdapter(); - ScreensaverContext context; - Picture currentPicture = null; - File currentImage = null; - ImageLoaderUtil loader = new ImageLoaderUtil(3, this); - Dimension size = null; - boolean newImage = false; - ArrayList picturesList = null; - int delay = 5000; - boolean hasSettings = true; - - protected void initializeGR() { - super.initializeGR(); - - CoreUtils.initCore(); - - Log.startLog(_().properties.getIntProperty(PreferenceNames.LOG_LEVEL), _().properties.getBooleanProperty("toSysOut")); - - startup(); - } - - public void setContext(ScreensaverContext context) { - this.context = context; - } - - public void createProperties() { - super.createProperties(); - - File f = new File(System.getProperty("user.home") - + File.separator + ".GalleryRemote" - + File.separator); - - f.mkdirs(); - - File pf = new File(f, "GalleryRemoteScreenSaver.properties"); - - if (!pf.exists()) { - try { - pf.createNewFile(); - } catch (IOException e) { - Log.logException(Log.LEVEL_ERROR, MODULE, e); - } - } - - properties = new PropertiesFile(properties, pf.getPath(), "user"); - } - - public Frame getMainFrame() { - return null; - } - - public GalleryRemoteCore getCore() { - return this; - } - - protected void loadIcons() {} - - public void startup() { - ScreensaverSettings settings = context.getSettings(); - //settings.loadSettings("Gallery"); - Log.log(Log.LEVEL_TRACE, MODULE, "Screensaver settings: " + settings.getProperties().toString()); - - Properties p = settings.getProperties(); - - galleries = new DefaultComboBoxModel(); - - gallery = new Gallery(GalleryRemote._().getCore().getMainStatusUpdate()); - String curl = settings.getProperty("curl"); - - if (curl != null) { - try { - p.load(new URL(curl).openStream()); - } catch (IOException e) { - Log.log(Log.LEVEL_CRITICAL, MODULE, "Error trying to get configuration file: " + curl); - Log.logException(Log.LEVEL_CRITICAL, MODULE, e); - } - - Log.log(Log.LEVEL_TRACE, MODULE, "Fetched settings: " + settings.getProperties().toString()); - } - - String url = p.getProperty("url"); - if (url != null) { - gallery.setStUrlString(url); - if (p.getProperty("username") == null || p.getProperty("username").trim().length() == 0) { - gallery.cookieLogin = true; - } else { - gallery.setUsername(p.getProperty("username")); - gallery.setPassword(p.getProperty("password")); - } - gallery.setType(Gallery.TYPE_STANDALONE); - - properties.setBooleanProperty(SLIDESHOW_RECURSIVE, p.getProperty("recursive") != null); - properties.setBooleanProperty(SLIDESHOW_LOWREZ, p.getProperty("hires") == null); - properties.setBooleanProperty(SLIDESHOW_NOSTRETCH, p.getProperty("stretch") == null); - delay = Integer.parseInt(p.getProperty("delay")) * 1000; - String albums = p.getProperty("album"); - String[] albumsA = albums.split(","); - - galleries.addElement(gallery); - ImageUtils.deferredTasks(); - - album = new Album(gallery); - album.setName(albumsA[new Random().nextInt(albumsA.length)]); - album.addListDataListener(this); - - album.fetchAlbumImages(statusUpdate, - GalleryRemote._().properties.getBooleanProperty(SLIDESHOW_RECURSIVE), - 200, true); - } else { - hasSettings = false; - } - } - - public void nextPicture() { - if (GalleryRemote._() == null) { - return; - } - - if (picturesList == null || picturesList.size() == 0) { - picturesList = new ArrayList(album.getPicturesList()); - } - - Picture p = (Picture) picturesList.get((int) Math.floor(Math.random() * picturesList.size())); - picturesList.remove(p); - - loader.preparePicture(p, true, true); - } - - public void shutdown() { - if (GalleryRemote._() != null) { - GalleryRemote.shutdownInstance(); - } - } - - public void shutdown(boolean shutdownOs) { - shutdown(); - } - - public void flushMemory() {} - - public void preloadThumbnails(Iterator pictures) {} - - public Image getThumbnail(Picture p) { - return null; - } - - public StatusUpdate getMainStatusUpdate() { - return statusUpdate; - } - - public DefaultComboBoxModel getGalleries() { - return galleries; - } - - public void thumbnailLoadedNotify() {} - - public void setInProgress(boolean inProgress) {} - - public void addPictures(File[] files, int index, boolean select) { - album.addPictures(files, index); - } - - public void addPictures(Picture[] pictures, int index, boolean select) { - album.addPictures(Arrays.asList(pictures), index); - } - - public Album getCurrentAlbum() { - return album; - } - - public JList getPicturesList() { - return jPicturesList; - } - - public void contentsChanged(ListDataEvent e) { - if (album.isHasFetchedImages()) { - Log.log(Log.LEVEL_TRACE, MODULE, "Done downloading album info"); - - nextPicture(); - } - } - - public void intervalAdded(ListDataEvent e) {} - - public void intervalRemoved(ListDataEvent e) {} - - public void pictureReady() { - Log.log(Log.LEVEL_TRACE, MODULE, "PictureReady, letting screensaver thread update"); - newImage = true; - - new Thread() { - public void run() { - try { - Thread.sleep(delay); - } catch (InterruptedException e) { - e.printStackTrace(); - } - nextPicture(); - } - }.start(); - } - - public boolean blockPictureReady(Image image, Picture picture) { - return false; - } - - public Dimension getImageSize() { - if (size == null) { - size = context.getComponent().getBounds().getSize(); - } - - return size; - } - - public void nullRect() {} - public void pictureStartDownloading(Picture picture) {} - public void pictureStartProcessing(Picture picture) {} - public void pictureLoadError(Picture picture) {} -} diff --git a/com/gallery/GalleryRemote/MainFrame.java b/com/gallery/GalleryRemote/MainFrame.java index e7d4b63..e80f7a2 100644 --- a/com/gallery/GalleryRemote/MainFrame.java +++ b/com/gallery/GalleryRemote/MainFrame.java @@ -167,31 +167,19 @@ public void initMainFrame() { // load galleries galleries = new DefaultComboBoxModel(); - if (! GalleryRemote._().isAppletMode()) { - int i = 0; - while (true) { - try { - Gallery g = Gallery.readFromProperties(p, i++, jStatusBar); - if (g == null) { - break; - } - //g.addListDataListener(this); - galleries.addElement(g); - } catch (Exception e) { - Log.log(Log.LEVEL_ERROR, MODULE, "Error trying to load Gallery profile " + i); - Log.logException(Log.LEVEL_ERROR, MODULE, e); + int i = 0; + while (true) { + try { + Gallery g = Gallery.readFromProperties(p, i++, jStatusBar); + if (g == null) { + break; } + //g.addListDataListener(this); + galleries.addElement(g); + } catch (Exception e) { + Log.log(Log.LEVEL_ERROR, MODULE, "Error trying to load Gallery profile " + i); + Log.logException(Log.LEVEL_ERROR, MODULE, e); } - } else { - //Gallery g = new Gallery(jStatusBar); - Applet applet = GalleryRemote._().getApplet(); - - GRApplet.AppletInfo info = ((GRApplet) applet).getGRAppletInfo(); - - info.gallery.addTreeModelListener(this); - galleries.addElement(info.gallery); - - //CookieModule.addCookie(new Cookie(cookieName, cookieValue, cookieDomain, cookiePath, null, false)); } setIconImage(iconImage); @@ -502,14 +490,14 @@ public void run() { // if the selected album is uploading, disable everything boolean enabled = !inProgress && currentAlbum != null && jAlbumTree.getModel().getChildCount(jAlbumTree.getModel().getRoot()) >= 1; - jBrowseButton.setEnabled(enabled && currentAlbum.getCanAdd()); - jApertureImport.setEnabled(enabled && currentAlbum.getCanAdd()); + jBrowseButton.setEnabled(enabled && currentAlbum.getCanEdit()); + jApertureImport.setEnabled(enabled && currentAlbum.getCanEdit()); jPictureInspector.setEnabled(enabled); - jPicturesList.setEnabled(enabled && currentAlbum.getCanAdd()); + jPicturesList.setEnabled(enabled && currentAlbum.getCanEdit()); jNewAlbumButton.setEnabled(!inProgress && currentGallery != null && currentGallery.hasComm() && currentGallery.getComm(jStatusBar).isLoggedIn() && currentGallery.getComm(jStatusBar).hasCapability(jStatusBar, GalleryCommCapabilities.CAPA_NEW_ALBUM) - && currentAlbum != null && currentAlbum.getCanCreateSubAlbum()); + && currentAlbum != null && currentAlbum.getCanEdit()); // change image displayed int sel = jPicturesList.getSelectedIndex(); @@ -652,7 +640,7 @@ public void run() { source = new File(imagePath); ImageUtils.addToDelete(source); Picture p = new Picture(getCurrentGallery(), source); - p.setCaption(caption); + p.setDescription(caption); pictures.add(p); } } diff --git a/com/gallery/GalleryRemote/NewAlbumDialog.java b/com/gallery/GalleryRemote/NewAlbumDialog.java index 4577d07..1037f32 100644 --- a/com/gallery/GalleryRemote/NewAlbumDialog.java +++ b/com/gallery/GalleryRemote/NewAlbumDialog.java @@ -188,7 +188,7 @@ public void actionPerformed(ActionEvent e) { //newAlbum.setSuppressEvents(true); newAlbum.setName(jName.getText()); newAlbum.setTitle(jTitle.getText()); - newAlbum.setCaption(jDescription.getText()); + newAlbum.setDescription(jDescription.getText()); //newAlbum.setSuppressEvents(false); @@ -216,7 +216,7 @@ public void itemStateChanged(ItemEvent e) { void resetUIState() { Album a = (Album) jAlbum.getSelectedItem(); - boolean canCreateSubAlbum = a.getCanCreateSubAlbum(); + boolean canCreateSubAlbum = a.getCanEdit(); jOk.setEnabled(canCreateSubAlbum); jName.setEnabled(canCreateSubAlbum); @@ -252,7 +252,7 @@ public Component getListCellRendererComponent(JList list, Object value, int inde list, value, index, isSelected, cellHasFocus); - if (((Album) value).getCanCreateSubAlbum()) { + if (((Album) value).getCanEdit()) { if (! isSelected) { setForeground(Color.BLACK); } diff --git a/com/gallery/GalleryRemote/PictureInspector.java b/com/gallery/GalleryRemote/PictureInspector.java index 7a9e1d5..ba3c0c4 100644 --- a/com/gallery/GalleryRemote/PictureInspector.java +++ b/com/gallery/GalleryRemote/PictureInspector.java @@ -316,7 +316,7 @@ public void textUpdate(DocumentEvent e) { Picture p = ((Picture) pictures[0]); if (e.getDocument() == jCaption.getDocument()) { - p.setCaption(jCaption.getText()); + p.setDescription(jCaption.getText()); } Iterator it = extraTextAreas.keySet().iterator(); @@ -398,7 +398,7 @@ public void setPictures(Object[] pictures) { } jAlbum.setText(p.getParentAlbum().getTitle()); if (p.getParentAlbum().getGallery().getComm(mf.jStatusBar).hasCapability(mf.jStatusBar, GalleryCommCapabilities.CAPA_UPLOAD_CAPTION)) { - jCaption.setText(p.getCaption()); + jCaption.setText(p.getDescription()); jCaption.setEditable(true); jCaption.setBackground(UIManager.getColor("TextField.background")); } diff --git a/com/gallery/GalleryRemote/SlideshowFrame.java b/com/gallery/GalleryRemote/SlideshowFrame.java index f252350..440755f 100644 --- a/com/gallery/GalleryRemote/SlideshowFrame.java +++ b/com/gallery/GalleryRemote/SlideshowFrame.java @@ -423,8 +423,8 @@ public boolean blockPictureReady(Image image, Picture picture) { } if (picture != null) { - if (picture.getCaption() != null) { - caption = ImageLoaderUtil.stripTags(HTMLEscaper.unescape(picture.getCaption())).trim(); + if (picture.getDescription() != null) { + caption = ImageLoaderUtil.stripTags(HTMLEscaper.unescape(picture.getDescription())).trim(); } else { caption = null; } @@ -443,9 +443,9 @@ public boolean blockPictureReady(Image image, Picture picture) { url = picture.getSource().toString(); } - if (picture.getParentAlbum().getCaption() != null) { + if (picture.getParentAlbum().getDescription() != null) { album = ImageLoaderUtil.stripTags(HTMLEscaper.unescape( - picture.getParentAlbum().getCaption())).trim(); + picture.getParentAlbum().getDescription())).trim(); } else { album = null; } diff --git a/com/gallery/GalleryRemote/model/Album.java b/com/gallery/GalleryRemote/model/Album.java index 864c8bd..3c33f8d 100644 --- a/com/gallery/GalleryRemote/model/Album.java +++ b/com/gallery/GalleryRemote/model/Album.java @@ -73,13 +73,6 @@ public class Album extends GalleryItem implements ListModel, Serializable, Prefe Boolean overrideAddToBeginning = null; int autoResize = 0; - // permissions -- default to true for the sake of old protocols ... - boolean canRead = true; - boolean canAdd = true; - boolean canWrite = true; - boolean canDeleteFrom = true; - boolean canDeleteThisAlbum = true; - boolean canCreateSubAlbum = true; boolean hasFetchedInfo = false; boolean hasFetchedImages = false; @@ -595,10 +588,10 @@ public String toString() { ret.append(" (" + pictures.size() + ")"); } - // using canAdd here, since that's the only operation we perform + // using canEdit here, since that's the only operation we perform // currently. eventually, when we start changing things // on the server, permission support will get more ... interesting. - if (!canAdd) { + if (!canEdit) { ret.append(" ").append(GRI18n.getString(MODULE, "ro")); } @@ -680,58 +673,6 @@ public void setExtraFieldsString(String extraFieldsString) { } } - public void setCanRead(boolean b) { - canRead = b; - } - - public boolean getCanRead() { - return canRead; - } - - public void setCanAdd(boolean b) { - canAdd = b; - } - - public boolean getCanAdd() { - return canAdd; - } - - - public void setCanWrite(boolean b) { - canWrite = b; - } - - public boolean getCanWrite() { - return canWrite; - } - - - public void setCanDeleteFrom(boolean b) { - canDeleteFrom = b; - } - - public boolean getCanDeleteFrom() { - return canDeleteFrom; - } - - - public void setCanDeleteThisAlbum(boolean b) { - canDeleteThisAlbum = b; - } - - public boolean getCanDeleteThisAlbum() { - return canDeleteThisAlbum; - } - - - public void setCanCreateSubAlbum(boolean b) { - canCreateSubAlbum = b; - } - - public boolean getCanCreateSubAlbum() { - return canCreateSubAlbum; - } - public String getSummary() { return summary; } diff --git a/com/gallery/GalleryRemote/model/Gallery.java b/com/gallery/GalleryRemote/model/Gallery.java index 1119f86..5df83d7 100644 --- a/com/gallery/GalleryRemote/model/Gallery.java +++ b/com/gallery/GalleryRemote/model/Gallery.java @@ -47,18 +47,12 @@ public class Gallery extends DefaultTreeModel implements Serializable, PreferenceNames { public static final String MODULE = "Gallery"; - String stUrlString = null; - String pnLoginUrlString = null; - String pnGalleryUrlString = null; - String phpnLoginUrlString = null; - String phpnGalleryUrlString = null; - String glLoginUrlString = null; - String glGalleryUrlString = null; + String urlString = null; String username; String password; String alias; + String key; String userAgent = "Gallery Remote " + GalleryRemote._().properties.getProperty("version"); - int type = TYPE_STANDALONE; boolean autoLoadOnStartup = false; transient GalleryComm comm = null; @@ -73,13 +67,9 @@ public class Gallery extends DefaultTreeModel implements Serializable, Preferenc transient public String forceProtocolEncoding = null; transient public int resizeJpegQuality = -1; transient public boolean dirty = false; + transient public int type = TYPE_STANDALONE; - public static String types[] = new String[]{STANDALONE, POSTNUKE, PHPNUKE, GEEKLOG}; - public static final int TYPE_STANDALONE = 0; - public static final int TYPE_POSTNUKE = 1; - public static final int TYPE_PHPNUKE = 2; - public static final int TYPE_GEEKLOG = 3; - + public static final int TYPE_STANDALONE = 99; public static final int TYPE_APPLET = 99; public static final int TOSTRING_MAXLEN = 40; @@ -148,7 +138,7 @@ public String doNewAlbum(Album a, StatusUpdate su) { // create album synchronously String newAlbumName = getComm(su).newAlbum(su, a.getParentAlbum(), a.getName(), - a.getTitle(), a.getCaption(), false); + a.getTitle(), a.getDescription(), false); // refresh album list asynchronously //fetchAlbums(su); @@ -302,169 +292,31 @@ public static String reformatUrlString(String urlString, boolean trailingSlash) /* Standalone URL */ - public void setStUrlString(String urlString) { + public void setUrlString(String urlString) { if (urlString == null) { - stUrlString = null; + this.urlString = null; return; } - stUrlString = reformatUrlString(urlString, true); + this.urlString = reformatUrlString(urlString, true); - if (!blockWrites && stUrlString != null) { - GalleryRemote._().properties.setProperty(GURL + prefsIndex, stUrlString); + if (!blockWrites && this.urlString != null) { + GalleryRemote._().properties.setProperty(GURL + prefsIndex, this.urlString); } } - public String getStUrlString() { - if (stUrlString != null) { - return stUrlString; + public String getUrlString() { + if (urlString != null) { + return urlString; } else { return "http://example.com/gallery"; } } - /* PostNuke Gallery URL */ - - public void setPnGalleryUrlString(String urlString) { - if (urlString == null) { - pnGalleryUrlString = null; - return; - } - - pnGalleryUrlString = reformatUrlString(urlString, false); - - if (!blockWrites && pnGalleryUrlString != null) { - GalleryRemote._().properties.setProperty(PN_GALLERY_URL + prefsIndex, pnGalleryUrlString); - } - } - - public String getPnGalleryUrlString() { - if (pnGalleryUrlString != null) { - return pnGalleryUrlString.toString(); - } else { - return "http://example.com/modules.php?op=modload&name=gallery&file=index&include=$GALLERYFILE$"; - } - } - - /* PostNuke Login URL */ - - public void setPnLoginUrlString(String urlString) { - if (urlString == null) { - pnLoginUrlString = null; - return; - } - - pnLoginUrlString = reformatUrlString(urlString, false); - - if (!blockWrites && pnLoginUrlString != null) { - GalleryRemote._().properties.setProperty(PN_LOGIN_URL + prefsIndex, pnLoginUrlString); - } - } - - public String getPnLoginUrlString() { - if (pnLoginUrlString != null) { - return pnLoginUrlString.toString(); - } else { - return "http://example.com/user.php?uname=$USERNAME$&pass=$PASSWORD$&module=NS-User&op=login"; - } - } - - /* PHPNuke Gallery URL */ - - public void setPhpnGalleryUrlString(String urlString) { - if (urlString == null) { - phpnGalleryUrlString = null; - return; - } - - phpnGalleryUrlString = reformatUrlString(urlString, false); - - if (!blockWrites && phpnGalleryUrlString != null) { - GalleryRemote._().properties.setProperty(PHPN_GALLERY_URL + prefsIndex, phpnGalleryUrlString); - } - } - - public String getPhpnGalleryUrlString() { - if (phpnGalleryUrlString != null) { - return phpnGalleryUrlString.toString(); - } else { - return "http://example.com/modules.php?name=gallery&include=$GALLERYFILE$"; - } - } - - /* PHPNuke Login URL */ - - public void setPhpnLoginUrlString(String urlString) { - if (urlString == null) { - phpnLoginUrlString = null; - return; - } - - phpnLoginUrlString = reformatUrlString(urlString, false); - - if (!blockWrites && phpnLoginUrlString != null) { - GalleryRemote._().properties.setProperty(PHPN_LOGIN_URL + prefsIndex, phpnLoginUrlString); - } - } - - public String getPhpnLoginUrlString() { - if (phpnLoginUrlString != null) { - return phpnLoginUrlString.toString(); - } else { - return "http://example.com/modules.php?name=Your_Account&op=login&username=$USERNAME$&user_password=$PASSWORD$"; - } - } - - /* GeekLog Gallery URL */ - - public void setGlGalleryUrlString(String urlString) { - if (urlString == null) { - glGalleryUrlString = null; - return; - } - - glGalleryUrlString = reformatUrlString(urlString, false); - - if (!blockWrites && glGalleryUrlString != null) { - GalleryRemote._().properties.setProperty(GL_GALLERY_URL + prefsIndex, glGalleryUrlString); - } - } - - public String getGlGalleryUrlString() { - if (glGalleryUrlString != null) { - return glGalleryUrlString.toString(); - } else { - return "http://example.com/path/to/gallery/$GALLERYFILE$"; - } - } - - /* PostNuke Login URL */ - - public void setGlLoginUrlString(String urlString) { - if (urlString == null) { - glLoginUrlString = null; - return; - } - - glLoginUrlString = reformatUrlString(urlString, false); - - if (!blockWrites && glLoginUrlString != null) { - GalleryRemote._().properties.setProperty(GL_LOGIN_URL + prefsIndex, glLoginUrlString); - } - } - - public String getGlLoginUrlString() { - if (glLoginUrlString != null) { - return glLoginUrlString.toString(); - } else { - return "http://example.com/path/to/geeklog/public_html/users.php?loginname=$USERNAME$&passwd=$PASSWORD$"; - } - } - /* Applet URL */ public void setApUrlString(String urlString) { - stUrlString = urlString; + this.urlString = urlString; } /* Desired User-Agent */ @@ -479,57 +331,9 @@ public String getUserAgent() { /* Generic */ - public URL getLoginUrl(String galleryFile) { - try { - switch (type) { - case TYPE_STANDALONE: - return new URL(stUrlString + galleryFile); - - case TYPE_POSTNUKE: - return new URL(replace(pnLoginUrlString, galleryFile)); - - case TYPE_PHPNUKE: - return new URL(replace(phpnLoginUrlString, galleryFile)); - - case TYPE_GEEKLOG: - return new URL(replace(glLoginUrlString, galleryFile)); - - case TYPE_APPLET: - return new URL(stUrlString); - - default: - throw new RuntimeException("Unknown type: " + type); - } - } catch (MalformedURLException e) { - Log.log(Log.LEVEL_ERROR, MODULE, "Malformed URL."); - Log.logException(Log.LEVEL_ERROR, MODULE, e); - JOptionPane.showMessageDialog((JFrame) su, "Malformed URL (" + e.getMessage() + ")", - "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - } - - public URL getGalleryUrl(String galleryFile) { + public URL getUrl() { try { - switch (type) { - case TYPE_STANDALONE: - return new URL(stUrlString + galleryFile); - - case TYPE_POSTNUKE: - return new URL(replace(pnGalleryUrlString, galleryFile)); - - case TYPE_PHPNUKE: - return new URL(replace(phpnGalleryUrlString, galleryFile)); - - case TYPE_GEEKLOG: - return new URL(replace(glGalleryUrlString, galleryFile)); - - case TYPE_APPLET: - return new URL(stUrlString); - - default: - throw new RuntimeException("Unknown type: " + type); - } + return new URL(urlString); } catch (MalformedURLException e) { Log.log(Log.LEVEL_ERROR, MODULE, "Malformed URL."); Log.logException(Log.LEVEL_ERROR, MODULE, e); @@ -539,28 +343,6 @@ public URL getGalleryUrl(String galleryFile) { } } - String replace(String urlString, String galleryFile) { - StringBuffer sb = new StringBuffer(urlString); - - replace(sb, "$USERNAME$", username); - replace(sb, "$PASSWORD$", password); - replace(sb, "$GALLERYFILE$", galleryFile); - - return sb.toString(); - } - - boolean replace(StringBuffer sb, String token, String value) { - int n = sb.indexOf(token); - - if (n != -1) { - sb.replace(n, n + token.length(), value); - return true; - } - - return false; - } - - /* * **** Gallery properties management **** */ @@ -598,19 +380,24 @@ public void setPassword(String password) { } } - public void setType(int type) { - this.type = type; + public void setAlias(String alias) { + this.alias = alias; if (!blockWrites) { - GalleryRemote._().properties.setProperty(TYPE + prefsIndex, types[type]); + GalleryRemote._().properties.setProperty(ALIAS + prefsIndex, alias); } } - public void setAlias(String alias) { - this.alias = alias; + public void setKey(String key) { + if (!key.equals(this.key)) { - if (!blockWrites) { - GalleryRemote._().properties.setProperty(ALIAS + prefsIndex, alias); + this.key = key; + + logOut(); + + if (!blockWrites) { + GalleryRemote._().properties.setProperty(KEY + prefsIndex, key); + } } } @@ -618,20 +405,18 @@ public String getUsername() { return username; } - public String getPassword() { return password; } - - public int getType() { - return type; - } - public String getAlias() { return alias; } + public String getKey() { + return key; + } + public static Gallery readFromProperties(GalleryProperties p, int prefsIndex, StatusUpdate su) { return readFromProperties(p, prefsIndex, su, true); } @@ -660,25 +445,10 @@ public static Gallery readFromProperties(GalleryProperties p, int prefsIndex, St g.setBlockWrites(true); g.username = username; g.password = password; - g.setStUrlString(url); - - g.setPnLoginUrlString(p.getProperty(PN_LOGIN_URL + prefsIndex)); - g.setPnGalleryUrlString(p.getProperty(PN_GALLERY_URL + prefsIndex)); + g.setUrlString(url); - g.setPhpnLoginUrlString(p.getProperty(PHPN_LOGIN_URL + prefsIndex)); - g.setPhpnGalleryUrlString(p.getProperty(PHPN_GALLERY_URL + prefsIndex)); - - g.setGlLoginUrlString(p.getProperty(GL_LOGIN_URL + prefsIndex)); - g.setGlGalleryUrlString(p.getProperty(GL_GALLERY_URL + prefsIndex)); - - String typeS = p.getProperty(TYPE + prefsIndex); - if (typeS != null) { - int type = Arrays.asList(types).indexOf(typeS); - if (type != -1) { - g.setType(type); - } - } g.setAlias(p.getProperty(ALIAS + prefsIndex)); + g.setKey(p.getProperty(KEY + prefsIndex)); g.forceGalleryVersion = p.getIntProperty(FORCE_GALLERY_VERSION + prefsIndex, 0); g.forceProtocolEncoding = p.getProperty(FORCE_PROTOCOL_ENCODING + prefsIndex); @@ -694,40 +464,24 @@ public static Gallery readFromProperties(GalleryProperties p, int prefsIndex, St public void writeToProperties(PropertiesFile p) { Log.log(Log.LEVEL_TRACE, MODULE, "Writing to properties: " + toString()); - p.setProperty(GURL + prefsIndex, stUrlString); + p.setProperty(GURL + prefsIndex, urlString); p.setProperty(USERNAME + prefsIndex, username); if (getPassword() != null && p.getBooleanProperty(SAVE_PASSWORDS)) { p.setBase64Property(PASSWORD + prefsIndex, password); } else { p.setProperty(PASSWORD + prefsIndex, null); } - p.setProperty(TYPE + prefsIndex, types[type]); if (getAlias() != null && getAlias().length() > 0) { p.setProperty(ALIAS + prefsIndex, getAlias()); } else { p.setProperty(ALIAS + prefsIndex, null); } - - if (pnLoginUrlString != null) { - p.setProperty(PN_LOGIN_URL + prefsIndex, pnLoginUrlString); - } - if (pnGalleryUrlString != null) { - p.setProperty(PN_GALLERY_URL + prefsIndex, pnGalleryUrlString); - } - - if (phpnLoginUrlString != null) { - p.setProperty(PHPN_LOGIN_URL + prefsIndex, phpnLoginUrlString); - } - if (phpnGalleryUrlString != null) { - p.setProperty(PHPN_GALLERY_URL + prefsIndex, phpnGalleryUrlString); + if (getKey() != null && getKey().length() > 0) { + p.setProperty(KEY + prefsIndex, getKey()); + } else { + p.setProperty(KEY + prefsIndex, null); } - if (glLoginUrlString != null) { - p.setProperty(GL_LOGIN_URL + prefsIndex, glLoginUrlString); - } - if (glGalleryUrlString != null) { - p.setProperty(GL_GALLERY_URL + prefsIndex, glGalleryUrlString); - } p.setBooleanProperty(AUTO_LOAD_ON_STARTUP + prefsIndex, autoLoadOnStartup); } @@ -737,12 +491,8 @@ public static void removeFromProperties(PropertiesFile p, int n) { p.setProperty(GURL + n, null); p.setProperty(USERNAME + n, null); p.setProperty(PASSWORD + n, null); - p.setProperty(TYPE + n, null); - p.setProperty(PN_LOGIN_URL + n, null); - p.setProperty(PN_GALLERY_URL + n, null); - p.setProperty(PHPN_LOGIN_URL + n, null); - p.setProperty(PHPN_GALLERY_URL + n, null); p.setProperty(ALIAS + n, null); + p.setProperty(KEY + n, null); p.setProperty(FORCE_GALLERY_VERSION + n, null); p.setProperty(FORCE_PROTOCOL_ENCODING + n, null); p.setProperty(RESIZE_JPEG_QUALITY + n, null); @@ -768,30 +518,7 @@ public String toString(boolean disambiguate) { String tmp = null; - switch (type) { - case TYPE_STANDALONE: - tmp = stUrlString; - break; - - case TYPE_POSTNUKE: - tmp = pnGalleryUrlString; - break; - - case TYPE_PHPNUKE: - tmp = phpnGalleryUrlString; - break; - - case TYPE_GEEKLOG: - tmp = glGalleryUrlString; - break; - - case TYPE_APPLET: - tmp = stUrlString; - break; - - default: - throw new RuntimeException("Unknown type: " + type); - } + tmp = urlString; if (tmp == null) { tmp = "http://"; @@ -852,14 +579,14 @@ public static void uncacheAmbiguousUrl() { * Lazy instantiation for the GalleryComm instance. */ public GalleryComm getComm(StatusUpdate su) { - if (comm == null && stUrlString != null) { - URL url = getGalleryUrl(""); + if (comm == null && urlString != null) { + URL url = getUrl(); if (url != null) { - comm = GalleryComm.getCommInstance(su, url, this); + comm = GalleryComm.getCommInstance(su, this); if (comm == null) { Log.log(Log.LEVEL_ERROR, MODULE, "No protocol implementation found"); - su.error(GRI18n.getString(MODULE, "galleryNotFound", new Object[] {stUrlString})); + su.error(GRI18n.getString(MODULE, "galleryNotFound", new Object[] {urlString})); } } } @@ -939,14 +666,6 @@ public int getResizeJpegQuality() { return resizeJpegQuality; } - public String getForceProtocolEncoding() { - return forceProtocolEncoding; - } - - public void setForceProtocolEncoding(String forceProtocolEncoding) { - this.forceProtocolEncoding = forceProtocolEncoding; - } - public boolean isDirty() { return dirty; } @@ -955,14 +674,6 @@ public void setDirty(boolean dirty) { this.dirty = dirty; } - public String getAuthToken() { - return authToken; - } - - public void setAuthToken(String authToken) { - this.authToken = authToken; - } - public boolean isAutoLoadOnStartup() { return autoLoadOnStartup; } @@ -975,6 +686,14 @@ public void setAutoLoadOnStartup(boolean autoLoadOnStartup) { } } + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + class TreeEnumeration implements Enumeration { protected TreeNode root; protected Enumeration children; @@ -1009,4 +728,8 @@ public Object nextElement() { return retval; } } + + public Album newAlbum() { + return new Album(this); + } } diff --git a/com/gallery/GalleryRemote/model/GalleryItem.java b/com/gallery/GalleryRemote/model/GalleryItem.java index 2ba9159..28970c2 100644 --- a/com/gallery/GalleryRemote/model/GalleryItem.java +++ b/com/gallery/GalleryRemote/model/GalleryItem.java @@ -9,16 +9,16 @@ import com.gallery.GalleryRemote.util.HTMLEscaper; import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.MutableTreeNode; -import java.util.Vector; public abstract class GalleryItem extends DefaultMutableTreeNode implements Cloneable { public static final String MODULE = "GalleryItem"; transient Gallery gallery = null; - String caption = null; + String description = null; + String url = null; + boolean canEdit = true; - transient String escapedCaption = null; + transient String escapedDescription = null; public GalleryItem(Gallery gallery) { this.gallery = gallery; @@ -29,7 +29,7 @@ public Object clone() { newGalleryItem = (GalleryItem) super.clone(); - newGalleryItem.caption = caption; + newGalleryItem.description = description; newGalleryItem.gallery = gallery; return newGalleryItem; @@ -39,64 +39,43 @@ public Album getParentAlbum() { return (Album) getParent(); } - public void setCaption(String caption) { - this.caption = caption; - this.escapedCaption = null; + public void setDescription(String caption) { + this.description = caption; + this.escapedDescription = null; } - public String getCaption() { - return caption; + public String getDescription() { + return description; } - /** - * Cache the escapedCaption because the escaping is lengthy and this is called by a frequent UI method - * - * @return the HTML escaped version of the caption - */ - public String getEscapedCaption() { - if (escapedCaption == null) { - if (caption != null) { - escapedCaption = HTMLEscaper.escape(caption); - } - } - - return escapedCaption; + public String getUrl() { + return url; } - /* - ****** Overriden methods from DefaultMutableTreeNode to send notifications ****** - */ - - /*public void insert(MutableTreeNode newChild, int childIndex) { - if (!allowsChildren) { - throw new IllegalStateException("node does not allow children"); - } else if (newChild == null) { - throw new IllegalArgumentException("new child is null"); - } else if (isNodeAncestor(newChild)) { - throw new IllegalArgumentException("new child is an ancestor"); - } - - MutableTreeNode oldParent = (MutableTreeNode) newChild.getParent(); + public void setUrl(String url) { + this.url = url; + } - if (oldParent != null) { - oldParent.remove(newChild); - } + public void setCanEdit(boolean b) { + canEdit = b; + } - newChild.setParent(this); + public boolean getCanEdit() { + return canEdit; + } - if (children == null) { - children = new Vector(); + /** + * Cache the escapedDescription because the escaping is lengthy and this is called by a frequent UI method + * + * @return the HTML escaped version of the description + */ + public String getEscapedDescription() { + if (escapedDescription == null) { + if (description != null) { + escapedDescription = HTMLEscaper.escape(description); + } } - children.insertElementAt(newChild, childIndex); - gallery.nodesWereInserted(this, new int[] {childIndex}); + return escapedDescription; } - - public void remove(int childIndex) { - MutableTreeNode child = (MutableTreeNode)getChildAt(childIndex); - children.removeElementAt(childIndex); - //gallery.nodesWereRemoved(this, new int[] {childIndex}, new Object[] {child}); - gallery.nodeStructureChanged(this); - child.setParent(null); - }*/ } \ No newline at end of file diff --git a/com/gallery/GalleryRemote/model/Picture.java b/com/gallery/GalleryRemote/model/Picture.java index ab01d7f..391a9b0 100644 --- a/com/gallery/GalleryRemote/model/Picture.java +++ b/com/gallery/GalleryRemote/model/Picture.java @@ -121,7 +121,7 @@ public Object clone() { newPicture.indexOnServer = indexOnServer; newPicture.fileSize = fileSize; - newPicture.escapedCaption = escapedCaption; + newPicture.escapedDescription = escapedDescription; newPicture.indexCache = indexCache; return newPicture; @@ -147,13 +147,13 @@ public void setSource(File source) { } } - setCaption(filename); + setDescription(filename); } else if (GalleryRemote._().properties.getAutoCaptions() == AUTO_CAPTIONS_COMMENT && getExifData() != null && getExifData().getCaption() != null) { - setCaption(getExifData().getCaption()); + setDescription(getExifData().getCaption()); } else if (GalleryRemote._().properties.getAutoCaptions() == AUTO_CAPTIONS_DATE && getExifData() != null && getExifData().getCreationDate() != null) { - setCaption(getExifData().getCreationDate().toString()); + setDescription(getExifData().getCreationDate().toString()); } fileSize = 0; diff --git a/com/gallery/GalleryRemote/prefs/GalleryEditorDialog.java b/com/gallery/GalleryRemote/prefs/GalleryEditorDialog.java index 9c7d723..db864b1 100644 --- a/com/gallery/GalleryRemote/prefs/GalleryEditorDialog.java +++ b/com/gallery/GalleryRemote/prefs/GalleryEditorDialog.java @@ -24,42 +24,17 @@ public class GalleryEditorDialog extends JDialog implements ActionListener { JPanel jMainPanel = new JPanel(); JLabel jUsernameLabel = new JLabel(); JLabel jPasswordLabel = new JLabel(); - JLabel jTypeLabel = new JLabel(); - JLabel jPnLoginUrlLabel = new JLabel(); - JLabel jPnGalleryUrlLabel = new JLabel(); - JLabel jPnHelpLabel = new JLabel(); - JLabel jStandaloneUrlLabel = new JLabel(); - JLabel jStandaloneHelpLabel = new JLabel(); - JLabel jPhpnLoginUrlLabel = new JLabel(); - JLabel jPhpnGalleryUrlLabel = new JLabel(); - JLabel jPhpnHelpLabel = new JLabel(); - JLabel jGlLoginUrlLabel = new JLabel(); - JLabel jGlGalleryUrlLabel = new JLabel(); - JLabel jGlHelpLabel = new JLabel(); + JLabel jUrlLabel = new JLabel(); + JLabel jUrlHelpLabel = new JLabel(); JLabel jAliasLabel = new JLabel(); - - JComboBox jType = new JComboBox(); - JPanel jStylePanel = new JPanel(); - CardLayout jStyleLayout = new CardLayout(); + JLabel jKeyLabel = new JLabel(); JTextField jUsername = new JTextField(); JPasswordField jPassword = new JPasswordField(); JTextField jAlias = new JTextField(); + JTextField jKey = new JTextField(); - JPanel jPostNuke = new JPanel(); - JTextField jPnLoginUrl = new JTextField(); - JTextField jPnGalleryUrl = new JTextField(); - - JPanel jPHPNuke = new JPanel(); - JTextField jPhpnLoginUrl = new JTextField(); - JTextField jPhpnGalleryUrl = new JTextField(); - - JPanel jGeekLog = new JPanel(); - JTextField jGlLoginUrl = new JTextField(); - JTextField jGlGalleryUrl = new JTextField(); - - JPanel jStandalone = new JPanel(); - JTextField jStandaloneUrl = new JTextField(); + JTextField jUrl = new JTextField(); JCheckBox jAutoLogin = new JCheckBox(); @@ -95,12 +70,6 @@ private void jbInit() { jAlias.setToolTipText(GRI18n.getString(MODULE, "aliasTip")); jUsernameLabel.setText(GRI18n.getString(MODULE, "username")); jPasswordLabel.setText(GRI18n.getString(MODULE, "passwd")); - jTypeLabel.setText(GRI18n.getString(MODULE, "type")); - jStylePanel.setLayout(jStyleLayout); - - jType.setToolTipText(GRI18n.getString(MODULE, "typeTip")); - jType.setEditable(false); - jType.setModel(new DefaultComboBoxModel(Gallery.types)); jOk.setText(GRI18n.getString("Common", "OK")); jOk.setActionCommand("OK"); @@ -109,112 +78,43 @@ private void jbInit() { jButtonPanel.setLayout(gridLayout1); gridLayout1.setHgap(5); - jStandalone.setLayout(new GridBagLayout()); - jStandaloneUrlLabel.setText(GRI18n.getString(MODULE, "stndAln")); - jStandaloneHelpLabel.setText(GRI18n.getString(MODULE, "stndAlnHlp")); - jStandaloneHelpLabel.setVerticalAlignment(SwingConstants.TOP); - jStandaloneHelpLabel.setVerticalTextPosition(SwingConstants.CENTER); - - jPostNuke.setLayout(new GridBagLayout()); - jPnLoginUrlLabel.setText(GRI18n.getString(MODULE, "pnLogin")); - jPnLoginUrlLabel.setVerticalAlignment(SwingConstants.TOP); - jPnLoginUrlLabel.setVerticalTextPosition(SwingConstants.CENTER); - jPnGalleryUrlLabel.setText(GRI18n.getString(MODULE, "gllryUrl")); - jPnHelpLabel.setPreferredSize(new Dimension(300, 80)); - jPnHelpLabel.setText(GRI18n.getString(MODULE, "pnHelp")); - jPnHelpLabel.setVerticalAlignment(SwingConstants.TOP); - - jPHPNuke.setLayout(new GridBagLayout()); - jPhpnLoginUrlLabel.setText(GRI18n.getString(MODULE, "phpNukeLogin")); - jPhpnLoginUrlLabel.setVerticalAlignment(SwingConstants.TOP); - jPhpnLoginUrlLabel.setVerticalTextPosition(SwingConstants.CENTER); - jPhpnGalleryUrlLabel.setText(GRI18n.getString(MODULE, "gllryUrl")); - jPhpnHelpLabel.setPreferredSize(new Dimension(300, 80)); - jPhpnHelpLabel.setText(GRI18n.getString(MODULE, "phpNukeHelp")); - jPhpnHelpLabel.setVerticalAlignment(SwingConstants.TOP); - - jGeekLog.setLayout(new GridBagLayout()); - jGlLoginUrlLabel.setText(GRI18n.getString(MODULE, "glLogin")); - jGlLoginUrlLabel.setVerticalAlignment(SwingConstants.TOP); - jGlLoginUrlLabel.setVerticalTextPosition(SwingConstants.CENTER); - jGlGalleryUrlLabel.setText(GRI18n.getString(MODULE, "gllryUrl")); - jGlHelpLabel.setPreferredSize(new Dimension(300, 80)); - jGlHelpLabel.setText(GRI18n.getString(MODULE, "glHelp")); - jGlHelpLabel.setVerticalAlignment(SwingConstants.TOP); - + jUrlLabel.setText(GRI18n.getString(MODULE, "stndAln")); + /*jUrlHelpLabel.setText(GRI18n.getString(MODULE, "stndAlnHlp")); + jUrlHelpLabel.setVerticalAlignment(SwingConstants.TOP); + jUrlHelpLabel.setVerticalTextPosition(SwingConstants.CENTER);*/ + jAutoLogin.setText(GRI18n.getString(MODULE, "autoLogin")); this.getContentPane().add(jMainPanel, BorderLayout.CENTER); - jMainPanel.add(jUsernameLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0)); jMainPanel.add(jAliasLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + jMainPanel.add(jUsernameLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0)); jMainPanel.add(jPasswordLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0)); - jMainPanel.add(jTypeLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + jMainPanel.add(jKeyLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0)); + jMainPanel.add(jUrlLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 5, 5), 0, 0)); jMainPanel.add(jAlias, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 5), 0, 0)); jMainPanel.add(jUsername, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); jMainPanel.add(jPassword, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); - jMainPanel.add(jAutoLogin, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 - , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); - jMainPanel.add(jType, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0 + jMainPanel.add(jKey, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); - jMainPanel.add(jStylePanel, new GridBagConstraints(0, 5, 4, 1, 1.0, 1.0 - , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 5, 5, 5), 0, 0)); + jMainPanel.add(jUrl, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0 + , GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); + /*jMainPanel.add(jUrlHelpLabel, new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0 + , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 20, 0, 0), 0, 0));*/ + jMainPanel.add(jAutoLogin, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0 + , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); jMainPanel.add(jButtonPanel, new GridBagConstraints(0, 6, 2, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0)); jButtonPanel.add(jOk, null); jButtonPanel.add(jCancel, null); - jStylePanel.add(jPostNuke, Gallery.types[Gallery.TYPE_POSTNUKE]); - jPostNuke.add(jPnLoginUrlLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 0, 5), 0, 0)); - jPostNuke.add(jPnLoginUrl, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 - , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jPostNuke.add(jPnGalleryUrlLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 0, 5), 0, 0)); - jPostNuke.add(jPnGalleryUrl, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 - , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jPostNuke.add(jPnHelpLabel, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0 - , GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(0, 20, 0, 0), 0, 0)); - - jStylePanel.add(jPHPNuke, Gallery.types[Gallery.TYPE_PHPNUKE]); - jPHPNuke.add(jPhpnLoginUrlLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 0, 5), 0, 0)); - jPHPNuke.add(jPhpnLoginUrl, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 - , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jPHPNuke.add(jPhpnGalleryUrlLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 0, 5), 0, 0)); - jPHPNuke.add(jPhpnGalleryUrl, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 - , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jPHPNuke.add(jPhpnHelpLabel, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0 - , GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(0, 20, 0, 0), 0, 0)); - - jStylePanel.add(jGeekLog, Gallery.types[Gallery.TYPE_GEEKLOG]); - jGeekLog.add(jGlLoginUrlLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 0, 5), 0, 0)); - jGeekLog.add(jGlLoginUrl, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 - , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jGeekLog.add(jGlGalleryUrlLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 0, 5), 0, 0)); - jGeekLog.add(jGlGalleryUrl, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 - , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jGeekLog.add(jGlHelpLabel, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0 - , GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(0, 20, 0, 0), 0, 0)); - - jStylePanel.add(jStandalone, Gallery.types[Gallery.TYPE_STANDALONE]); - jStandalone.add(jStandaloneUrlLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 20, 5, 5), 0, 0)); - jStandalone.add(jStandaloneUrl, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 - , GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - jStandalone.add(jStandaloneHelpLabel, new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0 - , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 20, 0, 0), 0, 0)); - - jType.addActionListener(this); jOk.addActionListener(this); jCancel.addActionListener(this); @@ -225,43 +125,24 @@ public void resetUIState() { jUsername.setText(gallery.getUsername()); jPassword.setText(gallery.getPassword()); jAlias.setText(gallery.getAlias() == null?"":gallery.getAlias()); + jKey.setText(gallery.getKey() == null?"":gallery.getKey()); - jType.setSelectedIndex(gallery.getType()); - String panel = (String) jType.getSelectedItem(); - jStyleLayout.show(jStylePanel, panel); - - jStandaloneUrl.setText(gallery.getStUrlString()); - - jPnGalleryUrl.setText(gallery.getPnGalleryUrlString()); - jPnLoginUrl.setText(gallery.getPnLoginUrlString()); + jUrl.setText(gallery.getUrlString()); - jPhpnGalleryUrl.setText(gallery.getPhpnGalleryUrlString()); - jPhpnLoginUrl.setText(gallery.getPhpnLoginUrlString()); - jGlGalleryUrl.setText(gallery.getGlGalleryUrlString()); - jGlLoginUrl.setText(gallery.getGlLoginUrlString()); - jAutoLogin.setSelected(gallery.isAutoLoadOnStartup()); } public void readUIState() { gallery.setUsername(jUsername.getText()); gallery.setPassword(jPassword.getText()); - gallery.setType(jType.getSelectedIndex()); String alias = jAlias.getText().trim(); gallery.setAlias(alias.length() == 0?null:alias); + String key = jKey.getText().trim(); + gallery.setKey(key.length() == 0?null:key); - gallery.setStUrlString(jStandaloneUrl.getText()); - - gallery.setPnLoginUrlString(jPnLoginUrl.getText()); - gallery.setPnGalleryUrlString(jPnGalleryUrl.getText()); - - gallery.setPhpnLoginUrlString(jPhpnLoginUrl.getText()); - gallery.setPhpnGalleryUrlString(jPhpnGalleryUrl.getText()); + gallery.setUrlString(jUrl.getText()); - gallery.setGlLoginUrlString(jGlLoginUrl.getText()); - gallery.setGlGalleryUrlString(jGlGalleryUrl.getText()); - gallery.setAutoLoadOnStartup(jAutoLogin.isSelected()); } @@ -275,9 +156,6 @@ public void actionPerformed(ActionEvent e) { setVisible(false); } else if (cmd.equals("Cancel")) { setVisible(false); - } else if (cmd.equals("comboBoxChanged")) { - String panel = (String) jType.getSelectedItem(); - jStyleLayout.show(jStylePanel, panel); } else { Log.log(Log.LEVEL_ERROR, MODULE, "Unknown command: " + cmd); } diff --git a/com/gallery/GalleryRemote/prefs/PreferenceNames.java b/com/gallery/GalleryRemote/prefs/PreferenceNames.java index 8084549..42082d6 100644 --- a/com/gallery/GalleryRemote/prefs/PreferenceNames.java +++ b/com/gallery/GalleryRemote/prefs/PreferenceNames.java @@ -40,20 +40,10 @@ public interface PreferenceNames { // URL panel public static final String USERNAME = "username."; public static final String PASSWORD = "password."; - public static final String TYPE = "type."; public static final String GURL = "url."; - public static final String STANDALONE = "Standalone"; - public static final String POSTNUKE = "PostNuke"; - public static final String PHPNUKE = "PHPNuke"; - public static final String GEEKLOG = "GeekLog"; public static final String APPLET = "Applet"; - public static final String PN_GALLERY_URL = "pnGalleryUrl."; - public static final String PN_LOGIN_URL = "pnLoginUrl."; - public static final String PHPN_GALLERY_URL = "phpnGalleryUrl."; - public static final String PHPN_LOGIN_URL = "phpnLoginUrl."; - public static final String GL_GALLERY_URL = "glGalleryUrl."; - public static final String GL_LOGIN_URL = "glLoginUrl."; public static final String ALIAS = "alias."; + public static final String KEY = "key."; public static final String FORCE_GALLERY_VERSION = "forceGalleryVersion."; public static final String FORCE_PROTOCOL_ENCODING = "forceProtocolEncoding."; public static final String RESIZE_JPEG_QUALITY = "resizeJpegQuality."; diff --git a/com/gallery/GalleryRemote/prefs/URLPanel.java b/com/gallery/GalleryRemote/prefs/URLPanel.java index 8b40730..f9dcd3c 100644 --- a/com/gallery/GalleryRemote/prefs/URLPanel.java +++ b/com/gallery/GalleryRemote/prefs/URLPanel.java @@ -137,7 +137,7 @@ public void actionPerformed(ActionEvent e) { resetUIState(); } } else if (cmd.equals("Delete")) { - Object[] params = {g.getGalleryUrl("")}; + Object[] params = {g.getUrl()}; int n = JOptionPane.showConfirmDialog(this, GRI18n.getString(MODULE, "delConfirm", params), GRI18n.getString(MODULE, "delete"), JOptionPane.WARNING_MESSAGE, @@ -184,18 +184,7 @@ public void resetUIState() { if (selectedGallery != null) { sb.append(""); - if (selectedGallery.getType() == Gallery.TYPE_STANDALONE) { - sb.append(GRI18n.getString(MODULE, "gllryURL")).append(selectedGallery.getStUrlString()).append("
"); - } else if (selectedGallery.getType() == Gallery.TYPE_POSTNUKE) { - sb.append(GRI18n.getString(MODULE, "pnLoginURL")).append(selectedGallery.getPnLoginUrlString()).append("
"); - sb.append(GRI18n.getString(MODULE, "pnGllryURL")).append(selectedGallery.getPnGalleryUrlString()).append("
"); - } else if (selectedGallery.getType() == Gallery.TYPE_PHPNUKE) { - sb.append(GRI18n.getString(MODULE, "phpnLoginURL")).append(selectedGallery.getPhpnLoginUrlString()).append("
"); - sb.append(GRI18n.getString(MODULE, "phpnGllryURL")).append(selectedGallery.getPhpnGalleryUrlString()).append("
"); - } else if (selectedGallery.getType() == Gallery.TYPE_GEEKLOG) { - sb.append(GRI18n.getString(MODULE, "glLoginURL")).append(selectedGallery.getGlLoginUrlString()).append("
"); - sb.append(GRI18n.getString(MODULE, "glGllryURL")).append(selectedGallery.getGlGalleryUrlString()).append("
"); - } + sb.append(GRI18n.getString(MODULE, "gllryURL")).append(selectedGallery.getUrlString()).append("
"); String username = selectedGallery.getUsername(); if (username == null || username.length() == 0) { diff --git a/com/gallery/GalleryRemote/prefs/panes.properties b/com/gallery/GalleryRemote/prefs/panes.properties index 39368e2..27e658a 100644 --- a/com/gallery/GalleryRemote/prefs/panes.properties +++ b/com/gallery/GalleryRemote/prefs/panes.properties @@ -2,6 +2,6 @@ pane.1=com.gallery.GalleryRemote.prefs.GeneralPanel pane.2=com.gallery.GalleryRemote.prefs.UploadPanel pane.3=com.gallery.GalleryRemote.prefs.SlideshowPanel pane.4=com.gallery.GalleryRemote.prefs.URLPanel -pane.5=com.gallery.GalleryRemote.prefs.ProxyPanel -pane.6=com.gallery.GalleryRemote.prefs.QuickConfigPanel +#pane.5=com.gallery.GalleryRemote.prefs.ProxyPanel +#pane.6=com.gallery.GalleryRemote.prefs.QuickConfigPanel #pane.6=com.gallery.GalleryRemote.prefs.FilePanel diff --git a/com/gallery/GalleryRemote/resources/GRResources.properties b/com/gallery/GalleryRemote/resources/GRResources.properties index 4a27829..8eb359d 100644 --- a/com/gallery/GalleryRemote/resources/GRResources.properties +++ b/com/gallery/GalleryRemote/resources/GRResources.properties @@ -76,28 +76,6 @@ GEdiDlog.typeTip = Use Standalone when your Gallery is not embedded inside a Con GEdiDlog.stndAln = Gallery URL GEdiDlog.stndAlnHlp = The Gallery URL is the URL users would use to connect to your Gallery. GEdiDlog.gllryUrl = Gallery Module URL -GEdiDlog.pnLogin = PostNuke Login URL -GEdiDlog.pnHelp = Where $USERNAME$ and $PASSWORD$ will be replaced when Gallery \ - Remote tries to log in by the username and password you enter above \ - and $GALLERYFILE$ is replaced with the PHP file Gallery Remote uses \ - to communicate with Gallery (usually gallery_remote2.php).
\ - The name parameter is the PostNuke module name of your gallery; set it \ - accordingly.
\ - This functionality is only available with Gallery 1.3.5 (beta 10) and later. -GEdiDlog.phpNukeLogin = PHPNuke Login URL -GEdiDlog.phpNukeHelp = Where $USERNAME$ and $PASSWORD$ will be replaced when Gallery \ - Remote tries to log in by the username and password you enter above \ - and $GALLERYFILE$ is replaced with the PHP file Gallery Remote uses \ - to communicate with Gallery (usually gallery_remote2.php).
\ - The name parameter is the PHPNuke module name of your gallery; set it \ - accordingly.
\ - This functionality is only available with Gallery 1.3.5 (beta 10) and later. -GEdiDlog.glLogin = GeekLog Login URL -GEdiDlog.glHelp = Where $USERNAME$ and $PASSWORD$ will be replaced when Gallery \ - Remote tries to log in by the username and password you enter above \ - and $GALLERYFILE$ is replaced with the PHP file Gallery Remote uses \ - to communicate with Gallery (usually gallery_remote2.php).
\ - This functionality is only available with Gallery 1.3.5 (beta 10) and later. GEdiDlog.alias = Alias GEdiDlog.aliasTip = A short name to describe the Gallery.
It will be used in Gallery Remote to display a short \ name for the Gallery.
Leave empty to use the URL. diff --git a/com/gallery/GalleryRemote/util/ImageUtils.java b/com/gallery/GalleryRemote/util/ImageUtils.java index 2b65794..ff38cbe 100644 --- a/com/gallery/GalleryRemote/util/ImageUtils.java +++ b/com/gallery/GalleryRemote/util/ImageUtils.java @@ -811,7 +811,7 @@ public static URLConnection openUrlConnection(URL pictureUrl, Picture p) throws if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } - conn.addRequestProperty("Referer", p.getAlbumOnServer().getGallery().getGalleryUrl("").toString()); + conn.addRequestProperty("Referer", p.getAlbumOnServer().getGallery().getUrl().toString()); Cookie[] cookies = CookieModule.listAllCookies(); for (int i = 0; i < cookies.length; i++) { conn.addRequestProperty("Cookie", cookies[i].toString()); diff --git a/com/gallery/GalleryRemote/util/PostChangeLog.java b/com/gallery/GalleryRemote/util/PostChangeLog.java deleted file mode 100644 index a079083..0000000 --- a/com/gallery/GalleryRemote/util/PostChangeLog.java +++ /dev/null @@ -1,209 +0,0 @@ -package com.gallery.GalleryRemote.util; - -import HTTPClient.*; -import com.gallery.GalleryRemote.prefs.PropertiesFile; -import org.apache.tools.ant.BuildException; - -import java.io.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Created by IntelliJ IDEA. - * User: paour - * Date: Oct 8, 2003 - */ -public class PostChangeLog extends org.apache.tools.ant.Task { - public static final String baseUrl = "http://www.gallery2.hu/download/GalleryRemote/"; - - public void execute() throws BuildException { - PropertiesFile changeProps = new PropertiesFile("postchangelog"); - PropertiesFile defaultProps = new PropertiesFile("defaults"); - - // should we even be doing this? - boolean active = changeProps.getBooleanProperty("active", false); - if (!active) { - System.out.println("Not active"); - return; - } - - // find out what the current and last builds are - int siteBetaBuild = changeProps.getIntProperty("siteBetaBuild", 0); - String currentBuildS = defaultProps.getProperty("version"); - - Pattern buildPattern = Pattern.compile(".*-b(\\d*)"); - Matcher m = buildPattern.matcher(currentBuildS); - if (!m.matches()) { - System.out.println("Not a beta build"); - return; - } - - int currentBetaBuild = Integer.parseInt(m.group(1)); - if (currentBetaBuild == siteBetaBuild) { - System.out.println("Current and site beta builds are the same: nothing to do"); - return; - } - - // parse the ChangeLog - try { - Pattern header = Pattern.compile("([0-9\\-])\\s*(.*)\\s*<(.*)> \\((.*)\\)"); - //String date = null; - //String author = null; - //String email = null; - String version = null; - StringBuffer changes = new StringBuffer(); - - changes.append("Changes between b").append(siteBetaBuild).append(" and b").append(currentBetaBuild).append(": "); - - File changeLog = new File("ChangeLog"); - BufferedReader in = new BufferedReader(new FileReader(changeLog)); - - String line = null; - while ((line = in.readLine()) != null) { - System.out.println("Got line: " + line); - m = header.matcher(line); - - if (m.matches()) { - // got a header - version = m.group(4); - System.out.println("Got a header. Version: " + version); - - m = buildPattern.matcher(version); - if (m.matches()) { - int myBetaBuild = Integer.parseInt(m.group(1)); - System.out.println("Beta version: " + myBetaBuild); - - if (myBetaBuild == siteBetaBuild) { - System.out.println("Found the right beta: stopping"); - break; - } - } else { - System.out.println("Found a non-beta... guess it stops here"); - break; - } - } else { - // got just a normal line - line = line.trim(); - - if (line.length() > 0) { - if (line.startsWith("*")) { - changes.append("\\n").append(line).append(" "); - } else { - changes.append(line.trim()).append(" "); - } - } - } - } - - StringBuffer note = new StringBuffer(); - note.append("version=").append(currentBuildS).append('\n'); - note.append("releaseDate=").append(defaultProps.getProperty("releaseDate")).append('\n'); - note.append("releaseUrl=").append(baseUrl).append("gallery_remote_") - .append(defaultProps.getProperty("version")).append(".zip").append('\n'); - note.append("releaseUrlMac=").append(baseUrl).append("GalleryRemote.") - .append(defaultProps.getProperty("version")).append(".MacOSX.NoVM.tgz").append('\n'); - note.append("releaseNotes=").append(changes.toString()); - - System.out.println("Got changes: " + changes); - - NVPair form_data_login[] = { - new NVPair("name", changeProps.getProperty("username")), - new NVPair("pass", changeProps.getProperty("password")), - new NVPair("form_id", "user_login"), - new NVPair("op", "Log in") - }; - - // set cookie handling - CookieModule.setCookiePolicyHandler(new CookiePolicyHandler() { - public boolean acceptCookie(Cookie cookie, RoRequest req, RoResponse resp) { - System.out.println("Accepting cookie: " + cookie); - return true; - } - - public boolean sendCookie(Cookie cookie, RoRequest req) { - System.out.println("Sending cookie: " + cookie); - return true; - } - }); - - HTTPConnection mConnection = new HTTPConnection("gallery.menalto.com"); - HTTPResponse rsp = null; - String response = null; - - // get login - rsp = mConnection.Get("/user"); - response = new String(rsp.getData()).trim(); - System.out.println("Get login response: " + response); - - System.out.println(); System.out.println(); - System.out.println("*****************************"); - - // login - rsp = mConnection.Post("/user", form_data_login); - response = new String(rsp.getData()).trim(); - System.out.println("Login response: " + response); - - System.out.println(); System.out.println(); - System.out.println("*****************************"); - - // get form - rsp = mConnection.Get("/admin/gmc_versioncheck/edit/5"); - response = new String(rsp.getData()).trim(); - System.out.println("Get form response: " + response); - - System.out.println(); System.out.println(); - System.out.println("*****************************"); - - Pattern p = Pattern.compile(".*.*", Pattern.DOTALL); - m = p.matcher(response); - - if (m.matches()) { - String formToken = m.group(1); - System.out.println("Form token: " + formToken); - - NVPair form_data_submit[] = { - new NVPair("url", "galleryremote/beta"), - new NVPair("note", note.toString()), - new NVPair("id", "5"), - new NVPair("form_token", formToken), - new NVPair("form_id", "gmc_versioncheck_form"), - new NVPair("op", "Update") - }; - - // login - rsp = mConnection.Post("/admin/gmc_versioncheck/edit/5", form_data_submit); - response = new String(rsp.getData()).trim(); - System.out.println("Submit response: " + response); - - // activate - //rsp = mConnection.Get("/admin/galleryremote/current/beta/1"); - //response = new String(rsp.getData()).trim(); - //System.out.println("Activate response: " + response); - - // test - HTTPConnection mConnection1 = new HTTPConnection("gallery.sourceforge.net"); - rsp = mConnection1.Get("/gallery_remote_version_check_beta.php"); - response = new String(rsp.getData()).trim(); - System.out.println("Test response: " + response); - - if (response.startsWith("version=" + currentBuildS)) { - // worked - System.out.println("Success: writing to postlogchange properties"); - changeProps.setIntProperty("siteBetaBuild", currentBetaBuild); - changeProps.write(); - } else { - System.out.println("Failed to update Menalto"); - } - } else { - System.out.println("Could not find the form_token"); - System.out.println("Failed to update Menalto"); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ModuleException e) { - e.printStackTrace(); - } - } -}