Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web push notification w/ FCM topic #368

Draft
wants to merge 17 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions apps/core/migrations/0057_alter_notification_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 4.2.5 on 2023-11-02 15:18

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("core", "0056_alter_article_comment_count_alter_article_hit_count_and_more"),
]

operations = [
migrations.AlterField(
model_name="notification",
name="type",
field=models.CharField(
choices=[
("default", "default"),
("article_commented", "article_commented"),
("comment_commented", "comment_commented"),
("article_new", "article_new"),
],
default="default",
max_length=32,
verbose_name="알림 종류",
),
),
]
12 changes: 12 additions & 0 deletions apps/core/migrations/0059_merge_20240206_2234.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Generated by Django 4.2.9 on 2024-02-06 13:34

from django.db import migrations


class Migration(migrations.Migration):
dependencies = [
("core", "0057_alter_notification_type"),
("core", "0058_merge_20240109_2331"),
]

operations = []
24 changes: 24 additions & 0 deletions apps/core/migrations/0060_alter_article_url.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 4.2.9 on 2024-02-06 13:34

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("core", "0059_merge_20240206_2234"),
]

operations = [
migrations.AlterField(
model_name="article",
name="url",
field=models.URLField(
blank=True,
db_index=True,
default=None,
max_length=256,
null=True,
verbose_name="포탈 링크",
),
),
]
124 changes: 103 additions & 21 deletions apps/core/models/notification.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
from django.contrib.auth import get_user_model
from django.db import models
from django.utils.functional import cached_property

from apps.user.models import FCMTopic
from ara.db.models import MetaDataModel
from ara.firebase import fcm_notify_comment
from ara.firebase import fcm_notify_topic, fcm_notify_user

User = get_user_model()

TYPE_CHOICES = (
("default", "default"),
("article_commented", "article_commented"),
("comment_commented", "comment_commented"),
("article_new", "article_new"),
)


Expand Down Expand Up @@ -56,47 +61,124 @@ def data(self) -> dict:
"click_action": "",
}

# TODO: Support English
# TODO: add test code
@classmethod
def notify_article(cls, article):
from apps.core.models import NotificationReadLog

board_topic_str = (
f" - {article.parent_topic.ko_name}" if article.parent_topic else ""
)
title = f"[{article.parent_board.ko_name}{board_topic_str}] 새로운 글이 달렸습니다: {article.title[:32]}"
topic = f"board_{article.parent_board_id}"

subs_id = FCMTopic.objects.filter(topic=topic).values_list("user", flat=True)
subs = User.objects.filter(id__in=subs_id)

NotificationReadLog.objects.bulk_create(
[
NotificationReadLog(
read_by=sub,
notification=cls.objects.create(
type="article_new",
title=title,
content=article.content_text[:32],
related_article=article,
related_comment=None,
),
)
for sub in subs
]
)
fcm_notify_topic(
topic,
title,
article.content_text[:32],
f"post/{article.id}",
)

@classmethod
def notify_commented(cls, comment):
from apps.core.models import NotificationReadLog

def notify_article_commented(_parent_article, _comment):
title = f"{_comment.created_by.profile.nickname} 님이 새로운 댓글을 작성했습니다."
NotificationReadLog.objects.create(
read_by=_parent_article.created_by,
notification=cls.objects.create(
type="article_commented",
title=title,
content=_comment.content[:32],
related_article=_parent_article,
related_comment=None,
),
topic = f"article_commented_{_parent_article.id}"

subs_id = list(
FCMTopic.objects.filter(topic=topic).values_list("user", flat=True)
)
subs_id.append(_parent_article.created_by.id)
subs = User.objects.filter(id__in=subs_id)

NotificationReadLog.objects.bulk_create(
[
NotificationReadLog(
read_by=sub,
notification=cls.objects.create(
type="article_commented",
title=title,
content=_comment.content[:32],
related_article=_parent_article,
related_comment=None,
),
)
for sub in subs
]
)
fcm_notify_comment(

fcm_notify_user(
_parent_article.created_by,
title,
_comment.content[:32],
f"post/{_parent_article.id}",
)
fcm_notify_topic(
topic,
title,
_comment.content[:32],
f"post/{_parent_article.id}",
)

def notify_comment_commented(_parent_article, _comment):
title = f"{_comment.created_by.profile.nickname} 님이 새로운 대댓글을 작성했습니다."
NotificationReadLog.objects.create(
read_by=_comment.parent_comment.created_by,
notification=cls.objects.create(
type="comment_commented",
title=title,
content=_comment.content[:32],
related_article=_parent_article,
related_comment=_comment.parent_comment,
),
topic = f"comment_commented_{_comment.parent_comment.id}"

subs_id = list(
FCMTopic.objects.filter(topic=topic).values_list("user", flat=True)
)
fcm_notify_comment(
subs_id.append(_comment.parent_comment.created_by.id)
subs = User.objects.filter(id__in=subs_id)

NotificationReadLog.objects.bulk_create(
[
NotificationReadLog(
read_by=sub,
notification=cls.objects.create(
type="comment_commented",
title=title,
content=_comment.content[:32],
related_article=_parent_article,
related_comment=_comment.parent_comment,
),
)
for sub in subs
]
)

fcm_notify_user(
_comment.parent_comment.created_by,
title,
_comment.content[:32],
f"post/{_parent_article.id}",
)
fcm_notify_topic(
topic,
title,
_comment.content[:32],
f"post/{_parent_article.id}",
)

article = (
comment.parent_article
Expand Down
1 change: 1 addition & 0 deletions apps/core/models/signals/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .article import *
from .block import *
from .comment import *
from .on_delete_cascade import *
Expand Down
11 changes: 11 additions & 0 deletions apps/core/models/signals/article.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.db import models
from django.dispatch import receiver
from django.utils import timezone

from apps.core.models import Article, Notification


@receiver(models.signals.post_save, sender=Article)
def comment_post_save_signal(created, instance, **kwargs):
TriangleYJ marked this conversation as resolved.
Show resolved Hide resolved
if created:
Notification.notify_article(instance)
52 changes: 52 additions & 0 deletions apps/user/migrations/0022_fcmtopic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Generated by Django 4.2.5 on 2023-11-02 15:18

import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("user", "0021_remove_userprofile_extra_preferences"),
]

operations = [
migrations.CreateModel(
name="FCMTopic",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"created_at",
models.DateTimeField(
db_index=True,
default=django.utils.timezone.now,
verbose_name="생성 시간",
),
),
("topic", models.CharField(max_length=200, verbose_name="알림 주제")),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="fcm_topic_set",
to=settings.AUTH_USER_MODEL,
verbose_name="유저",
),
),
],
options={
"ordering": ("-created_at",),
"unique_together": {("user", "topic")},
},
),
]
1 change: 1 addition & 0 deletions apps/user/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .fcm_token import *
from .fcm_topic import *
from .signals import *
from .user_profile import *
6 changes: 3 additions & 3 deletions apps/user/models/fcm_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@


class FCMToken(models.Model):
class Meta:
ordering = ("-created_at",)

created_at = models.DateTimeField(
default=timezone.now,
db_index=True,
Expand Down Expand Up @@ -35,3 +32,6 @@ class Meta:
is_web = models.BooleanField(
default=True, db_index=True, verbose_name="토큰 부여 플랫폼이 웹인지 여부"
)

class Meta:
ordering = ("-created_at",)
27 changes: 27 additions & 0 deletions apps/user/models/fcm_topic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from django.conf import settings
from django.db import models
from django.utils import timezone


class FCMTopic(models.Model):
created_at = models.DateTimeField(
default=timezone.now,
db_index=True,
verbose_name="생성 시간",
)

user = models.ForeignKey(
on_delete=models.CASCADE,
to=settings.AUTH_USER_MODEL,
related_name="fcm_topic_set",
verbose_name="유저",
)

topic = models.CharField(max_length=200, verbose_name="알림 주제")

class Meta:
ordering = ("-created_at",)
unique_together = (
"user",
"topic",
)
5 changes: 3 additions & 2 deletions apps/user/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.urls import include, path

from apps.user.views.fcmtoken import FCMTokenView
from apps.user.views.fcm import FCMTokenView, FCMTopicView
from apps.user.views.me import MeView
from apps.user.views.router import router

urlpatterns = [
path("api/", include(router.urls)),
path("api/me", MeView.as_view(), name="me"),
path("api/fcm_token/<mode>", FCMTokenView.as_view(), name="fcm"),
path("api/fcm/token/<mode>/", FCMTokenView.as_view(), name="fcm_token"),
path("api/fcm/topic/", FCMTopicView.as_view(), name="fcm_topic"),
]
Loading
Loading