Fix forward to dashboard after login.
[gpl/argeo-suite.git] / core / org.argeo.suite.ui / src / org / argeo / suite / ui / SuiteApp.java
1 package org.argeo.suite.ui;
2
3 import static org.argeo.cms.ui.CmsView.CMS_VIEW_UID_PROPERTY;
4
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.List;
9 import java.util.Locale;
10 import java.util.Map;
11 import java.util.Set;
12 import java.util.TreeMap;
13 import java.util.TreeSet;
14
15 import javax.jcr.Node;
16 import javax.jcr.RepositoryException;
17 import javax.jcr.Session;
18 import javax.jcr.nodetype.NodeType;
19 import javax.naming.InvalidNameException;
20 import javax.naming.ldap.LdapName;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.argeo.api.NodeUtils;
25 import org.argeo.cms.CmsUserManager;
26 import org.argeo.cms.LocaleUtils;
27 import org.argeo.cms.Localized;
28 import org.argeo.cms.auth.CmsSession;
29 import org.argeo.cms.ui.AbstractCmsApp;
30 import org.argeo.cms.ui.CmsTheme;
31 import org.argeo.cms.ui.CmsUiProvider;
32 import org.argeo.cms.ui.CmsView;
33 import org.argeo.cms.ui.dialogs.CmsFeedback;
34 import org.argeo.cms.ui.util.CmsUiUtils;
35 import org.argeo.eclipse.ui.specific.UiContext;
36 import org.argeo.entity.EntityConstants;
37 import org.argeo.entity.EntityNames;
38 import org.argeo.entity.EntityType;
39 import org.argeo.jcr.Jcr;
40 import org.argeo.suite.RankedObject;
41 import org.argeo.suite.SuiteUtils;
42 import org.argeo.util.LangUtils;
43 import org.eclipse.swt.SWT;
44 import org.eclipse.swt.widgets.Composite;
45 import org.osgi.framework.Constants;
46 import org.osgi.service.event.Event;
47 import org.osgi.service.event.EventHandler;
48 import org.osgi.service.useradmin.User;
49
50 /** The Argeo Suite App. */
51 public class SuiteApp extends AbstractCmsApp implements EventHandler {
52         private final static Log log = LogFactory.getLog(SuiteApp.class);
53
54         public final static String PUBLIC_BASE_PATH_PROPERTY = "publicBasePath";
55         public final static String DEFAULT_UI_NAME_PROPERTY = "defaultUiName";
56         public final static String DEFAULT_THEME_ID_PROPERTY = "defaultThemeId";
57         private final static String LOGIN = "login";
58
59         private String publicBasePath = null;
60
61         private String pidPrefix;
62         private String headerPid;
63         private String leadPanePid;
64         private String loginScreenPid;
65
66         private String defaultLayerPid = "argeo.suite.ui.dashboardLayer";
67
68         private String defaultUiName = "app";
69         private String defaultThemeId = "org.argeo.suite.theme.default";
70
71         private Map<String, RankedObject<CmsUiProvider>> uiProvidersByPid = Collections.synchronizedMap(new HashMap<>());
72         private Map<String, RankedObject<CmsUiProvider>> uiProvidersByType = Collections.synchronizedMap(new HashMap<>());
73         private Map<String, RankedObject<SuiteLayer>> layersByPid = Collections.synchronizedSortedMap(new TreeMap<>());
74         private Map<String, RankedObject<SuiteLayer>> layersByType = Collections.synchronizedSortedMap(new TreeMap<>());
75
76         private CmsUserManager cmsUserManager;
77
78         // TODO make more optimal or via CmsSession/CmsView
79         private Map<String, SuiteUi> managedUis = new HashMap<>();
80
81         public void init(Map<String, Object> properties) {
82                 if (log.isDebugEnabled())
83                         log.info("Argeo Suite App started");
84
85                 if (properties.containsKey(DEFAULT_UI_NAME_PROPERTY))
86                         defaultUiName = LangUtils.get(properties, DEFAULT_UI_NAME_PROPERTY);
87                 if (properties.containsKey(DEFAULT_THEME_ID_PROPERTY))
88                         defaultThemeId = LangUtils.get(properties, DEFAULT_THEME_ID_PROPERTY);
89                 publicBasePath = LangUtils.get(properties, PUBLIC_BASE_PATH_PROPERTY);
90
91                 if (properties.containsKey(Constants.SERVICE_PID)) {
92                         String servicePid = properties.get(Constants.SERVICE_PID).toString();
93                         if (servicePid.endsWith(".app")) {
94                                 pidPrefix = servicePid.substring(0, servicePid.length() - "app".length());
95                         }
96                 }
97
98                 if (pidPrefix == null)
99                         throw new IllegalArgumentException("PID prefix must be set.");
100
101                 headerPid = pidPrefix + "header";
102                 leadPanePid = pidPrefix + "leadPane";
103                 loginScreenPid = pidPrefix + "loginScreen";
104         }
105
106         public void destroy(Map<String, Object> properties) {
107                 for (SuiteUi ui : managedUis.values())
108                         if (!ui.isDisposed())
109                                 ui.dispose();
110                 if (log.isDebugEnabled())
111                         log.info("Argeo Suite App stopped");
112
113         }
114
115         @Override
116         public Set<String> getUiNames() {
117                 HashSet<String> uiNames = new HashSet<>();
118                 uiNames.add(defaultUiName);
119                 return uiNames;
120         }
121
122         @Override
123         public Composite initUi(Composite parent) {
124                 String uiName = parent.getData(UI_NAME_PROPERTY) != null ? parent.getData(UI_NAME_PROPERTY).toString() : null;
125                 CmsView cmsView = CmsView.getCmsView(parent);
126                 if (cmsView == null)
127                         throw new IllegalStateException("No CMS view is registered.");
128                 CmsTheme theme = getTheme(uiName);
129                 if (theme != null)
130                         CmsTheme.registerCmsTheme(parent.getShell(), theme);
131                 SuiteUi argeoSuiteUi = new SuiteUi(parent, SWT.INHERIT_DEFAULT);
132                 String uid = cmsView.getUid();
133                 managedUis.put(uid, argeoSuiteUi);
134                 argeoSuiteUi.addDisposeListener((e) -> {
135                         managedUis.remove(uid);
136                         if (log.isDebugEnabled())
137                                 log.debug("Suite UI " + uid + " has been disposed.");
138                 });
139                 return argeoSuiteUi;
140         }
141
142         @Override
143         public String getThemeId(String uiName) {
144                 return defaultThemeId;
145         }
146
147         @Override
148         public void refreshUi(Composite parent, String state) {
149                 try {
150                         Node context = null;
151                         SuiteUi ui = (SuiteUi) parent;
152                         CmsView cmsView = CmsView.getCmsView(parent);
153                         CmsUiProvider headerUiProvider = findUiProvider(headerPid);
154                         Localized appTitle = null;
155                         if (headerUiProvider instanceof DefaultHeader) {
156                                 appTitle = ((DefaultHeader) headerUiProvider).getTitle();
157                         }
158                         ui.setTitle(appTitle);
159
160                         if (cmsView.isAnonymous() && publicBasePath == null) {// internal app, must login
161                                 ui.logout();
162                                 refreshPart(headerUiProvider, ui.getHeader(), context);
163                                 ui.refreshBelowHeader(false);
164                                 refreshPart(findUiProvider(loginScreenPid), ui.getBelowHeader(), context);
165                                 ui.layout(true, true);
166                                 setState(ui, LOGIN);
167                         } else {
168                                 if (LOGIN.equals(state))
169                                         state = null;
170                                 CmsSession cmsSession = cmsView.getCmsSession();
171                                 if (ui.getUserDir() == null) {
172                                         if (cmsView.isAnonymous()) {
173                                                 assert publicBasePath != null;
174                                                 ui.initSessions(getRepository(), publicBasePath);
175                                         } else {
176                                                 Session adminSession = null;
177                                                 try {
178                                                         adminSession = NodeUtils.openDataAdminSession(getRepository(), null);
179                                                         Node userDir = SuiteUtils.getOrCreateCmsSessionNode(adminSession, cmsSession);
180                                                         ui.initSessions(getRepository(), userDir.getPath());
181                                                 } finally {
182                                                         Jcr.logout(adminSession);
183                                                 }
184                                         }
185                                 }
186                                 initLocale(cmsSession);
187                                 context = stateToNode(ui, state);
188                                 if (context == null)
189                                         context = ui.getUserDir();
190
191                                 refreshPart(headerUiProvider, ui.getHeader(), context);
192                                 ui.refreshBelowHeader(true);
193                                 for (String key : layersByPid.keySet()) {
194                                         SuiteLayer layer = layersByPid.get(key).get();
195                                         ui.addLayer(key, layer);
196                                 }
197                                 refreshPart(findUiProvider(leadPanePid), ui.getLeadPane(), context);
198                                 ui.layout(true, true);
199                                 setState(parent, state != null ? state : defaultLayerPid);
200                         }
201                 } catch (Exception e) {
202                         CmsFeedback.show("Unexpected exception", e);
203                 }
204         }
205
206         private void initLocale(CmsSession cmsSession) {
207                 if (cmsSession == null)
208                         return;
209                 Locale locale = cmsSession.getLocale();
210                 UiContext.setLocale(locale);
211                 LocaleUtils.setThreadLocale(locale);
212
213         }
214
215         private void refreshPart(CmsUiProvider uiProvider, Composite part, Node context) {
216                 CmsUiUtils.clear(part);
217                 uiProvider.createUiPart(part, context);
218         }
219
220         private CmsUiProvider findUiProvider(String pid) {
221                 if (!uiProvidersByPid.containsKey(pid))
222                         throw new IllegalArgumentException("No UI provider registered as " + pid);
223                 return uiProvidersByPid.get(pid).get();
224         }
225
226         private SuiteLayer findLayer(String pid) {
227                 if (!layersByPid.containsKey(pid))
228                         throw new IllegalArgumentException("No UI provider registered as " + pid);
229                 return layersByPid.get(pid).get();
230         }
231
232         private <T> T findByType(Map<String, RankedObject<T>> byType, Node context) {
233                 if (context == null)
234                         throw new IllegalArgumentException("A node should be provided");
235                 try {
236                         // mixins
237                         Set<String> types = new TreeSet<>();
238                         for (NodeType nodeType : context.getMixinNodeTypes()) {
239                                 String typeName = nodeType.getName();
240                                 if (byType.containsKey(typeName)) {
241                                         types.add(typeName);
242                                 }
243                         }
244                         // primary node type
245                         {
246                                 NodeType nodeType = context.getPrimaryNodeType();
247                                 String typeName = nodeType.getName();
248                                 if (byType.containsKey(typeName)) {
249                                         types.add(typeName);
250                                 }
251                                 for (NodeType mixin : nodeType.getDeclaredSupertypes()) {
252                                         if (byType.containsKey(mixin.getName())) {
253                                                 types.add(mixin.getName());
254                                         }
255                                 }
256                         }
257                         // entity type
258                         if (context.isNodeType(EntityType.entity.get())) {
259                                 if (context.hasProperty(EntityNames.ENTITY_TYPE)) {
260                                         String typeName = context.getProperty(EntityNames.ENTITY_TYPE).getString();
261                                         if (byType.containsKey(typeName)) {
262                                                 types.add(typeName);
263                                         }
264                                 }
265                         }
266
267 //                      if (context.getPath().equals("/")) {// root node
268 //                              types.add("nt:folder");
269 //                      }
270                         if (NodeUtils.isUserHome(context) && byType.containsKey("nt:folder")) {// home node
271                                 types.add("nt:folder");
272                         }
273
274                         if (types.size() == 0)
275                                 throw new IllegalArgumentException("No type found for " + context);
276                         String type = types.iterator().next();
277                         if (!byType.containsKey(type))
278                                 throw new IllegalArgumentException("No component found for " + context + " with type " + type);
279                         return byType.get(type).get();
280                 } catch (RepositoryException e) {
281                         throw new IllegalStateException(e);
282                 }
283         }
284
285         @Override
286         public void setState(Composite parent, String state) {
287                 if (state == null)
288                         return;
289                 if (!state.startsWith("/")) {
290                         if (parent instanceof SuiteUi) {
291                                 SuiteUi ui = (SuiteUi) parent;
292                                 if (LOGIN.equals(state) || state.equals("~")) {
293                                         String appTitle = "";
294                                         if (ui.getTitle() != null)
295                                                 appTitle = ui.getTitle().lead();
296                                         ui.getCmsView().stateChanged(state, appTitle);
297                                         return;
298                                 }
299                                 String currentLayerId = ui.getCurrentLayerId();
300                                 if (state.equals(currentLayerId))
301                                         return; // does nothing
302                                 else {
303                                         Map<String, Object> properties = new HashMap<>();
304                                         properties.put(SuiteEvent.LAYER, state);
305                                         ui.getCmsView().sendEvent(SuiteEvent.switchLayer.topic(), properties);
306                                 }
307                         }
308                         return;
309                 }
310                 SuiteUi suiteUi = (SuiteUi) parent;
311                 Node node = stateToNode(suiteUi, state);
312                 if (node == null) {
313                         suiteUi.getCmsView().navigateTo("~");
314                 } else {
315                         suiteUi.getCmsView().sendEvent(SuiteEvent.switchLayer.topic(), SuiteEvent.eventProperties(node));
316                         suiteUi.getCmsView().sendEvent(SuiteEvent.refreshPart.topic(), SuiteEvent.eventProperties(node));
317                 }
318         }
319
320         private String nodeToState(Node node) {
321                 return '/' + Jcr.getWorkspaceName(node) + Jcr.getPath(node);
322         }
323
324         private Node stateToNode(SuiteUi suiteUi, String state) {
325                 if (suiteUi == null)
326                         return null;
327                 if (state == null || !state.startsWith("/"))
328                         return null;
329
330                 String path = state.substring(1);
331                 String workspace;
332                 if (path.equals("")) {
333                         workspace = null;
334                         path = "/";
335                 } else {
336                         int index = path.indexOf('/');
337                         if (index == 0) {
338                                 log.error("Cannot interpret " + state);
339 //                              cmsView.navigateTo("~");
340                                 return null;
341                         } else if (index > 0) {
342                                 workspace = path.substring(0, index);
343                                 path = path.substring(index);
344                         } else {// index<0, assuming root node
345                                 workspace = path;
346                                 path = "/";
347                         }
348                 }
349                 Session session = suiteUi.getSession(workspace);
350                 if (session == null)
351                         return null;
352                 Node node = Jcr.getNode(session, path);
353                 return node;
354         }
355
356         /*
357          * Events management
358          */
359
360         @Override
361         public void handleEvent(Event event) {
362
363                 // Specific UI related events
364                 SuiteUi ui = getRelatedUi(event);
365                 if (ui == null)
366                         return;
367                 try {
368                         String appTitle = "";
369                         if (ui.getTitle() != null)
370                                 appTitle = ui.getTitle().lead() + " - ";
371
372 //                      String currentLayerId = ui.getCurrentLayerId();
373 //                      SuiteLayer currentLayer = currentLayerId != null ? layersByPid.get(currentLayerId).get() : null;
374                         if (SuiteUiUtils.isTopic(event, SuiteEvent.refreshPart)) {
375                                 Node node = getNode(ui, event);
376                                 if (node == null)
377                                         return;
378                                 CmsUiProvider uiProvider = findByType(uiProvidersByType, node);
379                                 SuiteLayer layer = findByType(layersByType, node);
380                                 ui.switchToLayer(layer, node);
381                                 ui.getCmsView().runAs(() -> layer.view(uiProvider, ui.getCurrentWorkArea(), node));
382                                 ui.getCmsView().stateChanged(nodeToState(node), appTitle + Jcr.getTitle(node));
383                         } else if (SuiteUiUtils.isTopic(event, SuiteEvent.openNewPart)) {
384                                 Node node = getNode(ui, event);
385                                 if (node == null)
386                                         return;
387                                 CmsUiProvider uiProvider = findByType(uiProvidersByType, node);
388                                 SuiteLayer layer = findByType(layersByType, node);
389                                 ui.switchToLayer(layer, node);
390                                 ui.getCmsView().runAs(() -> layer.open(uiProvider, ui.getCurrentWorkArea(), node));
391                                 ui.getCmsView().stateChanged(nodeToState(node), appTitle + Jcr.getTitle(node));
392                         } else if (SuiteUiUtils.isTopic(event, SuiteEvent.switchLayer)) {
393                                 String layerId = get(event, SuiteEvent.LAYER);
394                                 if (layerId != null) {
395 //                                      ui.switchToLayer(layerId, ui.getUserDir());
396                                         SuiteLayer suiteLayer = findLayer(layerId);
397                                         Localized layerTitle = suiteLayer.getTitle();
398                                         ui.getCmsView().runAs(() -> ui.switchToLayer(layerId, ui.getUserDir()));
399                                         String title = null;
400                                         if (layerTitle != null)
401                                                 title = layerTitle.lead();
402                                         ui.getCmsView().stateChanged(layerId, appTitle + title);
403                                 } else {
404                                         Node node = getNode(ui, event);
405                                         if (node != null) {
406                                                 SuiteLayer layer = findByType(layersByType, node);
407                                                 ui.getCmsView().runAs(() -> ui.switchToLayer(layer, node));
408                                         }
409                                 }
410                         }
411                 } catch (Exception e) {
412                         log.error("Cannot handle event " + event, e);
413 //                      CmsView.getCmsView(ui).exception(e);
414                 }
415
416         }
417
418         private Node getNode(SuiteUi ui, Event event) {
419                 String nodePath = get(event, SuiteEvent.NODE_PATH);
420                 String workspaceName = get(event, SuiteEvent.WORKSPACE);
421                 Session session = ui.getSession(workspaceName);
422                 Node node;
423                 if (nodePath == null) {
424                         // look for a user
425                         String username = get(event, SuiteEvent.USERNAME);
426                         if (username == null)
427                                 return null;
428                         User user = cmsUserManager.getUser(username);
429                         if (user == null)
430                                 return null;
431                         LdapName userDn;
432                         try {
433                                 userDn = new LdapName(user.getName());
434                         } catch (InvalidNameException e) {
435                                 throw new IllegalArgumentException("Badly formatted username", e);
436                         }
437                         String userNodePath = SuiteUtils.getUserNodePath(userDn);
438                         if (Jcr.itemExists(session, userNodePath))
439                                 node = Jcr.getNode(session, userNodePath);
440                         else {
441                                 Session adminSession = null;
442                                 try {
443                                         adminSession = NodeUtils.openDataAdminSession(getRepository(), workspaceName);
444                                         SuiteUtils.getOrCreateUserNode(adminSession, userDn);
445                                 } finally {
446                                         Jcr.logout(adminSession);
447                                 }
448                                 node = Jcr.getNode(session, userNodePath);
449                         }
450                 } else {
451                         node = Jcr.getNode(session, nodePath);
452                 }
453                 return node;
454         }
455
456         private SuiteUi getRelatedUi(Event event) {
457                 return managedUis.get(get(event, CMS_VIEW_UID_PROPERTY));
458         }
459
460         public static String get(Event event, String key) {
461                 Object value = event.getProperty(key);
462                 if (value == null)
463                         return null;
464 //                      throw new IllegalArgumentException("Property " + key + " must be set");
465                 return value.toString();
466
467         }
468
469         /*
470          * Dependency injection.
471          */
472
473         public void addUiProvider(CmsUiProvider uiProvider, Map<String, Object> properties) {
474                 if (properties.containsKey(Constants.SERVICE_PID)) {
475                         String pid = (String) properties.get(Constants.SERVICE_PID);
476                         RankedObject.putIfHigherRank(uiProvidersByPid, pid, uiProvider, properties);
477                 }
478                 if (properties.containsKey(EntityConstants.TYPE)) {
479                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
480                         for (String type : types)
481                                 RankedObject.putIfHigherRank(uiProvidersByType, type, uiProvider, properties);
482                 }
483         }
484
485         public void removeUiProvider(CmsUiProvider uiProvider, Map<String, Object> properties) {
486                 if (properties.containsKey(Constants.SERVICE_PID)) {
487                         String pid = (String) properties.get(Constants.SERVICE_PID);
488                         if (uiProvidersByPid.containsKey(pid)) {
489                                 if (uiProvidersByPid.get(pid).equals(new RankedObject<CmsUiProvider>(uiProvider, properties))) {
490                                         uiProvidersByPid.remove(pid);
491                                 }
492                         }
493                 }
494                 if (properties.containsKey(EntityConstants.TYPE)) {
495                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
496                         for (String type : types) {
497                                 if (uiProvidersByType.containsKey(type)) {
498                                         if (uiProvidersByType.get(type).equals(new RankedObject<CmsUiProvider>(uiProvider, properties))) {
499                                                 uiProvidersByType.remove(type);
500                                         }
501                                 }
502                         }
503                 }
504         }
505
506         public void addLayer(SuiteLayer layer, Map<String, Object> properties) {
507                 if (properties.containsKey(Constants.SERVICE_PID)) {
508                         String pid = (String) properties.get(Constants.SERVICE_PID);
509                         RankedObject.putIfHigherRank(layersByPid, pid, layer, properties);
510                 }
511                 if (properties.containsKey(EntityConstants.TYPE)) {
512                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
513                         for (String type : types)
514                                 RankedObject.putIfHigherRank(layersByType, type, layer, properties);
515                 }
516         }
517
518         public void removeLayer(SuiteLayer layer, Map<String, Object> properties) {
519                 if (properties.containsKey(Constants.SERVICE_PID)) {
520                         String pid = (String) properties.get(Constants.SERVICE_PID);
521                         if (layersByPid.containsKey(pid)) {
522                                 if (layersByPid.get(pid).equals(new RankedObject<SuiteLayer>(layer, properties))) {
523                                         layersByPid.remove(pid);
524                                 }
525                         }
526                 }
527                 if (properties.containsKey(EntityConstants.TYPE)) {
528                         List<String> types = LangUtils.toStringList(properties.get(EntityConstants.TYPE));
529                         for (String type : types) {
530                                 if (layersByType.containsKey(type)) {
531                                         if (layersByType.get(type).equals(new RankedObject<CmsUiProvider>(layer, properties))) {
532                                                 layersByType.remove(type);
533                                         }
534                                 }
535                         }
536                 }
537         }
538
539         public void setCmsUserManager(CmsUserManager cmsUserManager) {
540                 this.cmsUserManager = cmsUserManager;
541         }
542
543 }