@@ -163,7 +163,7 @@ class Message(object):
163
163
apns: An instance of ``messaging.ApnsConfig`` (optional).
164
164
token: The registration token of the device to which the message should be sent (optional).
165
165
topic: Name of the FCM topic to which the message should be sent (optional). Topic name
166
- must not contain the ``/topics/`` prefix.
166
+ may contain the ``/topics/`` prefix.
167
167
condition: The FCM condition to which the message should be sent (optional).
168
168
"""
169
169
@@ -671,6 +671,18 @@ def encode_notification(cls, notification):
671
671
}
672
672
return cls .remove_null_values (result )
673
673
674
+ @classmethod
675
+ def sanitize_topic_name (cls , topic ):
676
+ if not topic :
677
+ return None
678
+ prefix = '/topics/'
679
+ if topic .startswith (prefix ):
680
+ topic = topic [len (prefix ):]
681
+ # Checks for illegal characters and empty string.
682
+ if not re .match (r'^[a-zA-Z0-9-_\.~%]+$' , topic ):
683
+ raise ValueError ('Malformed topic name.' )
684
+ return topic
685
+
674
686
def default (self , obj ): # pylint: disable=method-hidden
675
687
if not isinstance (obj , Message ):
676
688
return json .JSONEncoder .default (self , obj )
@@ -685,16 +697,11 @@ def default(self, obj): # pylint: disable=method-hidden
685
697
'topic' : _Validators .check_string ('Message.topic' , obj .topic , non_empty = True ),
686
698
'webpush' : _MessageEncoder .encode_webpush (obj .webpush ),
687
699
}
700
+ result ['topic' ] = _MessageEncoder .sanitize_topic_name (result .get ('topic' ))
688
701
result = _MessageEncoder .remove_null_values (result )
689
702
target_count = sum ([t in result for t in ['token' , 'topic' , 'condition' ]])
690
703
if target_count != 1 :
691
704
raise ValueError ('Exactly one of token, topic or condition must be specified.' )
692
- topic = result .get ('topic' )
693
- if topic :
694
- if topic .startswith ('/topics/' ):
695
- raise ValueError ('Topic name must not contain the /topics/ prefix.' )
696
- if not re .match (r'^[a-zA-Z0-9-_\.~%]+$' , topic ):
697
- raise ValueError ('Illegal characters in topic name.' )
698
705
return result
699
706
700
707
0 commit comments