/
GalleryComm2.java
872 lines (736 loc) · 26.9 KB
/
GalleryComm2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
/*
* 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 java.io.IOException;
import java.io.StringBufferInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.SocketException;
import java.util.*;
import HTTPClient.Codecs;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.ModuleException;
import HTTPClient.NVPair;
import com.gallery.GalleryRemote.model.Album;
import com.gallery.GalleryRemote.model.Gallery;
import com.gallery.GalleryRemote.model.Picture;
import com.gallery.GalleryRemote.util.HTMLEscaper;
import com.gallery.GalleryRemote.prefs.PreferenceNames;
/**
* The GalleryComm2 class implements the client side of the Gallery remote
* protocol <a href="http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/gallery/gallery/gallery_remote.php?rev=HEAD&content-type=text/vnd.viewcvs-text">
* version 2</a>.
*
* @author jackodog
* @author paour
* @author <a href="mailto:tim_miller@users.sourceforge.net">Tim Miller</a>
*/
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";
/* -------------------------------------------------------------------------
* INSTANCE VARIABLES
*/
/**
* The gallery this GalleryComm2 instance is attached to.
*/
protected final Gallery g;
/**
* The process ID for StatusUpdate. XXX: What's -1? -- tim
* -1 is an initialization value. means no id.
*/
int pId = -1;
/**
* 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;
/**
* The capabilities for 2.1
*/
private static int[] capabilities1;
private static int[] capabilities2;
/* -------------------------------------------------------------------------
* 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 };
Arrays.sort(capabilities);
}
/* -------------------------------------------------------------------------
* 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 ) {
doTask( new UploadTask( su ), 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 albumInfo( 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)
*
* @param su an instance that implements the StatusUpdate interface.
* @param a if null, create the album in the root of the gallery; otherwise
* create as a child of the given album
*/
public void newAlbum( StatusUpdate su, Album parentAlbum,
String newAlbumName, String newAlbumTitle,
String newAlbumDesc, boolean async ) {
doTask( new NewAlbumTask( su, parentAlbum, newAlbumName,
newAlbumTitle, newAlbumDesc ), async );
}
public void logOut() {
isLoggedIn = 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, String message) {
Log.log(Log.INFO, MODULE, message);
if (pId != -1) {
su.setStatus(message);
} else {
su.updateProgressStatus(pId, message);
}
}
void error( StatusUpdate su, String message) {
status(su, message);
su.error( message );
}
void trace(String message) {
Log.log(Log.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;
public GalleryTask( StatusUpdate su ) {
if ( su == null ) {
this.su = new StatusUpdateAdapter(){};
} else {
this.su = su;
}
}
public void run() {
su.setInProgress(true);
if ( ! isLoggedIn ) {
if ( !login() ) {
Log.log(Log.TRACE, MODULE, "Failed to log in" + g.toString());
su.setInProgress(false);
return;
}
isLoggedIn = true;
} else {
Log.log(Log.TRACE, MODULE, "Still logged in to " + g.toString());
}
runTask();
su.setInProgress(false);
}
public void interrupt() {
interrupt = true;
}
abstract void runTask();
/**
* POSTSs a request to the Gallery server with the given form data.
*/
Properties requestResponse( NVPair form_data[] ) throws GR2Exception, ModuleException, IOException {
return requestResponse( form_data, null, g.getGalleryUrl(SCRIPT_NAME), true);
}
Properties requestResponse( NVPair form_data[], URL galUrl ) throws GR2Exception, ModuleException, IOException {
return requestResponse( form_data, null, galUrl, true);
}
/**
* POSTSs a request to the Gallery server with the given form data. If data is
* not null, a multipart MIME post is performed.
*/
Properties requestResponse( NVPair form_data[], byte[] data, URL galUrl, boolean checkResult) throws GR2Exception, ModuleException, IOException {
// assemble the URL
String urlPath = galUrl.getFile();
//urlPath = urlPath + ( (urlPath.endsWith( "/" )) ? SCRIPT_NAME : "/" + SCRIPT_NAME );
Log.log(Log.TRACE, MODULE, "Url: " + urlPath );
// create a connection
HTTPConnection mConnection = new HTTPConnection( galUrl );
HTTPResponse rsp = null;
// 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);
}
// handle 30x redirects
if (rsp.getStatusCode() >= 300 && rsp.getStatusCode() < 400) {
// retry, the library will have fixed the URL
status(su, "Received redirect, following...");
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);
}
}
// handle response
if (rsp.getStatusCode() >= 300) {
throw new GR2Exception( "HTTP POST failed (HTTP " + rsp.getStatusCode() + " " + rsp.getReasonLine() + ")");
} else {
// load response
String response = new String(rsp.getData()).trim();
Log.log(Log.TRACE, MODULE, response);
if (checkResult) {
// validate response
int i = response.indexOf(PROTOCOL_MAGIC);
if ( i == -1 ) {
throw new GR2Exception("Server contacted, but Gallery not found at this URL (" + galUrl.toString() + ")");
} else if ( i > 0 ) {
response = response.substring(i);
Log.log(Log.TRACE, MODULE, "Short response: " + response);
}
Properties p = new Properties();
p.load( new StringBufferInputStream( response ) );
return p;
} else {
return null;
}
}
}
private boolean login() {
status(su, "Logging in to " + g.toString());
if (g.getType() != Gallery.TYPE_STANDALONE) {
try {
requestResponse( null, null, g.getLoginUrl(SCRIPT_NAME), false );
} catch (IOException ioe) {
Log.logException(Log.ERROR, MODULE, ioe);
error(su, "Error: " + ioe.toString());
} catch (ModuleException me) {
Log.logException(Log.ERROR, MODULE, me);
error(su, "Error handling request: " + me.getMessage());
}
}
// setup protocol parameters
NVPair form_data[] = {
new NVPair("cmd", "login"),
new NVPair("protocol_version", PROTOCOL_VERSION),
new NVPair("uname", g.getUsername()),
new NVPair("password", g.getPassword())
};
Log.log(Log.TRACE, MODULE, "login parameters: " + Arrays.asList(form_data));
// make the request
try {
// load and validate the response
Properties p = requestResponse( form_data, g.getGalleryUrl(SCRIPT_NAME) );
if ( GR_STAT_SUCCESS.equals( p.getProperty( "status" ) ) ) {
status(su, "Logged in");
try {
String serverVersion = p.getProperty( "server_version" );
int i = serverVersion.indexOf( "." );
serverMinorVersion = Integer.parseInt( serverVersion.substring( i+1 ) );
Log.log(Log.TRACE, MODULE, "Server minor version: " + serverMinorVersion);
if (serverMinorVersion == 1) {
// we have more than the 2.0 capabilities, we have 2.1 capabilities.
capabilities = capabilities1;
} else if (serverMinorVersion >= 2) {
// we have more than the 2.1 capabilities, we have 2.2 capabilities.
capabilities = capabilities2;
}
} catch (Exception e) {
Log.log( Log.ERROR, MODULE, "Malformed server_version: " + p.getProperty( "server_version" ) );
Log.logException(Log.ERROR, MODULE, e);
}
return true;
} else if (GR_STAT_PASSWD_WRONG.equals(p.getProperty("status"))) {
error(su, "Invalid username/password.\n\n" +
"If your Gallery is embedded inside a CMS like PostNuke,\n" +
"you need to use the \"native\" (non-embedded) Gallery URL to log in,\n" +
"as well as the native Gallery user and password.\n" +
"You can test these by trying to go the native URL and trying to log in.");
return false;
} else {
error(su, "Login Error: " + p.getProperty( "status_text" ));
return false;
}
} catch ( GR2Exception gr2e ) {
Log.logException(Log.ERROR, MODULE, gr2e );
error(su, "Error: " + gr2e.getMessage());
} catch (IOException ioe) {
Log.logException(Log.ERROR, MODULE, ioe);
error(su, "Error: " + ioe.toString());
} catch (ModuleException me) {
Log.logException(Log.ERROR, MODULE, me);
error(su, "Error handling request: " + me.getMessage());
}
return false;
}
}
/**
* An extension of GalleryTask to handle uploading photos.
*/
class UploadTask extends GalleryTask {
UploadTask( StatusUpdate su ) {
super(su);
}
void runTask() {
ArrayList pictures = g.getAllPictures();
pId = su.startProgress(0, pictures.size(), "Uploading pictures", false);
// upload each file, one at a time
boolean allGood = true;
int uploadedCount = 0;
Iterator iter = pictures.iterator();
while (iter.hasNext() && allGood && !interrupt) {
Picture p = (Picture) iter.next();
su.updateProgressStatus(pId, "Uploading " + p.toString()
+ " (" + (uploadedCount + 1) + "/" + pictures.size() + ")");
allGood = uploadPicture(p);
su.updateProgressValue(pId, uploadedCount++);
if (allGood) {
p.getAlbum().removePicture(p);
}
}
if (allGood) {
su.stopProgress(pId, "Upload complete");
} else {
su.stopProgress(pId, "Upload failed");
}
pId = -1;
}
boolean uploadPicture(Picture p) {
try {
// can't set null as an NVPair value
String caption = p.getCaption();
caption = (caption == null) ? "" : caption;
if (GalleryRemote.getInstance().properties.getBooleanProperty(HTML_ESCAPE_CAPTIONS)) {
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.getAlbum().getName()),
new NVPair("caption", caption )
};
Log.log(Log.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(opts, afile, hdrs);
// load and validate the response
Properties props = requestResponse( hdrs, data, g.getGalleryUrl(SCRIPT_NAME), true );
if ( props.getProperty( "status" ).equals(GR_STAT_SUCCESS) ) {
status(su, "Upload successful.");
return true;
} else {
error(su, "Upload error: " + props.getProperty( "status_text" ));
return false;
}
} catch ( GR2Exception gr2e ) {
Log.logException(Log.ERROR, MODULE, gr2e );
error(su, "Error: " + gr2e.getMessage());
} catch (SocketException swe) {
Log.logException(Log.ERROR, MODULE, swe);
error(su, "You may need to set LimitRequestBody 16777216 and memory_limit = 64M " +
"in /etc/php.ini and /etc/httpd/conf.d/php.conf on your Gallery server\n\n" +
swe.toString());
} catch (IOException ioe) {
Log.logException(Log.ERROR, MODULE, ioe);
error(su, "Error: " + ioe.toString());
} catch (ModuleException me) {
Log.logException(Log.ERROR, MODULE, me);
error(su, "Error handling request: " + me.getMessage());
}
return false;
}
}
/**
* An extension of GalleryTask to handle fetching albums.
*/
class AlbumListTask extends GalleryTask {
AlbumListTask( StatusUpdate su ) {
super(su);
}
void runTask() {
pId = su.startProgress(0, 10, "Fetching albums from " + g.toString(), true);
try {
long startTime = System.currentTimeMillis();
if (serverMinorVersion < 2) {
list20();
} else {
list22();
}
Log.log(Log.INFO, MODULE, "execution time for AlbumList: " + (System.currentTimeMillis() - startTime));
} catch ( GR2Exception gr2e ) {
Log.logException(Log.ERROR, MODULE, gr2e );
error(su, "Error: " + gr2e.getMessage());
} catch (IOException ioe) {
Log.logException(Log.ERROR, MODULE, ioe);
error(su, "Error: " + ioe.toString());
} catch (ModuleException me) {
Log.logException(Log.ERROR, MODULE, me);
error(su, "Error: " + me.toString());
}
su.stopProgress(pId, "Fetch complete");
}
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.TRACE, MODULE, "fetchAlbums parameters: " + Arrays.asList(form_data));
// load and validate the response
Properties p = requestResponse( form_data );
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" ) );
// System.err.println( "### albumCount = " + albumCount );
HashMap ref2parKey = new HashMap();
HashMap ref2album = new HashMap();
for ( int i = 1; i < albumCount + 1; i++ ) {
Album a = new Album();
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;
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.setName( p.getProperty( nameKey ) );
a.setTitle( p.getProperty( titleKey ) );
a.setGallery( g );
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 );
}
}
// 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 );
a.setParentAlbum( pa );
}
}
status(su, "Fetched albums");
g.setAlbumList(mAlbumList);
} else {
error(su, "Error: " + p.getProperty( "status_text" ));
}
}
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.TRACE, MODULE, "fetchAlbums parameters: " + Arrays.asList(form_data));
// load and validate the response
Properties p = requestResponse( form_data );
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" ) );
// System.err.println( "### albumCount = " + albumCount );
HashMap name2parentName = new HashMap();
HashMap name2album = new HashMap();
for ( int i = 1; i < albumCount + 1; i++ ) {
Album a = new Album();
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;
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 );
String title = p.getProperty( titleKey );
a.setName( name );
a.setTitle( title );
a.setGallery( g );
mAlbumList.add( a );
// map album names to parent albums
name2album.put( name, a );
// map album refs to parent refs
String parentName = p.getProperty( parentKey );
if ( parentName != null && parentName.length() > 0 && !parentName.equals("0")) {
name2parentName.put( name, parentName );
}
}
// 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) {
child.setParentAlbum(parent);
}
}
// reorder
//Collections.reverse(mAlbumList);
ArrayList orderedAlbums = new ArrayList();
int depth = 0;
while (!mAlbumList.isEmpty()) {
it = mAlbumList.iterator();
while (it.hasNext()) {
Album a = (Album) it.next();
if (a.getAlbumDepth() == depth) {
it.remove();
Album parentAlbum = a.getParentAlbum();
if (parentAlbum == null) {
orderedAlbums.add(a);
} else {
int i = orderedAlbums.indexOf(parentAlbum);
orderedAlbums.add(i + 1, a);
}
}
}
depth++;
}
status(su, "Fetched albums");
g.setAlbumList(orderedAlbums);
} else {
error(su, "Error: " + p.getProperty( "status_text" ));
}
}
}
/**
* 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, "Getting album information from " + g.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.TRACE, MODULE, "album-info parameters: " + Arrays.asList(form_data));
// load and validate the response
Properties p = requestResponse( form_data );
if ( p.getProperty( "status" ).equals(GR_STAT_SUCCESS) ) {
// parse and store the data
int autoResize = Integer.parseInt( p.getProperty( "auto_resize" ) );
a.setServerAutoResize( autoResize );
status(su, "Fetched album properties.");
} else {
error(su, "Error: " + p.getProperty( "status_text" ));
}
} catch ( GR2Exception gr2e ) {
Log.logException(Log.ERROR, MODULE, gr2e );
error(su, "Error: " + gr2e.getMessage());
} catch (IOException ioe) {
Log.logException(Log.ERROR, MODULE, ioe);
error(su, "Error: " + ioe.toString());
} catch (ModuleException me) {
Log.logException(Log.ERROR, MODULE, me);
error(su, "Error: " + me.toString());
}
}
}
/**
* An extension of GalleryTask to handle creating a new album.
*/
class NewAlbumTask extends GalleryTask {
Album parentAlbum;
String albumName;
String albumTitle;
String albumDesc;
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, "Getting album information from " + g.toString());
// 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 (GalleryRemote.getInstance().properties.getBooleanProperty(HTML_ESCAPE_CAPTIONS)) {
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 ),
new NVPair("newAlbumDesc", albumDesc )
};
Log.log(Log.TRACE, MODULE, "new-album parameters: " + Arrays.asList(form_data));
// load and validate the response
Properties p = requestResponse( form_data );
if ( p.getProperty( "status" ).equals(GR_STAT_SUCCESS) ) {
status(su, "Create album successful.");
} else {
error(su, "Error: " + p.getProperty( "status_text" ));
}
} catch ( GR2Exception gr2e ) {
Log.logException(Log.ERROR, MODULE, gr2e );
error(su, "Error: " + gr2e.getMessage());
} catch (IOException ioe) {
Log.logException(Log.ERROR, MODULE, ioe);
error(su, "Error: " + ioe.toString());
} catch (ModuleException me) {
Log.logException(Log.ERROR, MODULE, me);
error(su, "Error: " + me.toString());
}
}
}
boolean isTrue( String s ){
return s.equals( "true" );
}
/* -------------------------------------------------------------------------
* 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 ) {
}
}*/
}