<commit_before>################################################################################
# gae_python_gcm/gcm.py
#
# In Python, for Google App Engine
# Originally ported from https://github.com/Instagram/node2dm
# Extended to support new GCM API.
# <NAME> <<EMAIL>>
#
# From: https://github.com/gregbayer/gae-python-gcm
#
###############################################################################
#
# 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.
#
################################################################################

from datetime import datetime, timedelta
import logging
import re
import json
import importlib

from google.appengine.api import taskqueue  # Google App Engine specific

from helpers.push_helper import PushHelper

from models.sitevar import Sitevar


class GCMMessage:
    device_tokens = None
    notification = None
    collapse_key = None
    delay_while_idle = None
    time_to_live = None
    priority = None

    def __init__(self, device_tokens, notification, collapse_key=None, delay_while_idle=None, time_to_live=None, priority=None):
        if isinstance(device_tokens, list):
            self.device_tokens = device_tokens
        else:
            self.device_tokens = [device_tokens]

        self.notification = notification
        self.collapse_key = collapse_key
        self.delay_while_idle = delay_while_idle
        self.time_to_live = time_to_live
        self.priority = priority

    def __unicode__(self):
        return "%s:%s:%s:%s:%s" % (repr(self.device_tokens), repr(self.notification), repr(self.collapse_key), repr(self.delay_while_idle), repr(self.time_to_live))

    def json_string(self):

        if not self.device_tokens or not isinstance(self.device_tokens, list):
            logging.error('FCMMessage generate_json_string error. Invalid device tokens: ' + repr(self))
            raise Exception('FCMMessage generate_json_string error. Invalid device tokens.')

        json_dict = {}
        json_dict['registration_ids'] = self.device_tokens

        # If message is a dict, send each key individually
        # Else, send entire message under data key
        if isinstance(self.notification, dict):
            json_dict['data'] = self.notification
        else:
            json_dict['data'] = {'data': self.notification}

        if self.collapse_key:
            json_dict['collapse_key'] = self.collapse_key
        if self.delay_while_idle:
            json_dict['delay_while_idle'] = self.delay_while_idle
        if self.time_to_live:
            json_dict['time_to_live'] = self.time_to_live
        if self.priority:
            json_dict['priority'] = self.priority

        json_str = json.dumps(json_dict)
        return json_str


# Instantiate to send GCM message. No initialization required.
class GCMConnection:

    ################################     Config     ###############################
    # settings.py
    #
    #     GCM_CONFIG = {'gcm_api_key': '',
    #                   'delete_bad_token_callback_func': lambda x: x,
    #                   'update_token_callback_func': lambda x: x}
    ##############################################################################

    def __init__(self):
        self.LOCALHOST = False
        self.SERVER_KEY = Sitevar.get_by_id('gcm.serverKey')
        if self.SERVER_KEY is None:
            raise Exception("Missing sitevar: gcm.serverKey. Can't send FCM messages.")
        self.GCM_CONFIG = {'gcm_api_key': self.SERVER_KEY.contents['gcm_key']}
        self.GOOGLE_LOGIN_URL = 'https://www.google.com/accounts/ClientLogin'
        # Can't use https on localhost due to Google cert bug
        self.GOOGLE_GCM_SEND_URL = 'https://fcm.googleapis.com/fcm'

        self.GCM_QUEUE_NAME = 'gcm-retries'
        self.GCM_QUEUE_CALLBACK_URL = '/gae_python_gcm/send_request'<commit_msg>Fix fcm url<commit_after>################################################################################
# gae_python_gcm/gcm.py
#
# In Python, for Google App Engine
# Originally ported from https://github.com/Instagram/node2dm
# Extended to support new GCM API.
# <NAME> <<EMAIL>>
#
# From: https://github.com/gregbayer/gae-python-gcm
#
###############################################################################
#
# 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.
#
################################################################################

from datetime import datetime, timedelta
import logging
import re
import json
import importlib

from google.appengine.api import taskqueue  # Google App Engine specific

from helpers.push_helper import PushHelper

from models.sitevar import Sitevar


class GCMMessage:
    device_tokens = None
    notification = None
    collapse_key = None
    delay_while_idle = None
    time_to_live = None
    priority = None

    def __init__(self, device_tokens, notification, collapse_key=None, delay_while_idle=None, time_to_live=None, priority=None):
        if isinstance(device_tokens, list):
            self.device_tokens = device_tokens
        else:
            self.device_tokens = [device_tokens]

        self.notification = notification
        self.collapse_key = collapse_key
        self.delay_while_idle = delay_while_idle
        self.time_to_live = time_to_live
        self.priority = priority

    def __unicode__(self):
        return "%s:%s:%s:%s:%s" % (repr(self.device_tokens), repr(self.notification), repr(self.collapse_key), repr(self.delay_while_idle), repr(self.time_to_live))

    def json_string(self):

        if not self.device_tokens or not isinstance(self.device_tokens, list):
            logging.error('FCMMessage generate_json_string error. Invalid device tokens: ' + repr(self))
            raise Exception('FCMMessage generate_json_string error. Invalid device tokens.')

        json_dict = {}
        json_dict['registration_ids'] = self.device_tokens

        # If message is a dict, send each key individually
        # Else, send entire message under data key
        if isinstance(self.notification, dict):
            json_dict['data'] = self.notification
        else:
            json_dict['data'] = {'data': self.notification}

        if self.collapse_key:
            json_dict['collapse_key'] = self.collapse_key
        if self.delay_while_idle:
            json_dict['delay_while_idle'] = self.delay_while_idle
        if self.time_to_live:
            json_dict['time_to_live'] = self.time_to_live
        if self.priority:
            json_dict['priority'] = self.priority

        json_str = json.dumps(json_dict)
        return json_str


# Instantiate to send GCM message. No initialization required.
class GCMConnection:

    ################################     Config     ###############################
    # settings.py
    #
    #     GCM_CONFIG = {'gcm_api_key': '',
    #                   'delete_bad_token_callback_func': lambda x: x,
    #                   'update_token_callback_func': lambda x: x}
    ##############################################################################

    def __init__(self):
        self.LOCALHOST = False
        self.SERVER_KEY = Sitevar.get_by_id('gcm.serverKey')
        if self.SERVER_KEY is None:
            raise Exception("Missing sitevar: gcm.serverKey. Can't send FCM messages.")
        self.GCM_CONFIG = {'gcm_api_key': self.SERVER_KEY.contents['gcm_key']}
        self.GOOGLE_LOGIN_URL = 'https://www.google.com/accounts/ClientLogin'
        # Can't use https on localhost due to Google cert bug
        self.GOOGLE_GCM_SEND_URL = 'https://fcm.googleapis.com/fcm/send'

        self.GCM_QUEUE_NAME = 'gcm-retries'
        self.GCM_QUEUE_CALLBACK_URL = '/gae_python_gcm/send_request'
{'fraction_non_alphanumeric': 0.16898974772491648, 'fraction_numerical': 0.0011519410206197443, 'mean_word_length': 3.3848484848484848, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 8, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3789940', 'n_tokens_mistral': 2438, 'n_tokens_neox': 2353, 'n_words': 621}