Exemple #1
0
 def code():
     uuid = request.args["state"]
     code = generate_code()
     print(code)
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device_db = DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG)
         device_db.add_unpaired_device(uuid, code)
         result = {"code": code, "uuid": uuid}
     return nice_json(result)
Exemple #2
0
 def get_subscriber_voice_url(uuid=""):
     arch = request.args["arch"]
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_device_by_uuid(uuid)
         if device is not None:
             device.arch = arch
     return nice_json({"link": ""})
Exemple #3
0
 def activate():
     uuid = request.json["state"]
     from personal_mycroft_backend.settings import MAIL_USERNAME, MAIL_PASSWORD
     # AUto pairing, hell yeah
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_unpaired_by_uuid(uuid)
         if device is None:
             return Response(
                 'Could not verify your access level for that URL.\n'
                 'You have to authenticate with proper credentials', 401,
                 {'WWW-Authenticate': 'Basic realm="NOT PAIRED"'})
         user = device_db.get_user_by_uuid(uuid)
         # create user if it doesnt exist
         if not user:
             device_db.add_user(MAIL_USERNAME,
                                MAIL_USERNAME.split("@")[0], MAIL_PASSWORD)
         # auto pair!
         device_db.add_device(uuid,
                              mail=MAIL_USERNAME,
                              expires_at=time.time() + 72000,
                              accessToken=gen_api(),
                              refreshToken=gen_api())
         device_db.remove_unpaired(uuid)
         result = model_to_dict(device_db.get_device_by_uuid(uuid))
         print(result)
     return nice_json(result)
Exemple #4
0
    def token():
        api = request.headers.get('Authorization', '').replace("Bearer ", "")
        with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
            device = device_db.get_device_by_token(api)
            if not device:
                return Response(
                    'Could not verify your access level for that URL.\n'
                    'You have to authenticate with proper credentials', 401,
                    {'WWW-Authenticate': 'Basic realm="NOT PAIRED"'})
            # token to refresh expired token
            if device.refreshToken is None or device.refreshToken != api:
                return Response(
                    'Could not verify your access level for that URL.\n'
                    'You have to authenticate with proper credentials', 401,
                    {'WWW-Authenticate': 'Basic realm="BAD REFRESH CODE"'})
            # new tokens to access
            access_token = gen_api()
            new_refresh_token = gen_api()

            device_db.add_device(uuid=device.uuid,
                                 expires_at=time.time() + 72000,
                                 accessToken=access_token,
                                 refreshToken=new_refresh_token)
            result = model_to_dict(device)
        return nice_json(result)
Exemple #5
0
 def subscription_type(uuid=""):
     sub_type = "free"
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_device_by_uuid(uuid)
         if device is not None:
             sub_type = device.subscription
         subscription = {"@type": sub_type}
     return nice_json(subscription)
Exemple #6
0
 def metric(uuid="", name=""):
     data = request.json
     print(name, data)
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_device_by_uuid(uuid)
         if device is None:
             return
         device_db.add_metric(name=name, uuid=uuid, data=data)
Exemple #7
0
 def device():
     api = request.headers.get('Authorization', '').replace("Bearer ", "")
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_device_by_token(api)
         if device is not None:
             result = model_to_dict(device)
         else:
             result = {}
     return nice_json(result)
Exemple #8
0
def check_auth(api_key):
    """This function is called to check if a api key is valid."""
    with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
        device = device_db.get_device_by_token(api_key)
        result = True
        if not device:
            result = False
        elif device.expires_at < time.time():
            result = False
    return result
Exemple #9
0
def pair(code, mail_sender):
    with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
        device = device_db.get_unpaired_by_code(code)
        if device:
            user = get_user()
            if device_db.add_device(uuid=device.uuid, mail=user.mail):
                device_db.remove_unpaired(device.uuid)
                msg = Message("Device was paired", recipients=[user.mail])
                mail_sender.send(msg)
                return True
    return False
Exemple #10
0
 def send_mail(uuid=""):
     data = request.json
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         user = device_db.get_user_by_uuid(uuid)
         if user is not None:
             message = data["body"]
             subject = data["title"]
             msg = Message(recipients=[user.email],
                           body=message,
                           subject=subject,
                           sender=data["sender"])
             mail_sender.send(msg)
Exemple #11
0
 def pair(code, uuid, name, mail):
     # pair
     result = {"paired": False}
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_unpaired_by_uuid(uuid)
         if device and device.code == code:
             user = device_db.get_user_by_mail(mail)
             # create user if it doesnt exist
             if not user:
                 device_db.add_user(mail, name, "666")
             if device_db.add_device(uuid, mail=mail):
                 device_db.remove_unpaired(uuid)
                 result = {"paired": True}
     return nice_json(result)
Exemple #12
0
    def get_uuid(uuid):
        with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
            device = device_db.get_device_by_uuid(uuid)
            if device is not None:
                if request.method == 'PATCH':
                    result = request.json
                    device_db.add_device(
                        uuid=uuid,
                        name=result.get("name"),
                        expires_at=result.get("expires_at"),
                        accessToken=result.get("accessToken"),
                        refreshToken=result.get("refreshToken"))

                result = model_to_dict(device)
            else:
                result = {}
        return nice_json(result)
Exemple #13
0
 def location(uuid):
     with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
         device = device_db.get_device_by_uuid(uuid)
         if device is None:
             return nice_json({"error": "device not found"})
         if device.location.timezone is None:
             if not request.headers.getlist("X-Forwarded-For"):
                 ip = request.remote_addr
             else:
                 # TODO http://esd.io/blog/flask-apps-heroku-real-ip-spoofing.html
                 ip = request.headers.getlist("X-Forwarded-For")[0]
             device_db.add_ip(uuid, ip)
             new_location = geo_locate(ip)
             device_db.add_location(uuid, new_location)
             return nice_json(new_location)
         location = device.location
         result = location_dict(location.city, location.region_code,
                                location.country_code,
                                location.country_name, location.region,
                                location.longitude, location.latitude,
                                location.timezone)
     return nice_json(result)
Exemple #14
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 flask import Flask
from flask_mail import Mail
from flask_sslify import SSLify
from personal_mycroft_backend.settings import *
from personal_mycroft_backend.database.admin import AdminDatabase
from personal_mycroft_backend.database.devices import DeviceDatabase

ADMINS = AdminDatabase(SQL_ADMINS_URI, debug=DEBUG)
DEVICES = DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG)


def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = SECRET_KEY
    app.config['SECURITY_PASSWORD_SALT'] = SECURITY_PASSWORD_SALT

    mail = Mail(app)
    if SSL:
        sslify = SSLify(app)

    from personal_mycroft_backend.backend.utils import nice_json
    from personal_mycroft_backend.backend.decorators import noindex, donation
    from personal_mycroft_backend.backend.precise import get_precise_routes
    from personal_mycroft_backend.backend.auth import get_auth_routes
from personal_mycroft_backend.database.devices import DeviceDatabase

db = DeviceDatabase()

username = "******"
code = "XQFTNM"
uuid = "cc3524c7-ff52-42b3-af8f-de89249b19c8s"
mail = "fakemail2@not_real.com"

# add a device to the db
if not db.add_device(uuid):

    # cant commit device to db before pairing, make available for pairing
    db.add_unpaired_device(uuid, code)

    if not db.add_device(uuid):
        # user did not pair yet, perform manual pairing
        device = db.get_unpaired_by_code(code)
        if device:
            db.add_user(mail, username, "password")
            if db.add_device(uuid=device.uuid, mail=mail):
                db.remove_unpaired(device.uuid)

# Browse the db
device = db.get_device_by_uuid(uuid)
print(device.name)
print(device.last_seen)
print(device.created_at)
print(device.paired)
print(device.uuid)
print(device.ips)
Exemple #16
0
    def setting(uuid=""):
        with DeviceDatabase(SQL_DEVICES_URI, debug=DEBUG) as device_db:
            device = device_db.get_device_by_uuid(uuid)
            if device is not None:
                result = model_to_dict(device.config)

                # format result
                cleans = ["skills_dir", "skills_auto_update"]

                blacklisted = [
                    skill.folder for skill in device.config.skills
                    if skill.blacklisted
                ]
                priority = [
                    skill.folder for skill in device.config.skills
                    if skill.priority
                ]

                result["skills"] = {
                    "directory": device.config.skills_dir,
                    "auto_update": device.config.skills_auto_update,
                    "blacklisted_skills": blacklisted,
                    "priority_skills": priority
                }

                cleans += [
                    "listener_energy_ratio", "record_wake_words",
                    "record_utterances", "wake_word_upload", "stand_up_word",
                    "wake_word", "listener_sample_rate", "listener_channels",
                    "listener_multiplier", "phoneme_duration"
                ]

                result["listener"] = {
                    "sample_rate": result["listener_sample_rate"],
                    "channels": result["listener_channels"],
                    "record_wake_words": result["record_wake_words"],
                    "record_utterances": result["record_utterances"],
                    "phoneme_duration": result["phoneme_duration"],
                    "wake_word_upload": {
                        "enable": result["wake_word_upload"]
                    },
                    "multiplier": result["listener_multiplier"],
                    "energy_ratio": result["listener_energy_ratio"],
                    "wake_word": result["wake_word"],
                    "stand_up_word": result["stand_up_word"]
                }

                result["sounds"] = {}
                for sound in device.config.sounds:
                    result["sounds"][sound.name] = sound.path

                result["hotwords"] = {}
                for word in device.config.hotwords:
                    result["hotwords"][word.name] = {
                        "module": word.module,
                        "phonemes": word.phonemes,
                        "threshold": word.threshold,
                        "lang": word.lang,
                        "active": word.active,
                        "listen": word.listen,
                        "utterance": word.utterance,
                        "sound": word.sound
                    }
                stt = device.config.stt
                creds = {}
                if stt.engine_type == "token":
                    creds = {"token": stt.token}
                elif stt.engine_type == "basic":
                    creds = {
                        "username": stt.username,
                        "password": stt.password
                    }
                elif stt.engine_type == "key":
                    creds = {
                        "client_id": stt.client_id,
                        "client_key": stt.client_key
                    }
                elif stt.engine_type == "json":
                    creds = {
                        "json": stt.client_id,
                        "client_key": stt.client_key
                    }

                result["stt"] = {
                    "module": stt.name,
                    stt.name: {
                        "uri": stt.uri,
                        "lang": stt.lang,
                        "credential": creds
                    }
                }

                tts = device.config.tts
                result["tts"] = {
                    "module": tts.name,
                    tts.name: {
                        "token": tts.token,
                        "lang": tts.lang,
                        "voice": tts.voice,
                        "gender": tts.gender,
                        "uri": tts.uri
                    }
                }
                if tts.engine_type == "token":
                    result["tts"][tts.name].merge({"token": tts.token})
                elif tts.engine_type == "basic":
                    result["tts"][tts.name].merge({
                        "username": tts.username,
                        "password": tts.password
                    })
                elif tts.engine_type == "key":
                    result["tts"][tts.name].merge({
                        "client_id": tts.client_id,
                        "client_key": tts.client_key
                    })
                elif tts.engine_type == "api":
                    result["tts"][tts.name].merge({"api_key": tts.api_key})

                for c in cleans:
                    result.pop(c)

            else:
                result = {}
        return nice_json(result)