-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSkylineToolsStoreController.java
More file actions
1476 lines (1280 loc) · 61.1 KB
/
SkylineToolsStoreController.java
File metadata and controls
1476 lines (1280 loc) · 61.1 KB
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.skylinetoolsstore;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.labkey.api.action.FormHandlerAction;
import org.labkey.api.action.NavTrailAction;
import org.labkey.api.action.PermissionCheckable;
import org.labkey.api.action.ReturnUrlForm;
import org.labkey.api.action.SimpleErrorView;
import org.labkey.api.action.SimpleViewAction;
import org.labkey.api.action.SpringActionController;
import org.labkey.api.collections.LabKeyCollectors;
import org.labkey.api.data.Container;
import org.labkey.api.data.ContainerManager;
import org.labkey.api.data.NormalContainerType;
import org.labkey.api.files.FileContentService;
import org.labkey.api.module.FolderTypeManager;
import org.labkey.api.module.ModuleLoader;
import org.labkey.api.security.ActionNames;
import org.labkey.api.security.Group;
import org.labkey.api.security.MutableSecurityPolicy;
import org.labkey.api.security.RequiresLogin;
import org.labkey.api.security.RequiresNoPermission;
import org.labkey.api.security.RequiresPermission;
import org.labkey.api.security.RequiresSiteAdmin;
import org.labkey.api.security.RoleAssignment;
import org.labkey.api.security.SecurityPolicy;
import org.labkey.api.security.SecurityPolicyManager;
import org.labkey.api.security.User;
import org.labkey.api.security.UserManager;
import org.labkey.api.security.ValidEmail;
import org.labkey.api.security.permissions.DeletePermission;
import org.labkey.api.security.permissions.InsertPermission;
import org.labkey.api.security.permissions.ReadPermission;
import org.labkey.api.security.permissions.UpdatePermission;
import org.labkey.api.security.roles.EditorRole;
import org.labkey.api.security.roles.FolderAdminRole;
import org.labkey.api.security.roles.ReaderRole;
import org.labkey.api.security.roles.Role;
import org.labkey.api.security.roles.RoleManager;
import org.labkey.api.settings.AppProps;
import org.labkey.api.util.FileUtil;
import org.labkey.api.util.JavaScriptFragment;
import org.labkey.api.util.NetworkDrive;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.Pair;
import org.labkey.api.util.SafeToRender;
import org.labkey.api.util.URLHelper;
import org.labkey.api.view.ActionURL;
import org.labkey.api.view.HtmlView;
import org.labkey.api.view.HttpView;
import org.labkey.api.view.JspView;
import org.labkey.api.view.NavTree;
import org.labkey.api.view.NotFoundException;
import org.labkey.api.view.RedirectException;
import org.labkey.api.view.UnauthorizedException;
import org.labkey.api.webdav.WebdavResource;
import org.labkey.api.webdav.WebdavService;
import org.labkey.skylinetoolsstore.model.SkylineTool;
import org.labkey.skylinetoolsstore.view.SkylineToolDetails;
import org.labkey.skylinetoolsstore.view.SkylineToolStoreUrls;
import org.labkey.skylinetoolsstore.view.SkylineToolsStoreWebPart;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class SkylineToolsStoreController extends SpringActionController
{
private static final DefaultActionResolver _actionResolver = new DefaultActionResolver(SkylineToolsStoreController.class);
private static final String[] VALID_ICON_EXTENSIONS = new String[] { "png", "jpg", "jpeg", "gif" };
public SkylineToolsStoreController()
{
setActionResolver(_actionResolver);
}
@RequiresPermission(ReadPermission.class)
public static class BeginAction extends SimpleViewAction<Object>
{
@Override
public ModelAndView getView(Object o, BindException errors) throws Exception
{
ModuleLoader moduleLoader = ModuleLoader.getInstance();
if(!getContainer().getActiveModules().contains(moduleLoader.getModule(SkylineToolsStoreModule.class)))
{
// If the toolstore module is not enabled in the container look for a container
// that has tools.
SkylineTool[] tools = SkylineToolsStoreManager.get().getToolsLatest();
if (tools != null && tools.length > 0)
{
Container toolsHomeContainer = tools[0].getContainerParent();
// NOTE: This returns the first container that contains tools. We have only one such container
// on the skyline website.
// TODO: Need to look into why the tool store module is enabled in the individual tool sub-folders.
if (!getContainer().equals(toolsHomeContainer))
{
ActionURL redirectUrl = getViewContext().getActionURL();
redirectUrl.setContainer(toolsHomeContainer);
throw new RedirectException(redirectUrl);
}
}
}
return new SkylineToolsStoreWebPart();
}
@Override
public void addNavTrail(NavTree root)
{
root.addChild(getToolStoreNav(getContainer()));
}
}
public static NavTree getToolStoreNav(Container container)
{
return new NavTree("Skyline Tool Store", new ActionURL(BeginAction.class, container));
}
protected SkylineTool getToolFromZip(MultipartFile zip) throws IOException
{
SkylineTool tool = null;
byte[] toolIcon = null;
try (ZipInputStream zipStream = new ZipInputStream(zip.getInputStream()))
{
ZipEntry zipEntry;
while ((zipEntry = zipStream.getNextEntry()) != null &&
(tool == null || toolIcon == null))
{
String entryLower = zipEntry.getName().toLowerCase();
if (entryLower.startsWith("tool-inf/") && !entryLower.startsWith("tool-inf/docs/"))
{
String lowerBaseName = new File(zipEntry.getName()).getName().toLowerCase();
if (lowerBaseName.equals("info.properties"))
{
byte[] bytes = unzip(zipStream);
// zipEntry.closeEntry() not necessary, getNextEntry() does it automatically
tool = new SkylineTool(new BufferedReader(new StringReader(new String(bytes, "UTF-8"))));
}
else if (Arrays.asList(VALID_ICON_EXTENSIONS).contains(FileUtil.getExtension(lowerBaseName)))
{
toolIcon = unzip(zipStream);
}
}
}
}
catch (Exception e)
{
throw e;
}
if (tool != null)
{
tool.setZipName(FileUtil.makeLegalName(zip.getOriginalFilename()));
if (toolIcon != null)
tool.setIcon(toolIcon);
}
return tool;
}
protected byte[] unzip(ZipInputStream stream)
{
final int BUFFER_SIZE = 2048;
byte[] bytes = new byte[BUFFER_SIZE];
int bytesRead;
try (ByteArrayOutputStream unzipBytes = new ByteArrayOutputStream())
{
while ((bytesRead = stream.read(bytes, 0, BUFFER_SIZE)) != -1)
unzipBytes.write(bytes, 0, bytesRead);
return unzipBytes.toByteArray();
}
catch (Exception e)
{
return null;
}
}
protected static boolean extractDocsFromZip(Path zipFile, Path containerDir) throws IOException
{
Path docsDir = containerDir.resolve("docs");
boolean extracted = false;
try (ZipFile zf = new ZipFile(zipFile.toFile()))
{
Enumeration<? extends ZipEntry> entries = zf.entries();
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
String name = entry.getName();
if (!name.toLowerCase().startsWith("tool-inf/docs/") || entry.isDirectory())
continue;
// Strip "tool-inf/docs/" prefix to get relative path within docs dir
String relativePath = name.substring("tool-inf/docs/".length());
if (relativePath.isEmpty())
continue;
Path destPath = docsDir.resolve(relativePath).normalize();
// Zip-slip protection
if (!destPath.startsWith(docsDir.normalize()))
throw new IOException("Zip entry outside target directory: " + name);
Files.createDirectories(destPath.getParent());
try (InputStream in = zf.getInputStream(entry))
{
Files.copy(in, destPath, StandardCopyOption.REPLACE_EXISTING);
}
extracted = true;
}
}
return extracted;
}
public static File makeFile(Container c, String filename)
{
return getLocalPath(c).resolve(FileUtil.makeLegalName(filename)).toFile();
}
public static Path getLocalPath(Container c)
{
return FileContentService.get().getFileRootPath(c, FileContentService.ContentType.files);
}
protected Container makeContainer(Container parent, String folderName, List<User> users, Role role) throws IOException
{
StringBuilder sb = new StringBuilder();
if (!Container.isLegalName(folderName, false, sb))
return null;
if (parent.hasChild(folderName))
return null;
Container c = ContainerManager.createContainer(parent, folderName, null, null, NormalContainerType.NAME, getUser());
c.setFolderType(FolderTypeManager.get().getFolderType("Collaboration"), getUser());
Path fileRoot = FileContentService.get().getFileRootPath(c, FileContentService.ContentType.files);
if(!Files.exists(fileRoot))
{
Files.createDirectories(fileRoot);
}
// Make folder readable by all site users and guests, so that they can access the zip file/icon
MutableSecurityPolicy policy = new MutableSecurityPolicy(c);
User guest = new User();
guest.setUserId(Group.groupGuests);
User user = new User();
user.setUserId(Group.groupUsers);
policy.addRoleAssignment(guest, RoleManager.getRole(ReaderRole.class));
policy.addRoleAssignment(user, RoleManager.getRole(ReaderRole.class));
if (users != null && !users.isEmpty() && role != null)
for (User u : users)
policy.addRoleAssignment(u, role);
SecurityPolicyManager.savePolicy(policy, User.getAdminServiceUser());
return c;
}
protected MutableSecurityPolicy copyPolicy(Container c, SecurityPolicy from)
{
MutableSecurityPolicy policy = new MutableSecurityPolicy(c);
for (RoleAssignment assignment : from.getAssignments())
{
User u = new User();
u.setUserId(assignment.getUserId());
policy.addRoleAssignment(u, assignment.getRole());
}
return policy;
}
protected MutableSecurityPolicy filterPolicy(SecurityPolicy original, List<User> users, Role[] roles)
{
// For each role assignment where the role is in roles, only keep if the user is in users
MutableSecurityPolicy policy = new MutableSecurityPolicy(ContainerManager.getForId(original.getContainerId()));
for (RoleAssignment assignment : original.getAssignments())
{
if (Arrays.asList(roles).contains(assignment.getRole()))
{
boolean skip = true;
for (User u : users)
{
if (u.getUserId() == assignment.getUserId())
{
skip = false;
break;
}
}
if (skip)
continue;
}
User u = new User();
u.setUserId(assignment.getUserId());
policy.addRoleAssignment(u, assignment.getRole());
}
return policy;
}
protected void copyContainerPermissions(Container from, Container to)
{
if (from == null || to == null)
return;
SecurityPolicyManager.savePolicy(copyPolicy(to, from.getPolicy()), User.getAdminServiceUser());
}
public static SkylineTool[] sortToolsByCreateDate(SkylineTool[] tools)
{
List<SkylineTool> toolList = Arrays.asList(tools);
toolList.sort((lhs, rhs) -> rhs.getCreated().compareTo(lhs.getCreated()));
return toolList.toArray(new SkylineTool[0]);
}
public static SafeToRender getUsersForAutocomplete()
{
JSONArray jsonArray = UserManager.getActiveUsers().stream()
.map(User::getEmail)
.collect(LabKeyCollectors.toJSONArray());
return JavaScriptFragment.unsafe(jsonArray.toString());
}
protected static Pair<ArrayList<User>, ArrayList<String>> parseToolOwnerString(String toolOwners) throws ValidEmail.InvalidEmailException
{
ArrayList<User> toolOwnersUsers = new ArrayList<>();
ArrayList<String> toolOwnersInvalid = new ArrayList<>();
if (toolOwners != null)
{
for (String toolOwner : toolOwners.split(","))
{
toolOwner = toolOwner.trim();
if (!toolOwner.isEmpty())
{
User u = UserManager.getUser(new ValidEmail(toolOwner));
if (u == null)
toolOwnersInvalid.add(toolOwner);
else
toolOwnersUsers.add(u);
}
}
}
return new Pair<>(toolOwnersUsers, toolOwnersInvalid);
}
public static ArrayList<String> getToolOwners(SkylineTool tool)
{
return getToolRelevantUsers(tool, new Role[]{RoleManager.getRole(EditorRole.class), RoleManager.getRole(FolderAdminRole.class)});
}
public static ArrayList<String> getToolRelevantUsers(SkylineTool tool, Role[] roles)
{
HashSet<String> users = new HashSet<>();
for (RoleAssignment assignment : tool.lookupContainer().getPolicy().getAssignments())
if (Arrays.asList(roles).contains(assignment.getRole()))
{
User user = UserManager.getUser(assignment.getUserId());
if(user != null && user.getEmail() != null)
{
users.add(user.getEmail());
}
}
return new ArrayList<>(users);
}
public static HashMap<String, String> getSupplementaryFiles(SkylineTool tool) throws IOException
{
// Store supporting files in map <url, icon url>
final String[] knownExtensions = {"pdf", "zip"};
final String imgDir = AppProps.getInstance().getContextPath() + "/skylinetoolsstore/img/";
HashMap<String, String> suppFiles = new HashMap<>();
for (String suppFile : getSupplementaryFileBasenames(tool))
{
final String suppFileExtension = FileUtil.getExtension(suppFile).toLowerCase();
final String suppFileIcon = (Arrays.asList(knownExtensions).contains(suppFileExtension)) ?
imgDir + suppFileExtension + "-icon.png" : imgDir + "unknown-icon.jpg";
suppFiles.put(tool.getFolderUrl() + suppFile, suppFileIcon);
}
return suppFiles;
}
public static HashSet<String> getSupplementaryFileBasenames(SkylineTool tool) throws IOException
{
HashSet<String> suppFiles = new HashSet<>();
Path localToolDir = getLocalPath(tool.lookupContainer());
try (var stream = Files.list(localToolDir))
{
stream.map(p -> p.getFileName().toString())
.filter(name -> !name.startsWith(".") && !name.equals(tool.getZipName()) && !name.equals("icon.png") && !name.equals("docs"))
.forEach(suppFiles::add);
}
return suppFiles;
}
@RequiresNoPermission
public class InsertAction extends AbstractController implements NavTrailAction, PermissionCheckable
{
private static final String NO_FILE = "You did not submit a file.";
private static final String INVALID_TOOL_FILE = "The file was not a valid Skyline Tool zip file.";
private static final String MISSING_REQUIRED_PROPERTIES = "The tool was missing the following properties: ";
private static final String TOOL_DOES_NOT_EXIST = "The Skyline Tool being updated does not exist.";
private static final String TOOL_ALREADY_EXISTS = "The Skyline Tool you are trying to add already exists.";
private static final String WRONG_TOOL = "The Skyline Tool zip file did not contain the Skyline Tool being updated.";
private static final String SAME_VERSION = "The Skyline Tool zip file contained the same version of the tool being updated.";
private static final String OLD_VERSION = "The Skyline Tool zip file contained an older version of the tool.";
private static final String NO_UPDATE_PERMISSIONS = "You do not have permission to update that Skyline Tool.";
private static final String NO_INSERT_PERMISSIONS = "You do not have permission to add a new Skyline Tool.";
private static final String UNKNOWN_USERS = "The following users are unknown: ";
public InsertAction()
{
}
@Override
public ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception
{
final String sender = httpServletRequest.getParameter("sender");
final String updateTargetString = StringUtils.trimToNull(httpServletRequest.getParameter("updatetarget"));
final int updateTarget = (updateTargetString != null) ? Integer.parseInt(updateTargetString) : -1;
final String toolOwners = httpServletRequest.getParameter("toolOwners");
if(updateTarget == -1 &&
!getContainer().getActiveModules().contains(ModuleLoader.getInstance().getModule(SkylineToolsStoreModule.class)))
{
// Make sure that the tool store module is enabled in the folder where the user is trying
// to insert the new tool.
return HtmlView.of("The Skyline Tool Store is not available in this folder.");
}
if (httpServletRequest.getMethod().equalsIgnoreCase("post") &&
httpServletRequest instanceof MultipartHttpServletRequest)
{
Map<?, ?> fileMap = ((MultipartHttpServletRequest)httpServletRequest).getFileMap();
MultipartFile zip = (MultipartFile)(fileMap.get("toolZip"));
Pair<ArrayList<User>, ArrayList<String>> parsedOwners = parseToolOwnerString(toolOwners);
ArrayList<User> toolOwnersUsers = parsedOwners.first;
ArrayList<String> toolOwnersInvalid = parsedOwners.second;
if (!toolOwnersInvalid.isEmpty())
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
UNKNOWN_USERS + StringUtils.join(toolOwnersInvalid, ", "));
}
else if (!zip.getOriginalFilename().isEmpty())
{
SkylineTool tool = getToolFromZip(zip);
String folderName = (tool != null && tool.getName() != null) ? "_tool_" +
FileUtil.getBaseName(FileUtil.makeLegalName(tool.getName())) + "_" +
FileUtil.makeLegalName(tool.getVersion()) : "";
Container existingVersionContainer = null;
boolean addTool = false;
HashSet<String> copyFiles = null; // Paths of files to copy to the new tool's container
if (tool == null)
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
INVALID_TOOL_FILE);
}
else if (!tool.getMissingValues().isEmpty())
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
MISSING_REQUIRED_PROPERTIES + StringUtils.join(tool.getMissingValues(), ", "));
}
else if (updateTarget >= 0)
{
// Updating tool with rowId == updateTarget
SkylineTool existingVersion = SkylineToolsStoreManager.get().getTool(updateTarget);
if (existingVersion == null)
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
TOOL_DOES_NOT_EXIST);
}
// If the container in the request URL does not match the parent of the container associated
// with the tool, redirect to a URL with the correct container path.
if(!getContainer().equals(existingVersion.getContainerParent()))
{
ActionURL url = getURL();
// Add these parameters so that they are available after the redirect.
url.addParameter("sender", sender);
url.addParameter("updatetarget", updateTargetString);
url.addParameter("toolowners", toolOwners);
redirectToToolStoreContainer(existingVersion, url);
}
if (!tool.getIdentifier().equalsIgnoreCase(existingVersion.getIdentifier()))
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
WRONG_TOOL);
}
else if (tool.getVersion().equalsIgnoreCase(existingVersion.getVersion()))
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
SAME_VERSION);
}
else if (!existingVersion.lookupContainer().hasPermission(getUser(), UpdatePermission.class))
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
NO_UPDATE_PERMISSIONS);
}
else
{
addTool = true;
for (SkylineTool checkTool : SkylineToolsStoreManager.get().getToolsByIdentifier(tool.getIdentifier()))
{
if (checkTool.getVersion().equalsIgnoreCase(tool.getVersion()))
{
addTool = false;
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
OLD_VERSION);
break;
}
}
if (addTool)
{
existingVersion.setLatest(false);
existingVersionContainer = existingVersion.lookupContainer();
SkylineToolsStoreManager.get().updateTool(existingVersionContainer, getUser(), existingVersion);
copyFiles = getSupplementaryFileBasenames(existingVersion);
}
}
}
else if (!getContainer().hasPermission(getUser(), InsertPermission.class))
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
NO_INSERT_PERMISSIONS);
}
else
{
// Adding a new tool
addTool = true;
for (SkylineTool checkTool : SkylineToolsStoreManager.get().getToolsLatest())
{
if (tool.getIdentifier().equalsIgnoreCase(checkTool.getIdentifier()))
{
addTool = false;
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
TOOL_ALREADY_EXISTS);
break;
}
}
for (Container checkContainer : getContainer().getChildren())
{
if (checkContainer.getName().equalsIgnoreCase(folderName))
{
addTool = false;
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
TOOL_ALREADY_EXISTS);
break;
}
}
}
if (addTool)
{
Container c = makeContainer(getContainer(), folderName, toolOwnersUsers, RoleManager.getRole(EditorRole.class));
copyContainerPermissions(existingVersionContainer, c);
File storedZip = makeFile(c, zip.getOriginalFilename());
zip.transferTo(storedZip);
tool.writeIconToFile(makeFile(c, "icon.png"), "png");
// Extract docs from tool-inf/docs/ in the ZIP; carry forward from previous version if absent
boolean hasDocs = extractDocsFromZip(storedZip.toPath(), getLocalPath(c));
if (!hasDocs && existingVersionContainer != null)
{
Path oldDocs = getLocalPath(existingVersionContainer).resolve("docs");
if (Files.isDirectory(oldDocs))
FileUtil.copyDirectory(oldDocs, getLocalPath(c).resolve("docs"));
}
if (copyFiles != null && existingVersionContainer != null)
for (String copyFile : copyFiles)
FileUtils.copyFile(makeFile(existingVersionContainer, copyFile), makeFile(c, copyFile), true);
tool.setLatest(true);
SkylineToolsStoreManager.get().insertTool(c, getUser(), tool);
return HttpView.redirect(SkylineToolStoreUrls.getToolDetailsUrl(tool));
}
}
else
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
NO_FILE);
}
}
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "sender", sender);
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "updatetarget", updateTargetString);
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "toolowners", toolOwners);
return new JspView<>("/org/labkey/skylinetoolsstore/view/SkylineToolsStoreUpload.jsp", null);
}
@Override
public void addNavTrail(NavTree root)
{
root.addChild(getToolStoreNav(getContainer()));
root.addChild("Upload Tool", getURL());
}
public ActionURL getURL()
{
return new ActionURL(InsertAction.class, getContainer());
}
@Override
public void checkPermissions() throws UnauthorizedException
{
if(getUser().isGuest())
throw new UnauthorizedException();
}
}
private void redirectToToolStoreContainer(SkylineTool tool, ActionURL originalUrl)
{
// If the container in the request URL does not match the parent of the container associated
// with the tool, redirect to the correct URL
Container toolContainerParent = tool.getContainerParent();
if(toolContainerParent != null)
{
if(!toolContainerParent.equals(getContainer()))
{
ActionURL url = originalUrl.clone();
url.setContainer(toolContainerParent);
throw new RedirectException(url);
}
}
}
@RequiresNoPermission
public class InsertSupplementAction extends AbstractController implements PermissionCheckable
{
private final Class REQ_PERMS = InsertPermission.class;
private static final String NO_FILE = "You did not submit a file.";
private static final String SUPPLEMENT_ALREADY_EXISTS = "The supplementary file already exists.";
private static final String INVALID_TOOL_ID = "Invalid tool Id in request: ";
public InsertSupplementAction()
{
}
@Override
public ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception
{
final String suppTargetString = httpServletRequest.getParameter("supptarget");
int suppTarget = NumberUtils.toInt(suppTargetString, -1);
if(suppTarget == -1)
{
httpServletRequest.setAttribute(BindingResult.MODEL_KEY_PREFIX + "form", INVALID_TOOL_ID + " " + suppTargetString);
httpServletRequest.setAttribute(BindingResult.MODEL_KEY_PREFIX + "supptarget", suppTargetString);
return new JspView<>("/org/labkey/skylinetoolsstore/view/SkylineToolSupplementUpload.jsp", null);
}
SkylineTool tool = SkylineToolsStoreManager.get().getTool(suppTarget);
final Container c = tool.lookupContainer();
if (!c.hasPermission(getUser(), REQ_PERMS))
throw new Exception();
Map<?, ?> fileMap = ((MultipartHttpServletRequest)httpServletRequest).getFileMap();
MultipartFile suppFile = (MultipartFile)(fileMap.get("suppFile"));
if (!suppFile.getOriginalFilename().isEmpty())
{
File targetFile = makeFile(c, FileUtil.makeLegalName(suppFile.getOriginalFilename()));
if (targetFile.exists())
{
// Can't upload supplementary file if the file already exists
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
SUPPLEMENT_ALREADY_EXISTS);
}
else
{
suppFile.transferTo(targetFile);
return HttpView.redirect(SkylineToolStoreUrls.getToolDetailsUrl(tool));
}
}
else
{
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "form",
NO_FILE);
}
getViewContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "supptarget", suppTargetString);
return new JspView<>("/org/labkey/skylinetoolsstore/view/SkylineToolSupplementUpload.jsp", null);
}
@Override
public void checkPermissions() throws UnauthorizedException
{
}
}
@RequiresNoPermission
public class DeleteSupplementAction extends AbstractController implements PermissionCheckable
{
private final Class REQ_PERMS = DeletePermission.class;
public DeleteSupplementAction()
{
}
@Override
public ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception
{
final int suppTarget = Integer.parseInt(httpServletRequest.getParameter("supptarget"));
final String suppFile = httpServletRequest.getParameter("suppFile");
final SkylineTool tool = SkylineToolsStoreManager.get().getTool(suppTarget);
if (tool == null)
throw new NotFoundException("Could not find tool with Id " + suppTarget);
final Container c = tool.lookupContainer();
if (!c.hasPermission(getUser(), REQ_PERMS))
throw new Exception();
File targetDel = makeFile(c, suppFile);
if (targetDel.isFile() &&
!targetDel.getName().equalsIgnoreCase("icon.png") &&
!targetDel.getName().equalsIgnoreCase(tool.getZipName()))
targetDel.delete();
else
throw new Exception();
return HttpView.redirect(SkylineToolStoreUrls.getToolDetailsUrl(tool));
}
@Override
public void checkPermissions() throws UnauthorizedException
{
}
}
@RequiresLogin
public static class DeleteAction extends FormHandlerAction<IdForm>
{
@Override
public URLHelper getSuccessURL(IdForm idForm)
{
return SkylineToolStoreUrls.getToolStoreHomeUrl(getContainer(), getUser());
}
@Override
public boolean handlePost(IdForm idForm, BindException errors) throws Exception
{
final SkylineTool tool = SkylineToolsStoreManager.get().getTool(idForm.getId());
if(tool == null)
{
errors.reject(ERROR_MSG, "Tool with id " + idForm.getId() + " does not exist.");
return false;
}
// Get the tool store container, in case we need it, before the tool and its container is deleted.
Container toolStoreContainer = tool.getContainerParent();
if(toolStoreContainer == null)
{
errors.reject(ERROR_MSG, "Failed to look up tool's parent container: " + tool.getName());
return false;
}
if(!getContainer().equals(toolStoreContainer))
{
ActionURL url = getViewContext().getActionURL().clone();
url.setContainer(toolStoreContainer);
throw new RedirectException(url);
}
Container toolContainer = tool.lookupContainer();
if(toolContainer == null)
{
errors.reject(ERROR_MSG, "Failed to look up tool's container: " + tool.getName());
return false;
}
if(!toolContainer.hasPermission(getUser(), DeletePermission.class))
{
errors.reject(ERROR_MSG, "User does not have permission to delete the tool." + tool.getName());
return false;
}
// TODO: Should be in a transaction
for (SkylineTool toDelete : SkylineToolsStoreManager.get().getToolsByIdentifier(tool.getIdentifier()))
{
ContainerManager.delete(toDelete.lookupContainer(), getUser());
}
return true;
}
@Override
public void validateCommand(IdForm idForm, Errors errors)
{
}
}
public static class IdForm extends ReturnUrlForm
{
private String _name;
private int _id;
public IdForm()
{
}
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
public int getId()
{
return _id;
}
public void setId(int id)
{
_id = id;
}
}
@RequiresLogin
public class DeleteLatestAction extends AbstractController implements PermissionCheckable
{
private final Class REQ_PERMS = DeletePermission.class;
@Override
public ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception
{
int id;
try {
id = Integer.parseInt(httpServletRequest.getParameter("id"));
}
catch(Exception e) {
return null;
}
final SkylineTool tool = SkylineToolsStoreManager.get().getTool(id);
if (!tool.lookupContainer().hasPermission(getUser(), REQ_PERMS))
throw new UnauthorizedException("User does not have permission to delete the tool.");
final String sender = httpServletRequest.getParameter("sender");
ActionURL senderUrl = sender != null ? new ActionURL(sender) : null;
// Get the tool store container, in case we need it, before we delete the tool and its container.
Container toolStoreContainer = tool != null ? tool.getContainerParent() : getContainer();
if (tool != null)
{
final String identifier = tool.getIdentifier();
SkylineTool[] tools = sortToolsByCreateDate(SkylineToolsStoreManager.get().getToolsByIdentifier(identifier));
// This action cannot be used if there is only one version
if (tools.length == 1)
throw new Exception();
ContainerManager.delete(tools[0].lookupContainer(), getUser());
if (tools.length > 1)
{
if (senderUrl != null)
{
if (!tools[0].getName().equals(tools[1].getName()) && senderUrl.getParameter("name") != null)
senderUrl.replaceParameter("name", tools[1].getName());
if (senderUrl.getParameter("version") != null && senderUrl.getParameter("version").equals(tools[0].getVersion()))
senderUrl.deleteParameter("version");
}
SkylineTool newLatest = tools[1];
newLatest.setLatest(true);
SkylineToolsStoreManager.get().updateTool(newLatest.lookupContainer(), getUser(), newLatest);
}
}
return HttpView.redirect((senderUrl != null) ? senderUrl :
SkylineToolStoreUrls.getToolStoreHomeUrl(toolStoreContainer, getUser()));
}
@Override
public void checkPermissions() throws UnauthorizedException
{
}
}
@RequiresNoPermission
public class DownloadToolAction extends AbstractController implements PermissionCheckable
{
public static final String DOWNLOADED_COOKIE_PREFIX = "downloadtool";
@Override
public ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception
{
final int id = NumberUtils.toInt(httpServletRequest.getParameter("id"), -1);
final String toolName = httpServletRequest.getParameter("name");
final String toolLsid = httpServletRequest.getParameter("lsid");
SkylineTool tool = null;
if (id > 0 && (tool = SkylineToolsStoreManager.get().getTool(id)) == null)
throw new NotFoundException("Could not find tool with id " + id);
else if (toolName != null &&
(tool = SkylineToolsStoreManager.get().getLatestTool(URLDecoder.decode(toolName.trim(), "UTF-8"))) == null)
throw new NotFoundException("Could not find tool with name " + toolName);
else if (toolLsid != null &&
(tool = SkylineToolsStoreManager.get().getToolLatestByIdentifier(toolLsid.trim())) == null)
throw new NotFoundException("Could not find tool with LSID " + toolLsid);
if (tool == null)
throw new NotFoundException("Could not do tool lookup");
if (recordDownload(httpServletRequest, tool.getRowId()))
{
// Cookie expires after 1 day
final int expires = 24 * 60 * 60;
// Download counter is an incidental write on a GET action — use ignoreSqlUpdates()
// to avoid the dev-mode mutating SQL assertion (like auditing writes)
try (var ignored = SpringActionController.ignoreSqlUpdates())
{
SkylineToolsStoreManager.get().recordToolDownload(tool);
}
DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, expires);
httpServletResponse.setHeader("Set-Cookie",
DOWNLOADED_COOKIE_PREFIX + tool.getRowId() + "=1; " +