Exemple #1
0
    def post(self, appname):
        try:
            self.appname = appname
            app = self.masterdb.applications.find_one(
                {'shortname': self.appname})

            if self.get_argument('appfullname', None):
                app['fullname'] = self.get_argument('appfullname')

            # Update app details
            if self.request.files:
                if self.request.files.has_key('appcertfile'):
                    rm_file(app.get('certfile', None))
                    app['certfile'] = save_file(
                        self.request.files['appcertfile'][0])

                if self.request.files.has_key('appkeyfile'):
                    rm_file(app.get('keyfile', None))
                    app['keyfile'] = save_file(
                        self.request.files['appkeyfile'][0])

                if self.request.files.has_key('mpnscertificatefile'):
                    rm_file(app.get('mpnscertificatefile', None))
                    app['mpnscertificatefile'] = save_file(
                        self.request.files['mpnscertificatefile'][0])
                    ## Update connections
                    self.mpnsconnections[app['shortname']] = []
                    mpns = MPNSClient(self.masterdb, app, 0)
                    self.mpnsconnections[app['shortname']].append(mpns)

            if self.get_argument('appdescription', None):
                app['description'] = self.get_argument('appdescription')

            if self.get_argument('blockediplist', None):
                app['blockediplist'] = self.get_argument(
                    'blockediplist').strip()
            else:
                app['blockediplist'] = ''

            updategcm = False
            if self.get_argument('gcmprojectnumber', None):
                if app.get(
                        'gcmprojectnumber',
                        '') != self.get_argument('gcmprojectnumber').strip():
                    app['gcmprojectnumber'] = self.get_argument(
                        'gcmprojectnumber').strip()
                    updategcm = True

            if self.get_argument('gcmapikey', None):
                if app.get('gcmapikey',
                           '') != self.get_argument('gcmapikey').strip():
                    app['gcmapikey'] = self.get_argument('gcmapikey').strip()
                    updategcm = True

            if updategcm:
                ## Update connections too
                self.gcmconnections[app['shortname']] = []
                gcm = GCMClient(app.get('gcmprojectnumber', ''),
                                app.get('gcmapikey', ''), app['shortname'], 0)
                self.gcmconnections[app['shortname']].append(gcm)

            if self.get_argument('connections', None):
                """If this value is greater than current apns connections,
                creating more
                If less than current apns connections, kill extra instances
                """
                if app.get('connections', 0) != int(
                        self.get_argument('connections')):
                    app['connections'] = int(self.get_argument('connections'))
                    self.stop_apns(app)
                    self.start_apns(app)

            if self.get_argument('performfeedbacktask', None):
                self.perform_feedback(app)

            if self.get_argument('launchapns', None):
                logging.info("Start APNS")
                app['enableapns'] = 1
                self.start_apns(app)

            if self.get_argument('stopapns', None):
                logging.info("Shutdown APNS")
                app['enableapns'] = 0
                self.stop_apns(app)

            if self.get_argument('turnonproduction', None):
                app['environment'] = 'production'
                self.stop_apns(app)
                self.start_apns(app)

            if self.get_argument('turnonsandbox', None):
                app['environment'] = 'sandbox'
                self.stop_apns(app)
                self.start_apns(app)

            updatewnsaccesstoken = False
            if self.get_argument('wnsclientid', None):
                wnsclientid = self.get_argument('wnsclientid').strip()
                if not wnsclientid == app.get('wnsclientid', ''):
                    app['wnsclientid'] = wnsclientid
                    updatewnsaccesstoken = True

            if self.get_argument('wnsclientsecret', None):
                wnsclientsecret = self.get_argument('wnsclientsecret').strip()
                if not wnsclientsecret == app.get('wnsclientsecret', ''):
                    app['wnsclientsecret'] = wnsclientsecret
                    updatewnsaccesstoken = True

            if updatewnsaccesstoken:
                url = 'https://login.live.com/accesstoken.srf'
                payload = {
                    'grant_type': 'client_credentials',
                    'client_id': app['wnsclientid'],
                    'client_secret': app['wnsclientsecret'],
                    'scope': 'notify.windows.com'
                }
                response = requests.post(url, data=payload)
                responsedata = response.json()
                if response.status_code != 200:
                    raise Exception('Invalid WNS secret')
                if 'access_token' in responsedata and 'token_type' in responsedata:
                    app['wnsaccesstoken'] = responsedata['access_token']
                    app['wnstokentype'] = responsedata['token_type']
                    app['wnstokenexpiry'] = int(
                        responsedata['expires_in']) + int(time.time())
                    ## Update connections too
                    self.wnsconnections[app['shortname']] = []
                    wns = WNSClient(self.masterdb, app, 0)
                    self.wnsconnections[app['shortname']].append(wns)

            updateclickatell = False
            if self.get_argument('clickatellusername', None):
                if app.get(
                        'clickatellusername',
                        '') != self.get_argument('clickatellusername').strip():
                    app['clickatellusername'] = self.get_argument(
                        'clickatellusername').strip()
                    updateclickatell = True

            if self.get_argument('clickatellpassword', None):
                if app.get(
                        'clickatellpassword',
                        '') != self.get_argument('clickatellpassword').strip():
                    app['clickatellpassword'] = self.get_argument(
                        'clickatellpassword').strip()
                    updateclickatell = True

            if self.get_argument('clickatellappid', None):
                if app.get('clickatellappid',
                           '') != self.get_argument('clickatellappid').strip():
                    app['clickatellappid'] = self.get_argument(
                        'clickatellappid').strip()
                    updateclickatell = True

            if updateclickatell:
                pass

            self.masterdb.applications.update({'shortname': self.appname},
                                              app,
                                              safe=True)
            self.redirect(r"/applications/%s/settings" % self.appname)
        except Exception as ex:
            logging.error(traceback.format_exc())
            self.render("app_settings.html", app=app, error=str(ex))
Exemple #2
0
    def post(self, appname):
        try:
            self.appname = appname
            app = self.masterdb.applications.find_one(
                {"shortname": self.appname})

            if self.get_argument("appfullname", None):
                app["fullname"] = self.get_argument("appfullname")

            # Update app details
            if self.request.files:
                if self.request.files.has_key("appcertfile"):
                    rm_file(app.get("certfile", None))
                    app["certfile"] = save_file(
                        self.request.files["appcertfile"][0])

                if self.request.files.has_key("appkeyfile"):
                    rm_file(app.get("keyfile", None))
                    app["keyfile"] = save_file(
                        self.request.files["appkeyfile"][0])

                if self.request.files.has_key("mpnscertificatefile"):
                    rm_file(app.get("mpnscertificatefile", None))
                    app["mpnscertificatefile"] = save_file(
                        self.request.files["mpnscertificatefile"][0])
                    ## Update connections
                    self.mpnsconnections[app["shortname"]] = []
                    mpns = MPNSClient(self.masterdb, app, 0)
                    self.mpnsconnections[app["shortname"]].append(mpns)

            if self.get_argument("appdescription", None):
                app["description"] = self.get_argument("appdescription")

            if self.get_argument("blockediplist", None):
                app["blockediplist"] = self.get_argument(
                    "blockediplist").strip()
            else:
                app["blockediplist"] = ""

            update_fcm = False
            if self.get_argument("fcm-project-id", None):
                if (app.get("fcm-project-id", "") !=
                        self.get_argument("fcm-project-id").strip()):
                    app["fcm-project-id"] = self.get_argument(
                        "fcm-project-id").strip()
                    update_fcm = True

            if self.get_argument("fcm-jsonkey", None):
                if (app.get("fcm-jsonkey", "") !=
                        self.get_argument("fcm-jsonkey").strip()):
                    app["fcm-jsonkey"] = self.get_argument(
                        "fcm-jsonkey").strip()
                    update_fcm = True

            if update_fcm:
                # reset fcm connections
                fcm = FCMClient(app["fcm-project-id"], app["fcm-jsonkey"],
                                app["shortname"], 0)
                self.fcmconnections[app["shortname"]] = [fcm]
                _logger.info(fcm)

            updategcm = False
            if self.get_argument("gcmprojectnumber", None):
                if (app.get("gcmprojectnumber", "") !=
                        self.get_argument("gcmprojectnumber").strip()):
                    app["gcmprojectnumber"] = self.get_argument(
                        "gcmprojectnumber").strip()
                    updategcm = True

            if self.get_argument("gcmapikey", None):
                if app.get("gcmapikey",
                           "") != self.get_argument("gcmapikey").strip():
                    app["gcmapikey"] = self.get_argument("gcmapikey").strip()
                    updategcm = True

            if updategcm:
                # reset gcm connections
                gcm = GCMClient(
                    app.get("gcmprojectnumber", ""),
                    app.get("gcmapikey", ""),
                    app["shortname"],
                    0,
                )
                self.gcmconnections[app["shortname"]] = [gcm]

            if self.get_argument("connections", None):
                """If this value is greater than current apns connections,
                creating more
                If less than current apns connections, kill extra instances
                """
                if app.get("connections", 0) != int(
                        self.get_argument("connections")):
                    app["connections"] = int(self.get_argument("connections"))
                    self.stop_apns(app)
                    self.start_apns(app)

            if self.get_argument("performfeedbacktask", None):
                self.perform_feedback(app)

            if self.get_argument("launchapns", None):
                logging.info("Start APNS")
                app["enableapns"] = 1
                self.start_apns(app)

            if self.get_argument("stopapns", None):
                logging.info("Shutdown APNS")
                app["enableapns"] = 0
                self.stop_apns(app)

            if self.get_argument("turnonproduction", None):
                app["environment"] = "production"
                self.stop_apns(app)
                self.start_apns(app)

            if self.get_argument("turnonsandbox", None):
                app["environment"] = "sandbox"
                self.stop_apns(app)
                self.start_apns(app)

            updatewnsaccesstoken = False
            if self.get_argument("wnsclientid", None):
                wnsclientid = self.get_argument("wnsclientid").strip()
                if not wnsclientid == app.get("wnsclientid", ""):
                    app["wnsclientid"] = wnsclientid
                    updatewnsaccesstoken = True

            if self.get_argument("wnsclientsecret", None):
                wnsclientsecret = self.get_argument("wnsclientsecret").strip()
                if not wnsclientsecret == app.get("wnsclientsecret", ""):
                    app["wnsclientsecret"] = wnsclientsecret
                    updatewnsaccesstoken = True

            if updatewnsaccesstoken:
                url = "https://login.live.com/accesstoken.srf"
                payload = {
                    "grant_type": "client_credentials",
                    "client_id": app["wnsclientid"],
                    "client_secret": app["wnsclientsecret"],
                    "scope": "notify.windows.com",
                }
                response = requests.post(url, data=payload)
                responsedata = response.json()
                if response.status_code != 200:
                    raise Exception("Invalid WNS secret")
                if "access_token" in responsedata and "token_type" in responsedata:
                    app["wnsaccesstoken"] = responsedata["access_token"]
                    app["wnstokentype"] = responsedata["token_type"]
                    app["wnstokenexpiry"] = int(
                        responsedata["expires_in"]) + int(time.time())
                    ## Update connections too
                    self.wnsconnections[app["shortname"]] = []
                    wns = WNSClient(self.masterdb, app, 0)
                    self.wnsconnections[app["shortname"]].append(wns)

            updateclickatell = False
            if self.get_argument("clickatellusername", None):
                if (app.get("clickatellusername", "") !=
                        self.get_argument("clickatellusername").strip()):
                    app["clickatellusername"] = self.get_argument(
                        "clickatellusername").strip()
                    updateclickatell = True

            if self.get_argument("clickatellpassword", None):
                if (app.get("clickatellpassword", "") !=
                        self.get_argument("clickatellpassword").strip()):
                    app["clickatellpassword"] = self.get_argument(
                        "clickatellpassword").strip()
                    updateclickatell = True

            if self.get_argument("clickatellappid", None):
                if (app.get("clickatellappid", "") !=
                        self.get_argument("clickatellappid").strip()):
                    app["clickatellappid"] = self.get_argument(
                        "clickatellappid").strip()
                    updateclickatell = True

            if updateclickatell:
                pass

            self.masterdb.applications.update({"shortname": self.appname}, app)
            self.redirect(r"/applications/%s/settings" % self.appname)
        except Exception as ex:
            logging.error(traceback.format_exc())
            self.render("app_settings.html", app=app, error=str(ex))
Exemple #3
0
def init_messaging_agents():
    services = {
        "apns": {},
        "fcm": {},
        "gcm": {},
        "mpns": {},
        "sms": {},
        "wns": {}
    }
    mongodb = None
    while not mongodb:
        try:
            mongodb = pymongo.MongoClient(options.mongohost, options.mongoport)
        except Exception as ex:
            _logger.error(ex)
    masterdb = mongodb[options.masterdb]
    # Authenticate if credentials are supplied.
    if options.dbuser is not None and options.dbpass is not None:
        masterdb.authenticate(options.dbuser,
                              options.dbpass,
                              source=options.dbauthsource)

    apps = masterdb.applications.find()
    for app in apps:
        """ APNs setup """
        services["apns"][app["shortname"]] = []
        conns = int(app["connections"])
        if conns < 1:
            conns = 1
        if "environment" not in app:
            app["environment"] = "sandbox"

        if (file_exists(app.get("certfile", False))
                and file_exists(app.get("keyfile", False))
                and "shortname" in app):
            if app.get("enableapns", False):
                for instanceid in range(0, conns):
                    try:
                        apn = APNClient(
                            app["environment"],
                            app["certfile"],
                            app["keyfile"],
                            app["shortname"],
                            instanceid,
                        )
                    except Exception as ex:
                        _logger.error(ex)
                        continue
                    services["apns"][app["shortname"]].append(apn)
        """ GCMClient setup """
        services["gcm"][app["shortname"]] = []
        if "gcmprojectnumber" in app and "gcmapikey" in app and "shortname" in app:
            try:
                http = GCMClient(app["gcmprojectnumber"], app["gcmapikey"],
                                 app["shortname"], 0)
            except Exception as ex:
                _logger.error(ex)
                continue
            services["gcm"][app["shortname"]].append(http)
        """ FCMClient setup """
        services["fcm"][app["shortname"]] = []
        if "fcm-project-id" in app and "fcm-jsonkey" in app and "shortname" in app:
            try:
                fcminstance = FCMClient(app["fcm-project-id"],
                                        app["fcm-jsonkey"], app["shortname"],
                                        0)
            except Exception as ex:
                _logger.error(ex)
                continue
            services["fcm"][app["shortname"]].append(fcminstance)
        """ WNS setup """
        services["wns"][app["shortname"]] = []
        if "wnsclientid" in app and "wnsclientsecret" in app and "shortname" in app:
            try:
                wns = WNSClient(masterdb, app, 0)
            except Exception as ex:
                _logger.error(ex)
                continue
            services["wns"][app["shortname"]].append(wns)
        """ MPNS setup """
        services["mpns"][app["shortname"]] = []
        try:
            mpns = MPNSClient(masterdb, app, 0)
        except Exception as ex:
            _logger.error(ex)
            continue
        services["mpns"][app["shortname"]].append(mpns)
        """ clickatell """
        services["sms"][app["shortname"]] = []
        try:
            sms = ClickatellClient(masterdb, app, 0)
        except Exception as ex:
            _logger.error(ex)
            continue
        services["sms"][app["shortname"]].append(sms)
    mongodb.close()
    return services
Exemple #4
0
def init_messaging_agents():
    services = {
        'gcm': {},
        'wns': {},
        'apns': {},
        'mpns': {},
        'sms': {},
    }
    mongodb = None
    while not mongodb:
        try:
            mongodb = Connection(options.mongohost, options.mongoport)
        except Exception as ex:
            _logger.error(ex)
    masterdb = mongodb[options.masterdb]
    apps = masterdb.applications.find()
    for app in apps:
        ''' APNs setup '''
        services['apns'][app['shortname']] = []
        conns = int(app['connections'])
        if conns < 1:
            conns = 1
        if 'environment' not in app:
            app['environment'] = 'sandbox'

        if file_exists(app.get('certfile', False)) and file_exists(
                app.get('keyfile', False)) and 'shortname' in app:
            if app.get('enableapns', False):
                for instanceid in range(0, conns):
                    try:
                        apn = APNClient(app['environment'], app['certfile'],
                                        app['keyfile'], app['shortname'],
                                        instanceid)
                    except Exception as ex:
                        _logger.error(ex)
                        continue
                    services['apns'][app['shortname']].append(apn)
        ''' GCMClient setup '''
        services['gcm'][app['shortname']] = []
        if 'gcmprojectnumber' in app and 'gcmapikey' in app and 'shortname' in app:
            try:
                http = GCMClient(app['gcmprojectnumber'], app['gcmapikey'],
                                 app['shortname'], 0)
            except Exception as ex:
                _logger.error(ex)
                continue
            services['gcm'][app['shortname']].append(http)
        ''' WNS setup '''
        services['wns'][app['shortname']] = []
        if 'wnsclientid' in app and 'wnsclientsecret' in app and 'shortname' in app:
            try:
                wns = WNSClient(masterdb, app, 0)
            except Exception as ex:
                _logger.error(ex)
                continue
            services['wns'][app['shortname']].append(wns)
        ''' MPNS setup '''
        services['mpns'][app['shortname']] = []
        try:
            mpns = MPNSClient(masterdb, app, 0)
        except Exception as ex:
            _logger.error(ex)
            continue
        services['mpns'][app['shortname']].append(mpns)
        ''' clickatell '''
        services['sms'][app['shortname']] = []
        try:
            sms = ClickatellClient(masterdb, app, 0)
        except Exception as ex:
            _logger.error(ex)
            continue
        services['sms'][app['shortname']].append(sms)
    mongodb.close()
    return services