技術者向けテクニカルtips
 / 

Liferay 7の通知設定(ノーティフィケーション)

Liferay DXP 7.0での通知設定について、通知の作成と送信をサポートする基本コードのご紹介です。

基礎


※本記事はLiferay Community Blogに投稿されている”Liferay 7 Notifications”を翻訳したものです。配信元または著者の許可を得て配信しています。
※オリジナルの英記事著者:David H Nebinger サウスカロライナ州のサマーヴィルに住むLiferay, Inc.のSoftware Architect/リードコンサルタント。Liferay Communityサイトにて、多くの技術情報を投稿するなど精力的に活動しています。

こんにちは。
日本ライフレイ、サポータビリティエンジニアの竹生(たけお)です。

本記事では、Liferay 7の通知設定(ノーティフィケーション)について解説している記事を紹介します。

先日構築したプロジェクトにて、ユーザー通知を発信できることの利点を感じるところがありました。

Liferayには、購読と通知のための組み込みシステムがあります。これらのAPIを使用することで、プロジェクトに通知をすばやく追加することができます。

実装に入る前に、サブスクリプションAPIと通知APIの基礎についてご説明します。

まず特定する必要があるのは、イベントです。イベントとは、ユーザーが購読するもので、イベントが発生したときに通知を出します。通知の送信が必要になるときにわかるよう、予定リストを作成しておくことで、作業が簡単になります。

本ブログ記事では、次のようなサンプル実装を紹介します。管理者の役割を持つユーザーがログインしたときに、通知を発行するシステムを構築します。サイトにおいて有効なセキュリティを確保するには、無制限のアクセス権限がある管理者アカウントを誰も使用しないようにすることが賢明でしょう。なので、管理者がログインした際に通知を受ける設定をしておくのは、良いセキュリティテストの一つと言えます。

この"管理者がログインしました"というイベントをもとに、以下ブログ記事では購読と通知のサポートを構築していきます。

まずはじめに必要なものは、ポートレット・モジュールです(インターフェース要件があるため)。新しいポートレット・モジュールを構築することから始めます。 IDEを使用することもできますが、今回はIDEに関係なく参考にできるよう、Bladeコマンドを使用します。

  1. blade create -t mvcportlet -p com.dnebinger.admin.notification admin-notification
  2.  

これにより、希望するパッケージと単純なプロジェクトディレクトリを使用した新しいLiferay MVCポートレットが提供されます。

イベントを購読する


ユーザーが最初に行うことができるようにすべきことは、イベントに登録することです。ポータル内の例でいうと、ブログ(ユーザーが、すべてのブログあるいは個人のブログに更新情報の購読申し込むことができる)などがあります。そこで、ユーザーが該当イベントに登録する場所を特定することが重要です。場合によっては、ページ(ブログやフォーラムスレッド)の右側に表示される場合もあれば、設定パネルに移動したい場合もあります。

本ポートレットでは、実際のUI設計の作業はありません。購読/購読解除のチェックボックスが付いた、JSPを持つだけです。重要な部分は、LiferayサブスクリプションAPIを使用する点です。

サブスクリプションはcom.liferay.portal.kernel.service.SubscriptionLocalServiceサービスによって処理されます。購読するときはaddSubscription()メソッドを使用し、購読解除するときはdeleteSubscription()メソッドを使用します。

呼び出しの引数は次のとおり:

  • userId:購読/購読を解除しているユーザー
  • groupId:ユーザーが購読しているグループ(追加の場合)(doc libフォルダやフォーラムカテゴリのような 'containers'の場合​​)
  • className:更新を監視するユーザーのクラス名です
  • pkId:購読/購読解除するオブジェクトのプライマリキー

通常はSBエンティティに購読を構築するので、購読機能とデータアクセスを結合するために、サービスインタフェースに購読および購読解除のメソッドを配置するのが一般的な方法です。

このプロジェクトでは、実際にエンティティやデータアクセスレイヤーがないため、アクションコマンドハンドラで購読/購読解除を直接処理します。また、実際にはPK idを持たないので、ID 0とポートレットクラスをクラス名として使用します。

  1. @Component(
  2. immediate = true,
  3. property = {
  4. "javax.portlet.name=" + AdminNotificationPortletKeys.ADMIN_NOTIFICATION_PORTLET_KEY,
  5. "mvc.command.name=/update_subscription"
  6. },
  7. service = MVCActionCommand.class
  8. )
  9. public class SubscribeMVCActionCommand extends BaseMVCActionCommand {
  10. @Override
  11. protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
  12. String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
  13. if (Validator.isNull(cmd)) {
  14. // an error
  15. }
  16. long userId = PortalUtil.getUserId(actionRequest);
  17. if (Constants.SUBSCRIBE.equals(cmd)) {
  18. _subscriptionLocalService.addSubscription(userId, 0, AdminNotificationPortlet.class.getName(), 0);
  19. } else if (Constants.UNSUBSCRIBE.equals(cmd)) {
  20. _subscriptionLocalService.deleteSubscription(userId, AdminNotificationPortlet.class.getName(), 0);
  21. }
  22. }
  23. @Reference(unbind = "-")
  24. protected void setSubscriptionLocalService(final SubscriptionLocalService subscriptionLocalService) {
  25. _subscriptionLocalService = subscriptionLocalService;
  26. }
  27. private SubscriptionLocalService _subscriptionLocalService;
  28. }

ユーザー通知の設定


ユーザーは通知を発行するポートレットとは別に通知設定を管理できます。サイドバーの、[マイアカウント]に移動すると、[通知]オプションが表示されます。このリンクをクリックすると、通常、通知リストが表示されます。しかし、右上隅のドットメニューをクリックすると、「設定」を選択して、以下すべてを確認することができます。

このページには、登録されている通知ポートレットごとに折りたたみ可能な領域があり、各領域には、通知の種類と、EメールまたはWebサイトによる通知を受け取るスライダの項目があります(ポートレットが両方の通知タイプをサポートしていると仮定した場合)。今後、Liferayまたはチームが通知方法(SMSやその他)を追加する可能性があり、その場合、ポートレットは通知のタイプもサポートしている必要があります。

折りたたみパネルに登録し、このページに表示させるにはどうすればよいか?OSGi DSサービスの注釈を通してそれが可能です。

実装する必要があるクラスには、2種類あります。最初に、com.liferay.portal.kernel.notifications.UserNotificationDefinitionクラスが拡張されます。クラス名が示唆するように、このクラスは、ポートレットが送信できる通知のタイプと、それがサポートする通知タイプの定義を提供します。

  1. @Component(
  2. immediate = true,
  3. property = {"javax.portlet.name=" + AdminNotificationPortletKeys.ADMIN_NOTIFICATION},
  4. service = UserNotificationDefinition.class
  5. )
  6. public class AdminLoginUserNotificationDefinition extends UserNotificationDefinition {
  7. public AdminLoginUserNotificationDefinition() {
  8. // pass in our portlet key, 0 for a class name id (don't care about it), the notification type (not really), and
  9. // finally the resource bundle key for the message the user sees.
  10. super(AdminNotificationPortletKeys.ADMIN_NOTIFICATION, 0,
  11. AdminNotificationType.NOTIFICATION_TYPE_ADMINISTRATOR_LOGIN,
  12. "receive-a-notification-when-an-admin-logs-in");
  13. // add a notification type for each sort of notification that we want to support.
  14. addUserNotificationDeliveryType(
  15. new UserNotificationDeliveryType(
  16. "email", UserNotificationDeliveryConstants.TYPE_EMAIL, true, true));
  17. addUserNotificationDeliveryType(
  18. new UserNotificationDeliveryType(
  19. "website", UserNotificationDeliveryConstants.TYPE_WEBSITE, true, true));
  20. }
  21. }

この定義は「通知定義」を登録し、通知します。コンストラクタは通知をカスタム・ポートレットにバインドし、通知パネルのメッセージ・キーを提供します。また、Eメールの送信用と、通知ポートレット用の、2つのユーザー通知配信タイプも追加します。

[マイアカウント]の[通知]パネルに移動し、右上隅のドロップダウンメニューの[設定]オプションを選択すると、通知設定が表示されます。

通知の処理


通知のもう1つの側面は、UserNotificationHandler実装です。 UserNotificationHandlerの仕事は、通知イベントを解釈し、通知を配信するかどうかを判断し、UserNotificationFeedEntry(基本的に通知メッセージ自体)を構築することです。

Liferayには、独自のUserNotificationHandlerインスタンスを構築するために使用できるいくつかの基本実装クラスが用意されています:

  • com.liferay.portal.kernel.notifications.BaseUserNotificationHandler - 通知の本体、およびその他の重要な点をオーバーライドするためのポイントを持つ簡単なユーザ通知ハンドラを実装します。ほとんどの場合、すべての基本的な通知の詳細を構築できます。
  • com.liferay.portal.kernel.notifications.BaseModelUserNotificationHandler - 通知のアセット対応エンティティに適した別の基本クラスです。エンティティクラスのAssetRendererを使用して、アセットをレンダリングし、これを通知のメッセージとして使用します。

明らかにアセット対応のエンティティが通知されている場合は、BaseModelUserNotificationHandlerを使用することをおすすめめします。
実装ではBaseUserNotificationHandlerを基本クラスとして使用します:

  1. @Component(
  2. immediate = true,
  3. property = {"javax.portlet.name=" + AdminNotificationPortletKeys.ADMIN_NOTIFICATION},
  4. service = UserNotificationHandler.class
  5. )
  6. public class AdminLoginUserNotificationHandler extends BaseUserNotificationHandler {
  7. /**
  8. * AdminLoginUserNotificationHandler: Constructor class.
  9. */
  10. public AdminLoginUserNotificationHandler() {
  11. setPortletId(AdminNotificationPortletKeys.ADMIN_NOTIFICATION);
  12. }
  13. @Override
  14. protected String getBody(UserNotificationEvent userNotificationEvent, ServiceContext serviceContext) throws Exception {
  15. String username = LanguageUtil.get(serviceContext.getLocale(), _UKNOWN_USER_KEY);
  16. // okay, we need to get the user for the event
  17. User user = _userLocalService.fetchUser(userNotificationEvent.getUserId());
  18. if (Validator.isNotNull(user)) {
  19. // get the company the user belongs to.
  20. Company company = _companyLocalService.fetchCompany(user.getCompanyId());
  21. // based on the company auth type, find the user name to display.
  22. // so we'll get screen name or email address or whatever they're using to log in.
  23. if (Validator.isNotNull(company)) {
  24. if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
  25. username = user.getEmailAddress();
  26. } else if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_SN)) {
  27. username = user.getScreenName();
  28. } else if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_ID)) {
  29. username = String.valueOf(user.getUserId());
  30. }
  31. }
  32. }
  33. // we'll be stashing the client address in the payload of the event, so let's extract it here.
  34. JSONObject jsonObject = JSONFactoryUtil.createJSONObject(
  35. userNotificationEvent.getPayload());
  36. String fromHost = jsonObject.getString(Constants.FROM_HOST);
  37. // fetch our strings via the language bundle.
  38. String title = LanguageUtil.get(serviceContext.getLocale(), _TITLE_KEY);
  39. String body = LanguageUtil.format(serviceContext.getLocale(), _BODY_KEY, new Object[] {username, fromHost});
  40. // build the html using our template.
  41. String html = StringUtil.replace(_BODY_TEMPLATE, _BODY_REPLACEMENTS, new String[] {title, body});
  42. return html;
  43. }
  44. @Reference(unbind = "-")
  45. protected void setUserLocalService(final UserLocalService userLocalService) {
  46. _userLocalService = userLocalService;
  47. }
  48. @Reference(unbind = "-")
  49. protected void setCompanyLocalService(final CompanyLocalService companyLocalService) {
  50. _companyLocalService = companyLocalService;
  51. }
  52. private UserLocalService _userLocalService;
  53. private CompanyLocalService _companyLocalService;
  54. private static final String _TITLE_KEY = "title.admin.login";
  55. private static final String _BODY_KEY = "body.admin.login";
  56. private static final String _UKNOWN_USER_KEY = "unknown.user";
  57. private static final String _BODY_TEMPLATE = "[$TITLE$][$BODY$]"; private static final String[] _BODY_REPLACEMENTS = new String[] {"[$TITLE$]", "[$BODY$]"};
  58.  private static final Log _log = LogFactoryUtil.getLog(AdminLoginUserNotificationHandler.class); }

このハンドラは基本的に管理者ログインの詳細(ユーザとログイン先)に基づいて通知本体を構築します。独自の通知を作成する場合、通知イベントペイロードを使用して詳細を渡すことがよくあります。管理者が訪問したホスト情報だけを渡すため、今回のペイロードは単純なものになりますが、必要な通知の詳細を渡すXMLまたはJSONなどの構造化文字列を、簡単に渡すことができます。

このハンドラは、Eメールと通知ポートレットの両方の表示に同内容の通知を作成しますが、この2つに違いはありません。メソッドにはUserNotificationEventが渡されるため、Eメール通知を作成するか、通知ポートレット表示メッセージを作成するかによって、getDeliveryType()メソッドを使用して異なるボディを構築できます。

通知イベントの発行


ここまでで、1.ユーザーが管理者ログインのイベントを購読できるようにする、2.通知の受信方法を選択できるようにする、そして、3.通知イベントを通知メッセージに変換できるようにするコードを紹介しました。残っているのは、通知イベント自体を、実際に発行することです。

これはイベントソースに非常に依存しています。ほとんどのLiferayイベントは、あるエンティティの追加または変更に基づいているため、エンティティが追加または更新されたときに、イベント実装のコードを、サービス実装クラスで見つけるのが一般的です。自分の通知イベントは、イベントが発生したどこからでも、サービスレイヤーの外からでも発行することができます。

今回の通知イベントは、管理者のログインに基づいています。これらの種類のイベントを発行する最善の方法は、ログイン後のコンポーネントを使用することです。新しいコンポーネントは次のように定義します。

  1. @Component(
  2. immediate = true, property = {"key=login.events.post"},
  3. service = LifecycleAction.class
  4. )
  5. public class AdminLoginNotificationEventSender implements LifecycleAction {
  6. @Override
  7. public void processLifecycleEvent(LifecycleEvent lifecycleEvent)
  8. throws ActionException {
  9. // get the request associated with the event
  10. HttpServletRequest request = lifecycleEvent.getRequest();
  11. // get the user associated with the event
  12. User user = null;
  13. try {
  14. user = PortalUtil.getUser(request);
  15. } catch (PortalException e) {
  16. // failed to get the user, just ignore this
  17. }
  18. if (user == null) {
  19. // failed to get a valid user, just return.
  20. return;
  21. }
  22. // We have the user, but are they an admin?
  23. PermissionChecker permissionChecker = null;
  24. try {
  25. permissionChecker = PermissionCheckerFactoryUtil.create(user);
  26. } catch (Exception e) {
  27. // ignore the exception
  28. }
  29. if (permissionChecker == null) {
  30. // failed to get a permission checker
  31. return;
  32. }
  33. // If the permission checker indicates the user is not omniadmin, nothing to report.
  34. if (! permissionChecker.isOmniadmin()) {
  35. return;
  36. }
  37. // this user is an administrator, need to issue the event
  38. ServiceContext serviceContext = null;
  39. try {
  40. // create a service context for the call
  41. serviceContext = ServiceContextFactory.getInstance(request);
  42. // note that when you're behind an LB, the remote host may be the address
  43. // for the LB instead of the remote client. In these cases the LB will often
  44. // add a request header with a special key that holds the remote client host
  45. // so you'd want to use that if it is available.
  46. String fromHost = request.getRemoteHost();
  47. // notify subscribers
  48. notifySubscribers(user.getUserId(), fromHost, user.getCompanyId(), serviceContext);
  49. } catch (PortalException e) {
  50. // ignored
  51. }
  52. }
  53. protected void notifySubscribers(long userId, String fromHost, long companyId, ServiceContext serviceContext)
  54. throws PortalException {
  55. // so all of this stuff should normally come from some kind of configuration.
  56. // As this is just an example, we're using a lot of hard coded values and portal-ext.properties values.
  57. String entryTitle = "Admin User Login";
  58. String fromName = PropsUtil.get(Constants.EMAIL_FROM_NAME);
  59. String fromAddress = GetterUtil.getString(PropsUtil.get(Constants.EMAIL_FROM_ADDRESS), PropsUtil.get(PropsKeys.ADMIN_EMAIL_FROM_ADDRESS));
  60. LocalizedValuesMap subjectLocalizedValuesMap = new LocalizedValuesMap();
  61. LocalizedValuesMap bodyLocalizedValuesMap = new LocalizedValuesMap();
  62. subjectLocalizedValuesMap.put(Locale.ENGLISH, "Administrator Login");
  63. bodyLocalizedValuesMap.put(Locale.ENGLISH, "Adminstrator has logged in.");
  64. AdminLoginSubscriptionSender subscriptionSender =
  65. new AdminLoginSubscriptionSender();
  66. subscriptionSender.setFromHost(fromHost);
  67. subscriptionSender.setClassPK(0);
  68. subscriptionSender.setClassName(AdminNotificationPortlet.class.getName());
  69. subscriptionSender.setCompanyId(companyId);
  70. subscriptionSender.setCurrentUserId(userId);
  71. subscriptionSender.setEntryTitle(entryTitle);
  72. subscriptionSender.setFrom(fromAddress, fromName);
  73. subscriptionSender.setHtmlFormat(true);
  74. int notificationType = AdminNotificationType.NOTIFICATION_TYPE_ADMINISTRATOR_LOGIN;
  75. subscriptionSender.setNotificationType(notificationType);
  76. String portletId = PortletProviderUtil.getPortletId(AdminNotificationPortletKeys.ADMIN_NOTIFICATION, PortletProvider.Action.VIEW);
  77. subscriptionSender.setPortletId(portletId);
  78. subscriptionSender.setReplyToAddress(fromAddress);
  79. subscriptionSender.setServiceContext(serviceContext);
  80. subscriptionSender.addPersistedSubscribers(
  81. AdminNotificationPortlet.class.getName(), 0);
  82. subscriptionSender.flushNotificationsAsync();
  83. }
  84. }

これは、ログイン後のライフサイクルイベントリスナーとして登録する、LifecycleActionコンポーネントです。一連のチェックを経て、ユーザーが管理者であるかどうかを判断し、管理者であれば通知を出します。実際の処理はnotifySubscribers()メソッドで起こります。

このメソッドには、多くの初期化とsubscriptionSenderプロパティの設定があります。この変数の型はAdminLoginSubscriptionSenderで、SubscriptionSenderを継承したクラスです。これは、実際の通知送信を処理するものです。flushNotificationAsync()メソッドは、メッセージ受信者がSubscriptionSenderを取得し、そのflushNotification()メソッドを呼び出すLiferayメッセージバスにインスタンスをプッシュします(非同期通知送信が不要な場合でもこのメソッドを呼び出すことができます)。

flushNotification()メソッドは、権限チェック、ユーザー確認、フィルタリング(イベントを生成したユーザーには通知を送信しない)を行い、最終的にEメール通知を送信したり、通知ポートレットのユーザー通知を追加したりします。

AdminLoginSubscriptionSenderクラスはとてもシンプルです:

  1. public class AdminLoginSubscriptionSender extends SubscriptionSender {
  2. private static final long serialVersionUID = -7152698157653361441L;
  3. protected void populateNotificationEventJSONObject(
  4. JSONObject notificationEventJSONObject) {
  5. super.populateNotificationEventJSONObject(notificationEventJSONObject);
  6. notificationEventJSONObject.put(Constants.FROM_HOST, _fromHost);
  7. }
  8. @Override
  9. protected boolean hasPermission(Subscription subscription, String className, long classPK, User user) throws Exception {
  10. return true;
  11. }
  12. @Override
  13. protected boolean hasPermission(Subscription subscription, User user) throws Exception {
  14. return true;
  15. }
  16. @Override
  17. protected void sendNotification(User user) throws Exception {
  18. // remove the super classes filtering of not notifying user who is self.
  19. // makes sense in most cases, but we want a notification of admin login so
  20. // we know when never any admin logs in from anywhere at any time.
  21. // will be a pain if we get notified because of our own login, but we want to
  22. // know if some hacker gets our admin credentials and logs in and it's not really us.
  23. sendEmailNotification(user);
  24. sendUserNotification(user);
  25. }
  26. public void setFromHost(String fromHost) {
  27. this._fromHost = fromHost;
  28. }
  29. private String _fromHost;
  30. }

まとめ


これで実装に必要なすべてが揃いました:

  • ユーザーに管理者ログインイベントを購読できるようにするコード
  • ユーザーが通知を受け取る方法を選択できるようにするコード
  • 通知ポートレットに表示するために、データベース内の通知メッセージを、HTMLに変換するコード
  • 管理者がログインしたときに通知を送信するコード

モジュールのビルドと、デプロイすれば、ほぼほぼ準備完了です。テストをしてみましょう。

まずログインして、通知を受け取る設定をする必要があります。ローカルのLiferayテスト環境を使用している場合、Eメールが有効になっていない可能性がありますので、必ずWeb通知を使用してください。実際、私のDXP環境では、Eメール設定がされておらず、LiferayのEメールサブシステムから数多くの例外を受信しました。Eメールを設定をされてないので無視しました。

その後ログアウトし、管理者として再度ログインすると、左側のサイドバーに通知ポップアップが表示されるはずです。

 

おわりに

通知の作成と送信をサポートする基本コードをご紹介しました。このコードを使用して、独自のポートレットに通知サポートを追加し、必要に応じて通知を受け取ることができます。

このプロジェクトのコードは以下githubでも参照できます:https://github.com/dnebing/admin-notification

ぜひ使ってみてください!


本記事は以上です。
いかがでしたでしょうか?

記事に関するご意見、ご感想などございましたら、お気軽にyasuyuki.takeo@liferay.comまでご連絡くだい。


■ これまで発信してきた日本語による技術コンテンツを、Qiitaでお読みいただけます。よろしければそちらの記事も合わせてご役立てください。
https://qiita.com/yasuflatland-lf

■ Doorkeeperのライフレイコミュニティメンバー大歓迎!
コーポレートブログの技術コンテンツ更新情報など定期的におとどけしています。
https://liferay.doorkeeper.jp/