Repository: MycroftAI/selene-backend Branch: master Commit: e10ac91cde6b Files: 538 Total size: 1001.5 KB Directory structure: gitextract_zfonubvk/ ├── .editorconfig ├── .github/ │ ├── CONTRIBUTING.md │ ├── ISSUE_TEMPLATE.md │ ├── PULL_REQUEST_TEMPLATE.md │ └── SUPPORT.md ├── .gitignore ├── .pre-commit-config.yaml ├── AUTHORS ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── Jenkinsfile ├── LICENSE ├── README.md ├── api/ │ ├── account/ │ │ ├── account_api/ │ │ │ ├── __init__.py │ │ │ ├── api.py │ │ │ └── endpoints/ │ │ │ ├── __init__.py │ │ │ ├── change_email_address.py │ │ │ ├── change_password.py │ │ │ ├── city.py │ │ │ ├── country.py │ │ │ ├── defaults.py │ │ │ ├── device.py │ │ │ ├── device_count.py │ │ │ ├── geography.py │ │ │ ├── membership.py │ │ │ ├── pairing_code.py │ │ │ ├── preferences.py │ │ │ ├── region.py │ │ │ ├── skill_oauth.py │ │ │ ├── skill_settings.py │ │ │ ├── skills.py │ │ │ ├── software_update.py │ │ │ ├── ssh_key_validator.py │ │ │ ├── timezone.py │ │ │ ├── verify_email_address.py │ │ │ ├── voice_endpoint.py │ │ │ └── wake_word_endpoint.py │ │ ├── pyproject.toml │ │ ├── tests/ │ │ │ └── features/ │ │ │ ├── add_device.feature │ │ │ ├── agreements.feature │ │ │ ├── authentication.feature │ │ │ ├── environment.py │ │ │ ├── pantacor_update.feature │ │ │ ├── profile.feature │ │ │ ├── remove_account.feature │ │ │ └── steps/ │ │ │ ├── add_device.py │ │ │ ├── agreements.py │ │ │ ├── authentication.py │ │ │ ├── common.py │ │ │ ├── pantacor_update.py │ │ │ ├── profile.py │ │ │ └── remove_account.py │ │ └── uwsgi.ini │ ├── market/ │ │ ├── market_api/ │ │ │ ├── __init__.py │ │ │ ├── api.py │ │ │ └── endpoints/ │ │ │ ├── __init__.py │ │ │ ├── available_skills.py │ │ │ ├── skill_detail.py │ │ │ ├── skill_install.py │ │ │ └── skill_install_status.py │ │ ├── pyproject.toml │ │ ├── swagger.yaml │ │ └── uwsgi.ini │ ├── precise/ │ │ ├── precise_api/ │ │ │ ├── __init__.py │ │ │ ├── api.py │ │ │ └── endpoints/ │ │ │ ├── __init__.py │ │ │ ├── audio_file.py │ │ │ ├── designation.py │ │ │ └── tag.py │ │ ├── pyproject.toml │ │ └── uwsgi.ini │ ├── public/ │ │ ├── __init__.py │ │ ├── public_api/ │ │ │ ├── __init__.py │ │ │ ├── api.py │ │ │ └── endpoints/ │ │ │ ├── __init__.py │ │ │ ├── audio_transcription.py │ │ │ ├── device.py │ │ │ ├── device_activate.py │ │ │ ├── device_code.py │ │ │ ├── device_email.py │ │ │ ├── device_location.py │ │ │ ├── device_metrics.py │ │ │ ├── device_oauth.py │ │ │ ├── device_pantacor.py │ │ │ ├── device_refresh_token.py │ │ │ ├── device_setting.py │ │ │ ├── device_skill.py │ │ │ ├── device_skill_manifest.py │ │ │ ├── device_skill_settings.py │ │ │ ├── device_subscription.py │ │ │ ├── geolocation.py │ │ │ ├── google_stt.py │ │ │ ├── oauth_callback.py │ │ │ ├── open_weather_map.py │ │ │ ├── premium_voice.py │ │ │ ├── stripe_webhook.py │ │ │ ├── wake_word_file.py │ │ │ ├── wolfram_alpha.py │ │ │ ├── wolfram_alpha_simple.py │ │ │ ├── wolfram_alpha_spoken.py │ │ │ └── wolfram_alpha_v2.py │ │ ├── pyproject.toml │ │ ├── tests/ │ │ │ └── features/ │ │ │ ├── device_email.feature │ │ │ ├── device_location.feature │ │ │ ├── device_metrics.feature │ │ │ ├── device_pairing.feature │ │ │ ├── device_refresh_token.feature │ │ │ ├── device_skill_manifest.feature │ │ │ ├── device_skill_settings.feature │ │ │ ├── device_subscription.feature │ │ │ ├── environment.py │ │ │ ├── get_device.feature │ │ │ ├── get_device_settings.feature │ │ │ ├── steps/ │ │ │ │ ├── common.py │ │ │ │ ├── device_email.py │ │ │ │ ├── device_location.py │ │ │ │ ├── device_metrics.py │ │ │ │ ├── device_pairing.py │ │ │ │ ├── device_refresh_token.py │ │ │ │ ├── device_skill_manifest.py │ │ │ │ ├── device_skill_settings.py │ │ │ │ ├── get_device.py │ │ │ │ ├── get_device_settings.py │ │ │ │ ├── get_device_subscription.py │ │ │ │ ├── resources/ │ │ │ │ │ └── test_stt.flac │ │ │ │ ├── transcribe_audio.py │ │ │ │ ├── wake_word_file.py │ │ │ │ └── wolfram_alpha.py │ │ │ ├── transcribe_audio.feature │ │ │ ├── wake_word_file_upload.feature │ │ │ └── wolfram_alpha.feature │ │ └── uwsgi.ini │ └── sso/ │ ├── Dockerfile │ ├── pyproject.toml │ ├── sso_api/ │ │ ├── __init__.py │ │ ├── api.py │ │ └── endpoints/ │ │ ├── __init__.py │ │ ├── authenticate_internal.py │ │ ├── github_token.py │ │ ├── logout.py │ │ ├── password_change.py │ │ ├── password_reset.py │ │ ├── validate_federated.py │ │ └── validate_token.py │ ├── tests/ │ │ └── features/ │ │ ├── add_account.feature │ │ ├── agreements.feature │ │ ├── environment.py │ │ ├── federated_login.feature │ │ ├── internal_login.feature │ │ ├── logout.feature │ │ ├── password_change.feature │ │ └── steps/ │ │ ├── add_account.py │ │ ├── agreements.py │ │ ├── common.py │ │ ├── login.py │ │ ├── logout.py │ │ └── password_change.py │ └── uwsgi.ini ├── batch/ │ ├── job_scheduler/ │ │ ├── __init__.py │ │ └── jobs.py │ ├── pyproject.toml │ └── script/ │ ├── __init__.py │ ├── daily_report.py │ ├── delete_wake_word_files.py │ ├── designate_wake_word_files.py │ ├── load_skill_display_data.py │ ├── move_wake_word_files.py │ ├── parse_core_metrics.py │ ├── partition_api_metrics.py │ ├── test_scheduler.py │ └── update_device_last_contact.py ├── db/ │ ├── mycroft/ │ │ ├── account_schema/ │ │ │ ├── create_schema.sql │ │ │ ├── data/ │ │ │ │ └── membership.sql │ │ │ ├── grants.sql │ │ │ └── tables/ │ │ │ ├── account.sql │ │ │ ├── account_agreement.sql │ │ │ ├── account_membership.sql │ │ │ ├── agreement.sql │ │ │ └── membership.sql │ │ ├── create_extensions.sql │ │ ├── create_mycroft_db.sql │ │ ├── create_roles.sql │ │ ├── create_template_db.sql │ │ ├── device_schema/ │ │ │ ├── create_schema.sql │ │ │ ├── data/ │ │ │ │ └── text_to_speech.sql │ │ │ ├── get_device_defaults_for_city.sql │ │ │ ├── get_device_geographies_for_city.sql │ │ │ ├── grants.sql │ │ │ └── tables/ │ │ │ ├── account_defaults.sql │ │ │ ├── account_preferences.sql │ │ │ ├── category.sql │ │ │ ├── device.sql │ │ │ ├── device_skill.sql │ │ │ ├── geography.sql │ │ │ ├── pantacor_config.sql │ │ │ ├── skill_setting.sql │ │ │ ├── text_to_speech.sql │ │ │ ├── wake_word.sql │ │ │ └── wake_word_settings.sql │ │ ├── drop_extensions.sql │ │ ├── drop_mycroft_db.sql │ │ ├── drop_roles.sql │ │ ├── drop_template_db.sql │ │ ├── geography_schema/ │ │ │ ├── create_schema.sql │ │ │ ├── delete_duplicate_cities.sql │ │ │ ├── get_duplicated_cities.sql │ │ │ ├── grants.sql │ │ │ └── tables/ │ │ │ ├── city.sql │ │ │ ├── country.sql │ │ │ ├── region.sql │ │ │ └── timezone.sql │ │ ├── metric_schema/ │ │ │ ├── create_schema.sql │ │ │ ├── grants.sql │ │ │ └── tables/ │ │ │ ├── account_activity.sql │ │ │ ├── api.sql │ │ │ ├── api_history.sql │ │ │ ├── core.sql │ │ │ ├── core_interaction.sql │ │ │ ├── job.sql │ │ │ ├── stt_engine.sql │ │ │ └── stt_transcription.sql │ │ ├── skill_schema/ │ │ │ ├── create_schema.sql │ │ │ ├── grants.sql │ │ │ └── tables/ │ │ │ ├── display.sql │ │ │ ├── oauth_credential.sql │ │ │ ├── oauth_token.sql │ │ │ ├── settings_display.sql │ │ │ └── skill.sql │ │ ├── tagging_schema/ │ │ │ ├── create_schema.sql │ │ │ ├── grants.sql │ │ │ └── tables/ │ │ │ ├── file_location.sql │ │ │ ├── session.sql │ │ │ ├── tag.sql │ │ │ ├── tag_value.sql │ │ │ ├── tagger.sql │ │ │ ├── wake_word_file.sql │ │ │ ├── wake_word_file_designation.sql │ │ │ └── wake_word_file_tag.sql │ │ ├── types/ │ │ │ ├── agreement_enum.sql │ │ │ ├── cateogory_enum.sql │ │ │ ├── core_version_enum.sql │ │ │ ├── date_format_enum.sql │ │ │ ├── measurement_system_enum.sql │ │ │ ├── membership_type_enum.sql │ │ │ ├── payment_method_enum.sql │ │ │ ├── tagger_type_enum.sql │ │ │ ├── tagging_file_origin_enum.sql │ │ │ ├── tagging_file_status_enum.sql │ │ │ ├── time_format_enum.sql │ │ │ └── tts_engine_enum.sql │ │ ├── versions/ │ │ │ └── 2020.9.1.sql │ │ └── wake_word_schema/ │ │ ├── create_schema.sql │ │ ├── grants.sql │ │ └── tables/ │ │ ├── pocketsphinx_settings.sql │ │ └── wake_word.sql │ ├── pyproject.toml │ └── scripts/ │ ├── __init__.py │ ├── bootstrap_mycroft_db.py │ ├── neo4j-postgres.py │ ├── queries.cypher │ └── remove_duplicate_cities.py └── shared/ ├── Dockerfile ├── MANIFEST.in ├── pyproject.toml ├── selene/ │ ├── __init__.py │ ├── api/ │ │ ├── __init__.py │ │ ├── base_config.py │ │ ├── base_endpoint.py │ │ ├── blueprint.py │ │ ├── endpoints/ │ │ │ ├── __init__.py │ │ │ ├── account.py │ │ │ ├── agreements.py │ │ │ ├── password_change.py │ │ │ └── validate_email.py │ │ ├── etag.py │ │ ├── pantacor.py │ │ ├── public_endpoint.py │ │ └── response.py │ ├── batch/ │ │ ├── __init__.py │ │ └── base.py │ ├── data/ │ │ ├── __init__.py │ │ ├── account/ │ │ │ ├── __init__.py │ │ │ ├── entity/ │ │ │ │ ├── __init__.py │ │ │ │ ├── account.py │ │ │ │ ├── agreement.py │ │ │ │ ├── membership.py │ │ │ │ └── skill.py │ │ │ └── repository/ │ │ │ ├── __init__.py │ │ │ ├── account.py │ │ │ ├── agreement.py │ │ │ ├── membership.py │ │ │ ├── skill.py │ │ │ └── sql/ │ │ │ ├── add_account.sql │ │ │ ├── add_account_agreement.sql │ │ │ ├── add_account_membership.sql │ │ │ ├── add_agreement.sql │ │ │ ├── add_membership.sql │ │ │ ├── change_email_address.sql │ │ │ ├── change_password.sql │ │ │ ├── daily_report.sql │ │ │ ├── delete_agreement.sql │ │ │ ├── delete_membership.sql │ │ │ ├── end_membership.sql │ │ │ ├── expire_account_agreement.sql │ │ │ ├── expire_agreement.sql │ │ │ ├── get_account.sql │ │ │ ├── get_account_by_device_id.sql │ │ │ ├── get_account_skills.sql │ │ │ ├── get_active_membership_by_account_id.sql │ │ │ ├── get_active_membership_by_payment_account_id.sql │ │ │ ├── get_agreement_content_id.sql │ │ │ ├── get_current_agreements.sql │ │ │ ├── get_membership_by_type.sql │ │ │ ├── get_membership_types.sql │ │ │ ├── remove_account.sql │ │ │ ├── update_last_activity_ts.sql │ │ │ └── update_username.sql │ │ ├── device/ │ │ │ ├── __init__.py │ │ │ ├── entity/ │ │ │ │ ├── __init__.py │ │ │ │ ├── default.py │ │ │ │ ├── device.py │ │ │ │ ├── device_skill.py │ │ │ │ ├── geography.py │ │ │ │ ├── preference.py │ │ │ │ └── text_to_speech.py │ │ │ └── repository/ │ │ │ ├── __init__.py │ │ │ ├── default.py │ │ │ ├── device.py │ │ │ ├── device_skill.py │ │ │ ├── geography.py │ │ │ ├── preference.py │ │ │ ├── setting.py │ │ │ ├── sql/ │ │ │ │ ├── add_device.sql │ │ │ │ ├── add_geography.sql │ │ │ │ ├── add_manifest_skill.sql │ │ │ │ ├── add_text_to_speech.sql │ │ │ │ ├── delete_device_skill.sql │ │ │ │ ├── get_account_defaults.sql │ │ │ │ ├── get_account_device_count.sql │ │ │ │ ├── get_account_geographies.sql │ │ │ │ ├── get_account_preferences.sql │ │ │ │ ├── get_all_device_ids.sql │ │ │ │ ├── get_device_by_id.sql │ │ │ │ ├── get_device_settings_by_device_id.sql │ │ │ │ ├── get_device_skill_manifest.sql │ │ │ │ ├── get_devices_by_account_id.sql │ │ │ │ ├── get_location_by_device_id.sql │ │ │ │ ├── get_open_dataset_agreement_by_device_id.sql │ │ │ │ ├── get_settings_display_usage.sql │ │ │ │ ├── get_skill_manifest_for_account.sql │ │ │ │ ├── get_skill_settings_for_account.sql │ │ │ │ ├── get_skill_settings_for_device.sql │ │ │ │ ├── get_voices.sql │ │ │ │ ├── remove_device.sql │ │ │ │ ├── remove_manifest_skill.sql │ │ │ │ ├── remove_text_to_speech.sql │ │ │ │ ├── update_device_from_account.sql │ │ │ │ ├── update_device_from_core.sql │ │ │ │ ├── update_device_skill_settings.sql │ │ │ │ ├── update_last_contact_ts.sql │ │ │ │ ├── update_pantacor_config.sql │ │ │ │ ├── update_skill_manifest.sql │ │ │ │ ├── update_skill_settings.sql │ │ │ │ ├── upsert_defaults.sql │ │ │ │ ├── upsert_device_skill_settings.sql │ │ │ │ ├── upsert_pantacor_config.sql │ │ │ │ └── upsert_preferences.sql │ │ │ └── text_to_speech.py │ │ ├── geography/ │ │ │ ├── __init__.py │ │ │ ├── entity/ │ │ │ │ ├── __init__.py │ │ │ │ ├── city.py │ │ │ │ ├── country.py │ │ │ │ ├── region.py │ │ │ │ └── timezone.py │ │ │ └── repository/ │ │ │ ├── __init__.py │ │ │ ├── city.py │ │ │ ├── country.py │ │ │ ├── region.py │ │ │ ├── sql/ │ │ │ │ ├── get_biggest_city_in_country.sql │ │ │ │ ├── get_biggest_city_in_region.sql │ │ │ │ ├── get_cities_by_region.sql │ │ │ │ ├── get_countries.sql │ │ │ │ ├── get_geographic_location_by_city.sql │ │ │ │ ├── get_regions_by_country.sql │ │ │ │ └── get_timezones_by_country.sql │ │ │ └── timezone.py │ │ ├── metric/ │ │ │ ├── __init__.py │ │ │ ├── entity/ │ │ │ │ ├── __init__.py │ │ │ │ ├── account_activity.py │ │ │ │ ├── api.py │ │ │ │ ├── core.py │ │ │ │ ├── job.py │ │ │ │ └── stt.py │ │ │ └── repository/ │ │ │ ├── __init__.py │ │ │ ├── account_activity.py │ │ │ ├── api.py │ │ │ ├── core.py │ │ │ ├── job.py │ │ │ ├── sql/ │ │ │ │ ├── add_account_activity.sql │ │ │ │ ├── add_api_metric.sql │ │ │ │ ├── add_core_interaction.sql │ │ │ │ ├── add_core_metric.sql │ │ │ │ ├── add_job_metric.sql │ │ │ │ ├── add_tts_transcription_metric.sql │ │ │ │ ├── create_api_metric_partition.sql │ │ │ │ ├── create_api_metric_partition_index.sql │ │ │ │ ├── delete_account_activity_date.sql │ │ │ │ ├── delete_api_metrics_by_date.sql │ │ │ │ ├── delete_stt_transcription_by_date.sql │ │ │ │ ├── get_account_activity_by_date.sql │ │ │ │ ├── get_api_metrics_for_date.sql │ │ │ │ ├── get_core_metric_by_device.sql │ │ │ │ ├── get_core_timing_metrics_by_date.sql │ │ │ │ ├── get_tts_transcription_by_account.sql │ │ │ │ ├── increment_accounts_added.sql │ │ │ │ ├── increment_accounts_deleted.sql │ │ │ │ ├── increment_activity.sql │ │ │ │ ├── increment_members_added.sql │ │ │ │ ├── increment_members_expired.sql │ │ │ │ ├── increment_open_dataset_added.sql │ │ │ │ └── increment_open_dataset_deleted.sql │ │ │ └── stt.py │ │ ├── repository_base.py │ │ ├── skill/ │ │ │ ├── __init__.py │ │ │ ├── entity/ │ │ │ │ ├── __init__.py │ │ │ │ ├── display.py │ │ │ │ ├── skill.py │ │ │ │ └── skill_setting.py │ │ │ └── repository/ │ │ │ ├── __init__.py │ │ │ ├── display.py │ │ │ ├── setting.py │ │ │ ├── settings_display.py │ │ │ ├── skill.py │ │ │ └── sql/ │ │ │ ├── add_device_skill.sql │ │ │ ├── add_settings_display.sql │ │ │ ├── add_skill.sql │ │ │ ├── delete_device_skill.sql │ │ │ ├── delete_settings_display.sql │ │ │ ├── get_display_data_for_skill.sql │ │ │ ├── get_display_data_for_skills.sql │ │ │ ├── get_settings_definition_by_gid.sql │ │ │ ├── get_settings_display_id.sql │ │ │ ├── get_settings_for_skill_family.sql │ │ │ ├── get_skill_by_global_id.sql │ │ │ ├── get_skill_setting_by_device.sql │ │ │ ├── get_skills_for_account.sql │ │ │ ├── remove_skill_by_gid.sql │ │ │ ├── update_device_skill_settings.sql │ │ │ └── upsert_skill_display_data.sql │ │ ├── tagging/ │ │ │ ├── __init__.py │ │ │ ├── entity/ │ │ │ │ ├── __init__.py │ │ │ │ ├── file_designation.py │ │ │ │ ├── file_location.py │ │ │ │ ├── file_tag.py │ │ │ │ ├── tag.py │ │ │ │ ├── tag_value.py │ │ │ │ ├── tagger.py │ │ │ │ └── wake_word_file.py │ │ │ └── repository/ │ │ │ ├── __init__.py │ │ │ ├── file_designation.py │ │ │ ├── file_location.py │ │ │ ├── file_tag.py │ │ │ ├── session.py │ │ │ ├── sql/ │ │ │ │ ├── add_file_location.sql │ │ │ │ ├── add_session.sql │ │ │ │ ├── add_tagger.sql │ │ │ │ ├── add_tagging_session.sql │ │ │ │ ├── add_wake_word_file.sql │ │ │ │ ├── add_wake_word_file_designation.sql │ │ │ │ ├── add_wake_word_file_tag.sql │ │ │ │ ├── change_account_file_status.sql │ │ │ │ ├── change_file_location.sql │ │ │ │ ├── change_file_status.sql │ │ │ │ ├── get_active_session.sql │ │ │ │ ├── get_designation_candidates.sql │ │ │ │ ├── get_designations_from_date.sql │ │ │ │ ├── get_file_location_id.sql │ │ │ │ ├── get_taggable_wake_word_file.sql │ │ │ │ ├── get_tagger_by_entity.sql │ │ │ │ ├── get_tags.sql │ │ │ │ ├── get_wake_word_files.sql │ │ │ │ ├── remove_file_location.sql │ │ │ │ ├── remove_wake_word_file.sql │ │ │ │ └── update_session_end_ts.sql │ │ │ ├── tag.py │ │ │ ├── tagger.py │ │ │ └── wake_word_file.py │ │ └── wake_word/ │ │ ├── __init__.py │ │ ├── entity/ │ │ │ ├── __init__.py │ │ │ ├── pocketsphinx_settings.py │ │ │ └── wake_word.py │ │ └── repository/ │ │ ├── __init__.py │ │ ├── sql/ │ │ │ ├── add_wake_word.sql │ │ │ ├── get_wake_word_id.sql │ │ │ ├── get_wake_words_for_web.sql │ │ │ └── remove_wake_word.sql │ │ └── wake_word.py │ ├── testing/ │ │ ├── __init__.py │ │ ├── account.py │ │ ├── account_activity.py │ │ ├── account_geography.py │ │ ├── account_preference.py │ │ ├── agreement.py │ │ ├── api.py │ │ ├── device.py │ │ ├── device_skill.py │ │ ├── membership.py │ │ ├── skill.py │ │ ├── tagging.py │ │ ├── test_db.py │ │ ├── text_to_speech.py │ │ └── wake_word.py │ └── util/ │ ├── __init__.py │ ├── auth.py │ ├── cache.py │ ├── db/ │ │ ├── __init__.py │ │ ├── connection.py │ │ ├── connection_pool.py │ │ ├── cursor.py │ │ └── transaction.py │ ├── email/ │ │ ├── __init__.py │ │ ├── email.py │ │ └── templates/ │ │ ├── account_not_found.html │ │ ├── base.html │ │ ├── email_change.html │ │ ├── email_verification.html │ │ ├── metrics.html │ │ ├── password_change.html │ │ └── reset_password.html │ ├── exceptions.py │ ├── github.py │ ├── log.py │ ├── payment/ │ │ ├── __init__.py │ │ └── stripe.py │ └── ssh/ │ ├── __init__.py │ ├── sftp.py │ └── ssh.py └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # top-most EditorConfig file root = true # Unix-style newlines with a newline ending every file [*] end_of_line = lf insert_final_newline = true # Matches multiple files with brace expansion notation # Set default charset [*.{py}] charset = utf-8 # 4 space indentation [*.py] indent_style = space indent_size = 4 trim_trailing_whitespace = true ================================================ FILE: .github/CONTRIBUTING.md ================================================ # How to contribute So you want to contribute to Mycroft? This should be as easy as possible for you but there are a few things to consider when contributing. The following guidelines for contribution should be followed if you want to submit a pull request. ## How to prepare * You need a [GitHub account](https://github.com/signup/free) * Submit an [issue ticket](https://github.com/MycroftAI/mycroft/issues) for your issue if there is not one yet. * Describe the issue and include steps to reproduce if it's a bug. * Ensure to mention the earliest version that you know is affected. * If you are able and want to fix this, fork the repository on GitHub ## Make Changes 1. [Fork the Project](https://help.github.com/articles/fork-a-repo/) 2. [Create a new Issue](https://help.github.com/articles/creating-an-issue/) 3. Create a **feature** or **bugfix** branch based on **dev** with your issue identifier. For example, if your issue identifier is: **issue-123** then you will create either: **feature/issue-123** or **bugfix/issue-123**. Use **feature** prefix for issues related to new functionalities or enhancements and **bugfix** in case of bugs found on the **dev** branch 4. Make sure you stick to the coding style and OO patterns that are used already. 5. Document code using [Google-style docstrings](http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html). Our automated documentation tools expect that format. All functions and class methods that are expected to be called externally should include a docstring. (And those that aren't [should be prefixed with a single underscore](https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references)). 6. Make commits in logical units and describe them properly. Use your issue identifier at the very begin of each commit. For instance: `git commit -m "Issues-123 - Fixing 'A' sound on Spelling Skill"` 7. Before committing, format your code following the PEP8 rules and organize your imports removing unused libs. To check whether you are following these rules, install pep8 and run `pep8 mycroft test` while in the `mycroft-core` folder. This will check for formatting issues in the `mycroft` and `test` folders. 8. Once you have committed everything and are done with your branch, you have to rebase your code with **dev**. Do the following steps: 1. Make sure you do not have any changes left on your branch 2. Checkout on dev branch and make sure it is up-to-date 3. Checkout your branch and rebase it with dev 4. Resolve any conflicts you have 5. You will have to force your push since the historical base has changed 6. Suggested steps are: ``` git checkout dev git fetch git reset --hard origin/dev git checkout git rebase dev git push -f ``` 9. If possible, create unit tests for your changes * [Unit Tests for most contributions](https://github.com/MycroftAI/mycroft-core/tree/dev/test) * [Intent Tests for new skills](https://docs.mycroft.ai/development/creating-a-skill#testing-your-skill) * We utilize TRAVIS-CI, which will test each pull request. To test locally you can run: `./start.sh unittest` 10. Once everything is OK, you can finally [create a Pull Request (PR) on Github](https://help.github.com/articles/using-pull-requests/) in order to be reviewed and merged. **Note**: Even if you have write access to the master branch, do not work directly on master! ## Submit Changes * Push your changes to a topic branch in your fork of the repository. * Open a pull request to the original repository and choose the right original branch you want to patch. _Advanced users may install the `hub` gem and use the [`hub pull-request` command](https://github.com/defunkt/hub#git-pull-request)._ * If not done in commit messages (which you really should do) please reference and update your issue with the code changes. But _please do not close the issue yourself_. * Even if you have write access to the repository, do not directly push or merge pull-requests. Let another team member review your pull request and approve. # Additional Resources * [General GitHub documentation](http://help.github.com/) * [GitHub pull request documentation](https://help.github.com/articles/about-pull-requests/) * [Read the Issue Guidelines by @necolas](https://github.com/necolas/issue-guidelines/blob/master/CONTRIBUTING.md) for more details ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ # How to submit an Issue to a Mycroft repository When submitting an Issue to a Mycroft repository, please follow these guidelines to help us help you. ## Be clear about the software, hardware and version you are running For example: * I'm running a Mark 1 * With version 0.9.10 of the Mycroft software * With the standard Wake Word ## Try to provide steps that we can use to replicate the Issue For example: 1. Burn the 0.9.10 image to Micro SD card using Etcher 2. Seat the Micro SD card in the RPi 3 3. Boot Picroft 4. Wait 3 minutes 5. The red light will come on indicating that the RPi 3 is overheating 6. Running `htop` via the command line indicates a number of Zombie'd processes ## Be as specific as possible about the expected condition, and the deviation from expected condition. This is called _object-deviation format_. Specify the object, then the deviation of the object from an expected condition. Example 1: * When I say "Hey Mycroft, set your eyes to cadet blue", the eyes turn purple instead of blue. Example 2: * When I say "Hey Mycroft, what time is it in Paris", the time spoken is out by one hour - it's not observing daylight savings time. Example 3: * When I run `msm default` on my Mark 1, I receive lots of Git 'locked file' errors on the command line. ## Provide log files or other output to help us see the error We will normally require log files or other troubleshooting information to assist you with your Issue. This [documentation](https://mycroft.ai/documentation/troubleshooting/) explains how to find log files. As of version 0.9.10, the [Support Skill](https://github.com/MycroftAI/skill-support) also helps to automate gathering support information. Simply say: * "Create a support ticket" _or_ * "You're not working!" _or_ * "Send me debug info" and the Skill will put together a support package which you can email to us. ## Upload any files to the Issue that will be useful in helping us to investigate Please ensure you upload any relevant files - such as screenshots - which will aid us investigating. ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ ## Description (Description of what the PR does, such as fixes # {issue number}) ## How to test (Description of how to validate or test this PR) ## Contributor license agreement signed? CLA [ ] (Whether you have signed a [CLA - Contributor Licensing Agreement](https://mycroft.ai/cla/) ================================================ FILE: .github/SUPPORT.md ================================================ # How to get support with Mycroft software, hardware and products There are multiple ways to seek support with Mycroft software, hardware and products. ## Forum We maintain a [Forum](https://community.mycroft.ai) which is regularly monitored. Feel free to post questions, bugs, and requests for assistance in the relevant Forum Topic. ## Chat Mycroft staff are regularly available in our [Chat](https://chat.mycroft.ai) platform. There are specific rooms available for different projects and products. ## Contact You can contact us via [our online form](https://mycroft.ai/contact), or give a call. ## GitHub We welcome you raising Issues and Pull Requests on our public GitHub repositories. See the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information. ## Helping us to help you Our [documentation](https://mycroft.ai/documentation/troubleshooting/) contains troubleshooting information, and information on log files and other files that we may need to help us help you. ================================================ FILE: .gitignore ================================================ # See http://help.github.com/ignore-files/ for more about ignoring files. # compiled output /dist /tmp /out-tsc **/*.egg-info # dependencies **/node_modules # python notebooks *.ipynb # IDEs and editors **/.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace __pycache__/ # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json # misc /.sass-cache /connect.lock /coverage /libpeerconnection.log npm-debug.log yarn-error.log testem.log /typings # System Files .DS_Store Thumbs.db ================================================ FILE: .pre-commit-config.yaml ================================================ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black rev: 22.3.0 hooks: - id: black ================================================ FILE: AUTHORS ================================================ The Mycroft Server was initially developed by Mycroft AI Inc It lives on as an open source project with many contributors, a self-updating list is at: https://github.com/mycroftai/selene-backend/graphs/contributors ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at kathy.reid@mycroft.ai. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: Dockerfile ================================================ # Multi-stage Dockerfile for running Selene APIs or their test suites. # # ASSUMPTION: # This Dockerfile assumes its resulting containers will run on a Docker network. A Postgres container named # "selene-db" and a Redis container named "selene-cache" also need to be running on this network. To create the # network and the Postgres/Redis containers, use the following commands: # docker network create --driver bridge # docker run -d --net --name selene-cache redis:6 # docker run -d -e POSTGRES_PASSWORD=selene --net --name selene-db postgres:10 # The DB_HOST environment variable is set to the name of the Postgres container and the REDIS_HOST environment # variable is set to the name of he Redis container. When running images created from this Dockerfile, include the # "--net " argument. # Build steps that apply to all of the selene applications. FROM python:3.9 as base-build RUN apt-get update && apt-get -y install gcc git libsndfile-dev RUN curl -sSL https://install.python-poetry.org | python3 - ENV PATH ${PATH}:/root/.local/bin RUN poetry --version RUN mkdir -p /root/allure /opt/selene/selene-backend /root/code-quality /var/log/mycroft WORKDIR /opt/selene/selene-backend ENV DB_HOST selene-db ENV DB_NAME mycroft ENV DB_PASSWORD adam ENV DB_USER selene ENV JWT_ACCESS_SECRET access-secret ENV JWT_REFRESH_SECRET refresh-secret ENV REDIS_HOST selene-cache ENV REDIS_PORT 6379 ENV SALT testsalt ENV SELENE_ENVIRONMENT dev # Put the copy of the shared library code in its own section to avoid reinstalling base software every time FROM base-build as selene-base COPY shared shared # Code quality scripts and user agreements are stored in the MycroftAI/devops repository. This repository is private. # builds for publicly available images should not use this build stage. # # The GitHub API key is sensitive information and can change depending on who is running the application. # It is used here to clone the private MycroftAI/devops repository. FROM selene-base as devops-build ARG github_api_key ENV GITHUB_API_KEY=$github_api_key RUN mkdir -p /opt/mycroft WORKDIR /opt/mycroft RUN git clone https://${github_api_key}@github.com/MycroftAI/devops.git WORKDIR /opt/mycroft/devops/jenkins RUN poetry install # Run a linter and code formatter against the API specified in the build argument FROM devops-build as api-code-check ARG api_name WORKDIR /opt/selene/selene-backend COPY api/${api_name} api/${api_name} WORKDIR /opt/selene/selene-backend/api/${api_name} RUN poetry install ENV PYTHONPATH=$PYTHONPATH:/opt/selene/selene-backend/api/${api_name} WORKDIR /opt/mycroft/devops/jenkins ENTRYPOINT ["poetry", "run", "python", "-m", "pipeline.code_check", "--repository", "selene-backend", "--base-dir", "/opt/selene"] # Bootstrap the Selene database as it will be needed to run any Selene applications. FROM devops-build as db-bootstrap ENV POSTGRES_PASSWORD selene WORKDIR /opt/selene/selene-backend COPY db db WORKDIR /opt/selene/selene-backend/db RUN poetry install RUN mkdir -p /tmp/selene ENTRYPOINT ["poetry", "run", "python", "scripts/bootstrap_mycroft_db.py", "--ci"] # Run the tests defined in the Account API FROM selene-base as account-api-test ARG stripe_api_key ENV ACCOUNT_BASE_URL https://account.mycroft.test ENV PANTACOR_API_TOKEN pantacor-token ENV PANTACOR_API_BASE_URL pantacor.test.url ENV PYTHONPATH=$PYTHONPATH:/opt/selene/selene-backend/api/account ENV STRIPE_PRIVATE_KEY $stripe_api_key COPY api/account api/account WORKDIR /opt/selene/selene-backend/api/account RUN poetry install WORKDIR /opt/selene/selene-backend/api/account/tests ENTRYPOINT ["poetry", "run", "behave", "-f", "allure_behave.formatter:AllureFormatter", "-o", "/root/allure/allure-result"] # Run the tests defined in the Single Sign On API FROM selene-base as sso-api-test ARG github_client_id ARG github_client_secret ENV PYTHONPATH=$PYTHONPATH:/opt/selene/selene-backend/api/sso ENV JWT_RESET_SECRET reset-secret # The GitHub client ID and secret are sensitive information and can change depending on who is running the application. # They are used here to facilitate user authentication using a GitHub account. ENV GITHUB_CLIENT_ID $github_client_id ENV GITHUB_CLIENT_SECRET $github_client_secret COPY api/sso api/sso WORKDIR /opt/selene/selene-backend/api/sso RUN poetry install WORKDIR /opt/selene/selene-backend/api/sso/tests ENTRYPOINT ["poetry", "run", "behave", "-f", "allure_behave.formatter:AllureFormatter", "-o", "/root/allure/allure-result"] # Run the tests defined in the Public Device API FROM selene-base as public-api-test RUN mkdir -p /opt/selene/data ARG google_stt_key ARG stt_api_key ARG wolfram_alpha_key ENV GOOGLE_APPLICATION_CREDENTIALS="/root/secrets/transcription-test-363101-6532632520e1.json" ENV GOOGLE_STT_KEY $google_stt_key ENV PANTACOR_API_TOKEN pantacor-token ENV PANTACOR_API_BASE_URL pantacor.test.url ENV PYTHONPATH=$PYTHONPATH:/opt/selene/selene-backend/api/public ENV GOOGLE_STT_KEY $google_stt_key ENV SENDGRID_API_KEY test_sendgrid_key ENV WOLFRAM_ALPHA_KEY $wolfram_alpha_key ENV WOLFRAM_ALPHA_URL https://api.wolframalpha.com COPY api/public api/public WORKDIR /opt/selene/selene-backend/api/public RUN poetry install WORKDIR /opt/selene/selene-backend/api/public/tests ENTRYPOINT ["poetry", "run", "behave", "-f", "allure_behave.formatter:AllureFormatter", "-o", "/root/allure/allure-result"] ================================================ FILE: Jenkinsfile ================================================ pipeline { agent any options { // Running builds concurrently could cause a race condition with // building the Docker image. disableConcurrentBuilds() buildDiscarder(logRotator(numToKeepStr: '5')) ansiColor('xterm') } environment { // Some branches have a "/" in their name (e.g. feature/new-and-cool) // Some commands, such as those that deal with directories, don't // play nice with this naming convention. Define an alias for the // branch name that can be used in these scenarios. BRANCH_ALIAS = sh( script: 'echo $BRANCH_NAME | sed -e "s#/#-#g"', returnStdout: true ).trim() DOCKER_BUILDKIT=1 //spawns GITHUB_USR and GITHUB_PSW environment variables GITHUB_API_KEY=credentials('38b2e4a6-167a-40b2-be6f-d69be42c8190') GITHUB_CLIENT_ID=credentials('380f58b1-8a33-4a9d-a67b-354a9b0e792e') GITHUB_CLIENT_SECRET=credentials('71626c21-de59-4450-bfad-5034fd596fb2') GOOGLE_STT_KEY=credentials('287949f8-2ada-4450-8806-1fe2dd8e4c4d') STRIPE_KEY=credentials('9980e41f-d418-49af-9d62-341d1246f555') WOLFRAM_ALPHA_KEY=credentials('f718e0a1-c19c-4c7f-af88-0689738ccaa1') } stages { stage('Lint & Format') { // Run PyLint and Black to check code quality. when { anyOf { changeRequest target: 'dev' changeRequest target: 'master' } } steps { labelledShell label: 'Account API Setup', script: """ docker build \ --build-arg github_api_key=${GITHUB_API_KEY} \ --build-arg api_name=account \ --target api-code-check --no-cache \ -t selene-linter:${BRANCH_ALIAS} . """ labelledShell label: 'Account API Check', script: """ docker run selene-linter:${BRANCH_ALIAS} --poetry-dir api/account --pull-request=${BRANCH_NAME} """ labelledShell label: 'Single Sign On API Setup', script: """ docker build \ --build-arg github_api_key=${GITHUB_API_KEY} \ --build-arg api_name=sso \ --target api-code-check --no-cache \ -t selene-linter:${BRANCH_ALIAS} . """ labelledShell label: 'Single Sign On API Check', script: """ docker run selene-linter:${BRANCH_ALIAS} --poetry-dir api/sso --pull-request=${BRANCH_NAME} """ labelledShell label: 'Public API Setup', script: """ docker build \ --build-arg github_api_key=${GITHUB_API_KEY} \ --build-arg api_name=public \ --target api-code-check --no-cache \ --label job=${JOB_NAME} \ -t selene-linter:${BRANCH_ALIAS} . """ labelledShell label: 'Public API Check', script: """ docker run selene-linter:${BRANCH_ALIAS} --poetry-dir api/public --pull-request=${BRANCH_NAME} """ } } stage('Bootstrap DB') { when { anyOf { branch 'dev' branch 'master' changeRequest target: 'dev' changeRequest target: 'master' } } steps { labelledShell label: 'Building Docker image', script: """ docker build \ --target db-bootstrap \ --build-arg github_api_key=${GITHUB_API_KEY} \ --label job=${JOB_NAME} \ -t selene-db:${BRANCH_ALIAS} . """ timeout(time: 5, unit: 'MINUTES') { labelledShell label: 'Run database bootstrap script', script: """ docker run \ -v '${HOME}/selene:/tmp/selene' \ --net selene-net selene-db:${BRANCH_ALIAS} """ } } } stage('Account API Tests') { when { anyOf { branch 'dev' branch 'master' changeRequest target: 'dev' changeRequest target: 'master' } } steps { labelledShell label: 'Building Docker image', script: """ docker build \ --build-arg stripe_api_key=${STRIPE_KEY} \ --target account-api-test \ --label job=${JOB_NAME} \ -t selene-account:${BRANCH_ALIAS} . """ timeout(time: 5, unit: 'MINUTES') { sh 'mkdir -p $HOME/selene/$BRANCH_ALIAS/allure' labelledShell label: 'Running behave tests', script: """ docker run \ --net selene-net \ -v '$HOME/selene/$BRANCH_ALIAS/allure/:/root/allure' \ --label job=${JOB_NAME} \ selene-account:${BRANCH_ALIAS} """ } } post { always { sh 'docker run \ -v "$HOME/selene/$BRANCH_ALIAS/allure:/root/allure" \ --entrypoint=/bin/bash \ --label build=${JOB_NAME} \ selene-account:${BRANCH_ALIAS} \ -x -c "chown $(id -u $USER):$(id -g $USER) \ -R /root/allure/"' } } } stage('Single Sign On API Tests') { when { anyOf { branch 'dev' branch 'master' changeRequest target: 'dev' changeRequest target: 'master' } } steps { labelledShell label: 'Building Docker image', script: """ docker build \ --build-arg github_client_id=${GITHUB_CLIENT_ID} \ --build-arg github_client_secret=${GITHUB_CLIENT_SECRET} \ --target sso-api-test \ --label job=${JOB_NAME} \ -t selene-sso:${BRANCH_ALIAS} . """ timeout(time: 2, unit: 'MINUTES') { labelledShell label: 'Running behave tests', script: """ docker run \ --net selene-net \ -v '$HOME/selene/$BRANCH_ALIAS/allure/:/root/allure' \ selene-sso:${BRANCH_ALIAS} """ } } post { always { sh 'docker run \ -v "$HOME/selene/$BRANCH_ALIAS/allure:/root/allure" \ --entrypoint=/bin/bash \ --label build=${JOB_NAME} \ selene-sso:${BRANCH_ALIAS} \ -x -c "chown $(id -u $USER):$(id -g $USER) \ -R /root/allure/"' } } } stage('Public Device API Tests') { when { anyOf { branch 'dev' branch 'master' changeRequest target: 'dev' changeRequest target: 'master' } } steps { labelledShell label: 'Building Docker image', script: """ docker build \ --build-arg wolfram_alpha_key=${WOLFRAM_ALPHA_KEY} \ --build-arg google_stt_key=${GOOGLE_STT_KEY} \ --target public-api-test \ --label job=${JOB_NAME} \ -t selene-public:${BRANCH_ALIAS} . """ timeout(time: 2, unit: 'MINUTES') { labelledShell label: 'Running behave tests', script: """ docker run \ --net selene-net \ -v '$HOME/selene/$BRANCH_ALIAS/allure/:/root/allure' \ -v '$HOME/selene/secrets/:/root/secrets' \ selene-public:${BRANCH_ALIAS} """ } } post { always { sh 'docker run \ -v "$HOME/selene/$BRANCH_ALIAS/allure:/root/allure" \ --entrypoint=/bin/bash \ --label build=${JOB_NAME} \ selene-account:${BRANCH_ALIAS} \ -x -c "chown $(id -u $USER):$(id -g $USER) \ -R /root/allure/"' } } } } post { always { sh 'rm -rf allure-result/*' sh 'mkdir -p $HOME/selene/$BRANCH_ALIAS/allure/allure-result' sh 'mv $HOME/selene/$BRANCH_ALIAS/allure/allure-result allure-result' // This directory should now be empty, rmdir will intentionally fail if not. sh 'rmdir $HOME/selene/$BRANCH_ALIAS/allure' script { allure([ includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'allure-result']] ]) } sh( label: 'Cleanup lingering docker containers and images.', script: """ docker container prune --force; docker image prune --force; """ ) } success { // Docker images should remain upon failure for troubleshooting purposes. However, // if the stage is successful, there is no reason to look back at the Docker image. In theory // broken builds will eventually be fixed so this step should run eventually for every PR sh( label: 'Delete Docker Image on Success', script: ''' docker image prune --all --force --filter label=job=${JOB_NAME}; ''' ) } } } ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ [![License](https://img.shields.io/badge/License-GNU_AGPL%203.0-blue.svg)](LICENSE) [![CLA](https://img.shields.io/badge/CLA%3F-Required-blue.svg)](https://mycroft.ai/cla) [![Team](https://img.shields.io/badge/Team-Mycroft_Backend-violetblue.svg)](https://github.com/MycroftAI/contributors/blob/master/team/Mycroft%20Backend.md) ![Status](https://img.shields.io/badge/-Production_ready-green.svg) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Join chat](https://img.shields.io/badge/Mattermost-join_chat-brightgreen.svg)](https://chat.mycroft.ai) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) Selene -- Mycroft's Server Backend ========== Selene provides the services used by [Mycroft Core](https://github.com/mycroftai/mycroft-core) to manage devices, skills and settings. It consists of two repositories. This one contains Python and SQL representing the database definition, data access layer, APIs and scripts. The second repository, [Selene UI](https://github.com/mycroftai/selene-ui), contains Angular web applications that use the APIs defined in this repository. There are four APIs defined in this repository, account management, single sign on, skill marketplace and device. The first three support account.mycroft.ai (aka home.mycroft.ai), sso.mycroft.ai, and market.mycroft.ai, respectively. The device API is how devices running Mycroft Core communicate with the server. Also included in this repository is a package containing batch scripts for maintenance and the definition of the database schema. Each API is designed to run independently of the others. Code common to each of the APIs, such as the Data Access Layer, can be found in the "shared" directory. The shared code is an independent Python package required by each of the APIs. Each API has its own Pipfile so that it can be run in its own virtual environment. ## Installation The Python code utilizes features introduced in Python 3.7, such as data classes. [Pipenv](https://pipenv.readthedocs.io/en/latest/) is used for virtual environment and package management. If you prefer to use pip and pyenv (or virtualenv), you can find the required libraries in the files named "Pipfile". These instructions will use pipenv commands. If the Selene applications will be servicing a large number of devices (enterprise usage, for example), it is recommended that each of the applications run on their own server or virtual machine. This configuration makes it easier to scale and monitor each application independently. However, all applications can be run on a single server. This configuration could be more practical for a household running a handful of devices. These instructions will assume a multi-server setup for several thousand devices. To run on a single server servicing a small number of devices, the recommended system requirements are 4 CPU, 8GB RAM and 100GB of disk. There are a lot of manual steps in this section that will eventually be replaced with an installation script. All Selene applications are time zone agnostic. It is recommended that the time zone on any server running Selene be UTC. It is recommended to create an application specific user. In these instructions this user will be `mycroft`. ### Postgres DB * Recommended server configuration: [Ubuntu 18.04 LTS (server install)](https://releases.ubuntu.com/bionic/), 2 CPU, 4GB RAM, 50GB disk. * Use the package management system to install Python 3.7, Python 3 pip and PostgreSQL 10 ``` sudo apt-get install postgresql python3.7 python python3-pip ``` * Set Postgres to start on boot ``` sudo systemctl enable postgresql ``` * Clone the selene-backend and documentation repositories ``` sudo mkdir -p /opt/selene sudo chown -R mycroft:users /opt/selene cd /opt/selene git clone https://github.com/MycroftAI/selene-backend.git ``` * Create the virtual environment for the database code ``` sudo python3.7 -m pip install pipenv cd /opt/selene/selene-backend/db pipenv install ``` * Download files from geonames.org used to populate the geography schema tables ``` mkdir -p /opt/selene/data cd /opt/selene/data wget http://download.geonames.org/export/dump/countryInfo.txt wget http://download.geonames.org/export/dump/timeZones.txt wget http://download.geonames.org/export/dump/admin1CodesASCII.txt wget http://download.geonames.org/export/dump/cities500.zip ``` * Add environment variables containing these passwords for the bootstrap script ``` export DB_PASSWORD= export POSTGRES_PASSWORD= ``` * Generate secure passwords for the postgres user and selene user on the database ``` sudo -u postgres psql -c "ALTER USER postgres PASSWORD '$POSTGRES_PASSWORD'" sudo -u postgres psql -c "CREATE ROLE selene WITH LOGIN ENCRYPTED PASSWORD '$DB_PASSWORD'" ``` * Run the bootstrap script ``` cd /opt/selene/selene-backend/db/scripts pipenv run python bootstrap_mycroft_db.py ``` * Note: if you get an authentication error you can temporarily edit `/etc/postgresql//main/pg_hba.conf` replacing the following lines: ``` # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust ``` * By default, Postgres only listens on localhost. This will not do for a multi-server setup. Change the `listen_addresses` value in the `posgresql.conf` file to the private IP of the database server. This file is owned by the `postgres` user so use the following command to edit it (substituting vi for your favorite editor) ``` sudo -u postgres vi /etc/postgres/10/main/postgresql.conf ``` * By default, Postgres only allows connections from localhost. This will not do for a multi-server setup either. Add an entry to the `pg_hba.conf` file for each server that needs to access this database. This file is also owned by the `postgres` user so use the following command to edit it (substituting vi for your favorite editor) ``` sudo -u postgres vi /etc/postgres/10/main/pg_hba.conf ``` * Instructions on how to update the `pg_hba.conf` file can be found in [Postgres' documentation](https://www.postgresql.org/docs/10/auth-pg-hba-conf.html). Below is an example for reference. ``` # IPv4 Selene connections host mycroft selene /32 md5 ``` * Restart Postgres for the `postgres.conf` and `pg_hba.conf` changes to take effect. ``` sudo systemctl restart postgresql ``` ### Redis DB * Recommended server configuration: Ubuntu 18.04 LTS, 1 CPU, 1GB RAM, 5GB disk. So as to not reinvent the wheel, here are some easy-to-follow instructions for [installing Redis on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-redis-on-ubuntu-18-04). * By default, Redis only listens on local host. For multi-server setups, one additional step is to change the "bind" variable in `/etc/redis/redis.conf` to be the private IP of the Redis host. ### APIs The majority of the setup for each API is the same. This section defines the steps common to all APIs. Steps specific to each API will be defined in their respective sections. * Add an application user to the VM. Either give this user sudo privileges or execute the sudo commands below as a user with sudo privileges. These instructions will assume a user name of "mycroft" * Use the package management system to install Python 3.7, Python 3 pip and Python 3.7 Developer Tools ``` sudo apt install python3.7 python3-pip python3.7-dev sudo python3.7 -m pip install pipenv ``` * Setup the Backend Application Directory ``` sudo mkdir -p /opt/selene sudo chown -R mycroft:users /opt/selene ``` * Setup the Log Directory ``` sudo mkdir -p /var/log/mycroft sudo chown -R mycroft:users /var/log/mycroft ``` * Clone the Selene Backend Repository ``` cd /opt/selene git clone https://github.com/MycroftAI/selene-backend.git ``` * If running in a test environment, be sure to checkout the "test" branch of the repository #### Single Sign On API Recommended server configuration: Ubuntu 18.04 LTS, 1 CPU, 1GB RAM, 5GB disk * Create the virtual environment and install the requirements for the application ``` cd /opt/selene/selene-backend/api/sso pipenv install ``` #### Account API * Recommended server configuration: Ubuntu 18.04 LTS, 1 CPU, 1GB RAM, 5GB disk * Create the virtual environment and install the requirements for the application ``` cd /opt/selene/selene-backend/api/account pipenv install ``` #### Marketplace API * Recommended server configuration: Ubuntu 18.04 LTS, 1 CPU, 1GB RAM, 10GB disk * Create the virtual environment and install the requirements for the application ``` cd /opt/selene/selene-backend/api/market pipenv install ``` #### Device API * Recommended server configuration: Ubuntu 18.04 LTS, 2 CPU, 2GB RAM, 50GB disk * Create the virtual environment and install the requirements for the application ``` cd /opt/selene/selene-backend/api/public pipenv install ``` #### Precise API * Recommended server configuration: Ubuntu 18.04 LTS, 1 CPU, 1GB RAM, 5GB disk * Create the virtual environment and install the requirements for the application ``` cd /opt/selene/selene-backend/api/precise pipenv install ``` ### Running the APIs Each API is configured to run on port 5000. This is not a problem if each is running in its own VM but will be an issue if all APIs are running on the same server, or if port 5000 is already in use. To address these scenarios, change the port numbering in the uwsgi.ini file for each API. #### Single Sign On API * The SSO application uses three JWTs for authentication. First is an access key, which is required to authenticate a user for API calls. Second is a refresh key that automatically refreshes the access key when it expires. Third is a reset key, which is used in a password reset scenario. Generate a secret key for each JWT. * Any data that can identify a user is encrypted. Generate a salt that will be used with the encryption algorithm. * Access to the Github API is required to support logging in with your Github account. Details can be found [here](https://developer.github.com/v3/guides/basics-of-authentication/). * The password reset functionality sends an email to the user with a link to reset their password. Selene uses SendGrid to send these emails so a SendGrid account and API key are required. * Define a systemd service to run the API. The service defines environment variables that use the secret and API keys generated in previous steps. ``` sudo vim /etc/systemd/system/sso_api.service ``` ``` [Unit] Description=Mycroft Single Sign On Api After=network.target [Service] User=mycroft Group=www-data Restart=always Type=simple WorkingDirectory=/opt/selene/selene-backend/api/sso ExecStart=/usr/local/bin/pipenv run uwsgi --ini uwsgi.ini Environment=DB_HOST= Environment=DB_NAME=mycroft Environment=DB_PASSWORD= Environment=DB_PORT=5432 Environment=DB_USER=selene Environment=GITHUB_CLIENT_ID= Environment=GITHUB_CLIENT_SECRET= Environment=JWT_ACCESS_SECRET= Environment=JWT_REFRESH_SECRET= Environment=JWT_RESET_SECRET= Environment=SALT= Environment=SELENE_ENVIRONMENT= Environment=SENDGRID_API_KEY= Environment=SSO_BASE_URL= [Install] WantedBy=multi-user.target ``` * Start the sso_api service and set it to start on boot ``` sudo systemctl start sso_api.service sudo systemctl enable sso_api.service ``` #### Account API * The account API uses the same authentication mechanism as the single sign on API. The JWT_ACCESS_SECRET, JWT_REFRESH_SECRET and SALT environment variables must be the same values as those on the single sign on API. * This application uses the Redis database so the service needs to know where it resides. * Define a systemd service to run the API. The service defines environment variables that use the secret and API keys generated in previous steps. ``` sudo vim /etc/systemd/system/account_api.service ``` ``` [Unit] Description=Mycroft Account API After=network.target [Service] User=mycroft Group=www-data Restart=always Type=simple WorkingDirectory=/opt/selene/selene-backend/api/account ExecStart=/usr/local/bin/pipenv run uwsgi --ini uwsgi.ini Environment=DB_HOST= Environment=DB_NAME=mycroft Environment=DB_PASSWORD= Environment=DB_PORT=5432 Environment=DB_USER=selene Environment=JWT_ACCESS_SECRET= Environment=JWT_REFRESH_SECRET= Environment=OAUTH_BASE_URL= Environment=REDIS_HOST= Environment=REDIS_PORT=6379 Environment=SELENE_ENVIRONMENT= Environment=SALT= [Install] WantedBy=multi-user.target ``` * Start the account_api service and set it to start on boot ``` sudo systemctl start account_api.service sudo systemctl enable account_api.service ``` #### Marketplace API * The marketplace API uses the same authentication mechanism as the single sign on API. The JWT_ACCESS_SECRET, JWT_REFRESH_SECRET and SALT environment variables must be the same values as those on the single sign on API. * This application uses the Redis database so the service needs to know where it resides. * Define a systemd service to run the API. The service defines environment variables that use the secret and API keys generated in previous steps. ``` sudo vim /etc/systemd/system/market_api.service ``` ``` [Unit] Description=Mycroft Marketplace API After=network.target [Service] User=mycroft Group=www-data Restart=always Type=simple WorkingDirectory=/opt/selene/selene-backend/api/market ExecStart=/usr/local/bin/pipenv run uwsgi --ini uwsgi.ini Environment=DB_HOST= Environment=DB_NAME=mycroft Environment=DB_PASSWORD= Environment=DB_PORT=5432 Environment=DB_USER=selene Environment=JWT_ACCESS_SECRET= Environment=JWT_REFRESH_SECRET= Environment=OAUTH_BASE_URL= Environment=REDIS_HOST= Environment=REDIS_PORT=6379 Environment=SELENE_ENVIRONMENT= Environment=SALT= [Install] WantedBy=multi-user.target ``` * Start the market_api service and set it to start on boot ``` sudo systemctl start market_api.service sudo systemctl enable market_api.service ``` * The marketplace API assumes that the skills it supplies to the web application are in the Postgres database. To get them there, a script needs to be run to download them from Github. The script requires the GITHUB_USER, GITHUB_PASSWORD, DB_HOST, DB_NAME, DB_USER and DB_PASSWORD environment variables to run. Use the same values as those in the service definition files. ``` cd /opt/selene/selene-backend/batch pipenv install pipenv run python load_skill_display_data.py --core-version ``` #### Device API * The device API uses the same authentication mechanism as the single sign on API. The JWT_ACCESS_SECRET, JWT_REFRESH_SECRET and SALT environment variables must be the same values as those on the single sign on API. * This application uses the Redis database so the service needs to know where it resides. * The weather skill requires a key to the Open Weather Map API * The speech to text engine requires a key to Google's STT API. * The Wolfram Alpha skill requires an API key to the Wolfram Alpha API * Define a systemd service to run the API. The service defines environment variables that use the secret and API keys generated in previous steps. ``` sudo vim /etc/systemd/system/public_api.service ``` ``` [Unit] Description=Mycroft Public API After=network.target [Service] User=mycroft Group=www-data Restart=always Type=simple WorkingDirectory=/opt/selene/selene-backend/api/public ExecStart=/usr/local/bin/pipenv run uwsgi --ini uwsgi.ini Environment=DB_HOST= Environment=DB_NAME=mycroft Environment=DB_PASSWORD= Environment=DB_PORT=5432 Environment=DB_USER=selene Environment=EMAIL_SERVICE_HOST= Environment=EMAIL_SERVICE_PORT= Environment=EMAIL_SERVICE_USER= Environment=EMAIL_SERVICE_PASSWORD= Environment=GOOGLE_STT_KEY= Environment=JWT_ACCESS_SECRET= Environment=JWT_REFRESH_SECRET= Environment=OAUTH_BASE_URL= Environment=OWM_KEY= Environment=OWM_URL=https://api.openweathermap.org/data/2.5 Environment=REDIS_HOST= Environment=REDIS_PORT=6379 Environment=SELENE_ENVIRONMENT= Environment=SALT= Environment=WOLFRAM_ALPHA_KEY=. ================================================ FILE: api/account/account_api/api.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """Entry point for the API that supports the Mycroft Marketplace.""" from flask import Flask from selene.api import get_base_config, selene_api, SeleneResponse from selene.api.endpoints import ( AccountEndpoint, AgreementsEndpoint, ValidateEmailEndpoint, ) from selene.util.cache import SeleneCache from selene.util.log import configure_selene_logger from .endpoints import ( AccountDefaultsEndpoint, CityEndpoint, CountryEndpoint, EmailAddressChangeEndpoint, DeviceEndpoint, DeviceCountEndpoint, GeographyEndpoint, MembershipEndpoint, RegionEndpoint, PairingCodeEndpoint, PasswordChangeEndpoint, PreferencesEndpoint, SkillsEndpoint, SkillOauthEndpoint, SkillSettingsEndpoint, SoftwareUpdateEndpoint, SshKeyValidatorEndpoint, TimezoneEndpoint, VerifyEmailAddressEndpoint, VoiceEndpoint, WakeWordEndpoint, ) configure_selene_logger("account_api") # Define the Flask application acct = Flask(__name__) acct.config.from_object(get_base_config()) acct.response_class = SeleneResponse acct.register_blueprint(selene_api) acct.config["SELENE_CACHE"] = SeleneCache() account_endpoint = AccountEndpoint.as_view("account_endpoint") acct.add_url_rule( "/api/account", view_func=account_endpoint, methods=["GET", "PATCH", "DELETE"] ) agreements_endpoint = AgreementsEndpoint.as_view("agreements_endpoint") acct.add_url_rule( "/api/agreement/", view_func=agreements_endpoint, methods=["GET"], ) city_endpoint = CityEndpoint.as_view("city_endpoint") acct.add_url_rule("/api/cities", view_func=city_endpoint, methods=["GET"]) country_endpoint = CountryEndpoint.as_view("country_endpoint") acct.add_url_rule("/api/countries", view_func=country_endpoint, methods=["GET"]) defaults_endpoint = AccountDefaultsEndpoint.as_view("defaults_endpoint") acct.add_url_rule( "/api/defaults", view_func=defaults_endpoint, methods=["GET", "PATCH", "POST"] ) device_endpoint = DeviceEndpoint.as_view("device_endpoint") acct.add_url_rule( "/api/devices", defaults={"device_id": None}, view_func=device_endpoint, methods=["GET"], ) acct.add_url_rule("/api/devices", view_func=device_endpoint, methods=["POST"]) acct.add_url_rule( "/api/devices/", view_func=device_endpoint, methods=["DELETE", "GET", "PATCH"], ) device_count_endpoint = DeviceCountEndpoint.as_view("device_count_endpoint") acct.add_url_rule("/api/device-count", view_func=device_count_endpoint, methods=["GET"]) change_email_endpoint = EmailAddressChangeEndpoint.as_view("change_email_endpoint") acct.add_url_rule("/api/change-email", view_func=change_email_endpoint, methods=["PUT"]) change_password_endpoint = PasswordChangeEndpoint.as_view("change_password_endpoint") acct.add_url_rule( "/api/change-password", view_func=change_password_endpoint, methods=["PUT"] ) geography_endpoint = GeographyEndpoint.as_view("geography_endpoint") acct.add_url_rule("/api/geographies", view_func=geography_endpoint, methods=["GET"]) membership_endpoint = MembershipEndpoint.as_view("membership_endpoint") acct.add_url_rule("/api/memberships", view_func=membership_endpoint, methods=["GET"]) pairing_code_endpoint = PairingCodeEndpoint.as_view("pairing_code_endpoint") acct.add_url_rule( "/api/pairing-code/", view_func=pairing_code_endpoint, methods=["GET"], ) preferences_endpoint = PreferencesEndpoint.as_view("preferences_endpoint") acct.add_url_rule( "/api/preferences", view_func=preferences_endpoint, methods=["GET", "PATCH", "POST"] ) region_endpoint = RegionEndpoint.as_view("region_endpoint") acct.add_url_rule("/api/regions", view_func=region_endpoint, methods=["GET"]) setting_endpoint = SkillSettingsEndpoint.as_view("setting_endpoint") acct.add_url_rule( "/api/skills//settings", view_func=setting_endpoint, methods=["GET", "PUT"], ) skill_endpoint = SkillsEndpoint.as_view("skill_endpoint") acct.add_url_rule("/api/skills", view_func=skill_endpoint, methods=["GET"]) skill_oauth_endpoint = SkillOauthEndpoint.as_view("skill_oauth_endpoint") acct.add_url_rule( "/api/skills/oauth/", view_func=skill_oauth_endpoint, methods=["GET"] ) software_update_endpoint = SoftwareUpdateEndpoint.as_view("software_update_endpoint") acct.add_url_rule( "/api/software-update", view_func=software_update_endpoint, methods=["PATCH"] ) ssh_key_validation_endpoint = SshKeyValidatorEndpoint.as_view( "ssh_key_validation_endpoint" ) acct.add_url_rule( "/api/ssh-key", view_func=ssh_key_validation_endpoint, methods=["GET"], ) timezone_endpoint = TimezoneEndpoint.as_view("timezone_endpoint") acct.add_url_rule("/api/timezones", view_func=timezone_endpoint, methods=["GET"]) validate_email_endpoint = ValidateEmailEndpoint.as_view("validate_email_endpoint") acct.add_url_rule( "/api/validate-email", view_func=validate_email_endpoint, methods=["GET"] ) verify_email_endpoint = VerifyEmailAddressEndpoint.as_view("verify_email_endpoint") acct.add_url_rule("/api/verify-email", view_func=verify_email_endpoint, methods=["PUT"]) voice_endpoint = VoiceEndpoint.as_view("voice_endpoint") acct.add_url_rule("/api/voices", view_func=voice_endpoint, methods=["GET"]) wake_word_endpoint = WakeWordEndpoint.as_view("wake_word_endpoint") acct.add_url_rule("/api/wake-words", view_func=wake_word_endpoint, methods=["GET"]) ================================================ FILE: api/account/account_api/endpoints/__init__.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """Public API into the endpoints package.""" from .preferences import PreferencesEndpoint from .change_email_address import EmailAddressChangeEndpoint from .change_password import PasswordChangeEndpoint from .city import CityEndpoint from .country import CountryEndpoint from .defaults import AccountDefaultsEndpoint from .device import DeviceEndpoint from .device_count import DeviceCountEndpoint from .geography import GeographyEndpoint from .membership import MembershipEndpoint from .pairing_code import PairingCodeEndpoint from .region import RegionEndpoint from .skills import SkillsEndpoint from .skill_oauth import SkillOauthEndpoint from .skill_settings import SkillSettingsEndpoint from .software_update import SoftwareUpdateEndpoint from .ssh_key_validator import SshKeyValidatorEndpoint from .timezone import TimezoneEndpoint from .verify_email_address import VerifyEmailAddressEndpoint from .voice_endpoint import VoiceEndpoint from .wake_word_endpoint import WakeWordEndpoint ================================================ FILE: api/account/account_api/endpoints/change_email_address.py ================================================ # Mycroft Server - Backend # Copyright (c) 2022 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # # This file is part of the Mycroft Server. # # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # """Defines the password change endpoint for the account API. This endpoint does not update the email address in the database. The user needs to verify the email address is correct before the change is applied. See the verify_email_address module in this package for the verification step. """ from binascii import a2b_base64, b2a_base64 from http import HTTPStatus from os import environ from selene.api import APIError, SeleneEndpoint from selene.util.email import EmailMessage, SeleneMailer, validate_email_address class EmailAddressChangeEndpoint(SeleneEndpoint): """Adds authentication to the common password changing endpoint.""" def put(self): """Executes an HTTP PUT request.""" self._authenticate() new_email_address = self._validate_request() self._send_notification() self._send_verification_email(new_email_address) return "", HTTPStatus.NO_CONTENT def _validate_request(self) -> str: """Validates the content of the API request. :returns: A validated and normalized email address :raises: APIError when email address is invalid """ request_token = self.request.json["token"] new_email_address = a2b_base64(request_token).decode() normalized_address, error = validate_email_address(new_email_address) if error is not None: raise APIError(error) return normalized_address def _send_notification(self): """Notifies the current email address' owner of the requested change.""" _, error = validate_email_address(self.account.email_address) if error is None: email = EmailMessage( recipient=self.account.email_address, sender="Mycroft AI", subject="Email Address Changed", template_file_name="email_change.html", ) mailer = SeleneMailer(email) mailer.send(using_jinja=True) @staticmethod def _send_verification_email(new_email_address): """Sends an email with a link for email verification to the requested address. :param new_email_address: the recipient of the verification email """ base_url = environ["ACCOUNT_BASE_URL"] token = b2a_base64(new_email_address.encode(), newline=False).decode() url = f"{base_url}/verify-email?token={token}" email = EmailMessage( recipient=new_email_address, sender="Mycroft AI", subject="Email Change Verification", template_file_name="email_verification.html", template_variables=dict(email_verification_url=url), ) mailer = SeleneMailer(email) mailer.send(using_jinja=True) ================================================ FILE: api/account/account_api/endpoints/change_password.py ================================================ # Mycroft Server - Backend # Copyright (c) 2022 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # # This file is part of the Mycroft Server. # # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # """Defines the password change endpoint for the account API.""" from selene.api.endpoints import PasswordChangeEndpoint as CommonPasswordChangeEndpoint from selene.util.email import EmailMessage, SeleneMailer class PasswordChangeEndpoint(CommonPasswordChangeEndpoint): """Adds authentication to the common password changing endpoint.""" @property def account_id(self): return self.account.id def _send_email(self): email = EmailMessage( recipient=self.account.email_address, sender="Mycroft AI", subject="Password Changed", template_file_name="password_change.html", ) mailer = SeleneMailer(email) mailer.send(using_jinja=True) ================================================ FILE: api/account/account_api/endpoints/city.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """Account API endpoint for retrieving city geographical information.""" from http import HTTPStatus from selene.api import SeleneEndpoint from selene.data.geography import CityRepository class CityEndpoint(SeleneEndpoint): """Retrieve a city in a region""" def get(self): """Process an HTTP GET request.""" region_id = self.request.args["region"] city_repository = CityRepository(self.db) cities = city_repository.get_cities_by_region(region_id=region_id) for city in cities: city.longitude = float(city.longitude) city.latitude = float(city.latitude) return cities, HTTPStatus.OK ================================================ FILE: api/account/account_api/endpoints/country.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from http import HTTPStatus from selene.api import SeleneEndpoint from selene.data.geography import CountryRepository class CountryEndpoint(SeleneEndpoint): def get(self): country_repository = CountryRepository(self.db) countries = country_repository.get_countries() return countries, HTTPStatus.OK ================================================ FILE: api/account/account_api/endpoints/defaults.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """Account API endpoint for account defaults.""" from http import HTTPStatus from flask import json from schematics import Model from schematics.types import StringType from selene.api import SeleneEndpoint from selene.data.device import DefaultsRepository from selene.util.log import get_selene_logger _log = get_selene_logger(__name__) class DefaultsRequest(Model): """Data model of the POST request.""" city = StringType() country = StringType() region = StringType() timezone = StringType() voice = StringType() wake_word = StringType() class AccountDefaultsEndpoint(SeleneEndpoint): """Handle account default HTTP requests.""" def __init__(self): super().__init__() self.defaults = None def get(self): """Process a HTTP GET request.""" self._authenticate() self._get_defaults() if self.defaults is None: response_data = "" response_code = HTTPStatus.NO_CONTENT else: response_data = self.defaults response_code = HTTPStatus.OK return response_data, response_code def _get_defaults(self): """Get the account defaults from the database.""" default_repository = DefaultsRepository(self.db, self.account.id) self.defaults = default_repository.get_account_defaults() if self.defaults is not None and self.defaults.wake_word.name is not None: self.defaults.wake_word.name = self.defaults.wake_word.name.title() def post(self): """Process a HTTP POST request.""" self._authenticate() defaults = self._validate_request() self._upsert_defaults(defaults) return "", HTTPStatus.NO_CONTENT def patch(self): """Process an HTTP PATCH request.""" self._authenticate() defaults = self._validate_request() self._upsert_defaults(defaults) return "", HTTPStatus.NO_CONTENT def _validate_request(self) -> dict: """Validate the data on the POST/PATCH request""" request_data = json.loads(self.request.data) defaults = DefaultsRequest() defaults.city = request_data.get("city") defaults.country = request_data.get("country") defaults.region = request_data.get("region") defaults.timezone = request_data.get("timezone") defaults.voice = request_data["voice"] defaults.wake_word = request_data["wakeWord"] defaults.validate() return defaults.to_native() def _upsert_defaults(self, defaults: dict): """Apply the changes in the request to the database.""" defaults_repository = DefaultsRepository(self.db, self.account.id) wake_word_default = defaults.get("wake_word") if wake_word_default is not None: defaults["wake_word"] = defaults["wake_word"].lower() defaults_repository.upsert(defaults) ================================================ FILE: api/account/account_api/endpoints/device.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """Account API endpoint for retrieving and maintaining device information.""" from dataclasses import asdict from datetime import datetime, timedelta from http import HTTPStatus from typing import List, Optional from flask import json from schematics import Model from schematics.exceptions import ValidationError from schematics.types import BooleanType, StringType from selene.api import SeleneEndpoint from selene.api.etag import ETagManager from selene.api.pantacor import get_pantacor_pending_deployment, update_pantacor_config from selene.api.public_endpoint import delete_device_login from selene.data.device import Device, DeviceRepository, Geography, GeographyRepository from selene.util.cache import ( DEVICE_LAST_CONTACT_KEY, DEVICE_PAIRING_CODE_KEY, DEVICE_PAIRING_TOKEN_KEY, SeleneCache, ) from selene.util.db import use_transaction from selene.util.log import get_selene_logger ONE_DAY = 86400 CONNECTED = "Connected" DISCONNECTED = "Disconnected" DORMANT = "Dormant" _log = get_selene_logger(__name__) def validate_pairing_code(pairing_code): """Ensure the pairing code exists in the cache of valid pairing codes.""" cache_key = DEVICE_PAIRING_CODE_KEY.format(pairing_code=pairing_code) cache = SeleneCache() pairing_cache = cache.get(cache_key) if pairing_cache is None: raise ValidationError("pairing code not found") class UpdateDeviceRequest(Model): """Schematic for a request to update a device.""" city = StringType(required=True) country = StringType(required=True) name = StringType(required=True) placement = StringType() region = StringType(required=True) timezone = StringType(required=True) wake_word = StringType(required=True, deserialize_from="wakeWord") voice = StringType(required=True) auto_update = BooleanType(deserialize_from="autoUpdate") ssh_public_key = StringType(deserialize_from="sshPublicKey") release_channel = StringType(deserialize_from="releaseChannel") class NewDeviceRequest(UpdateDeviceRequest): """Schematic for a request to add a device.""" pairing_code = StringType( required=True, deserialize_from="pairingCode", validators=[validate_pairing_code], ) class DeviceEndpoint(SeleneEndpoint): """Retrieve and maintain device information for the Account API""" _device_repository = None def __init__(self): super().__init__() self.devices = None self.validated_request = None self.cache = self.config["SELENE_CACHE"] self.etag_manager: ETagManager = ETagManager(self.cache, self.config) self.pantacor_channels = dict( myc200_dev_test="Development", myc200_beta_qa_test="Beta QA", myc200_beta="Beta", myc200_stable="Stable", myc200_lts="LTS", ) @property def device_repository(self): """Lazily instantiate the device repository.""" if self._device_repository is None: self._device_repository = DeviceRepository(self.db) return self._device_repository def get(self, device_id: str): """Process an HTTP GET request.""" self._authenticate() if device_id is None: response_data = self._get_devices() else: response_data = self._get_device(device_id) return response_data, HTTPStatus.OK def _get_devices(self) -> List[dict]: """Get a list of the devices belonging to the account in the request JWT :return: list of devices to be returned to the UI. """ devices = self.device_repository.get_devices_by_account_id(self.account.id) response_data = [] for device in devices: response_device = self._format_device_for_response(device) response_data.append(response_device) return response_data def _get_device(self, device_id: str) -> dict: """Get the device information for a specific device. :param device_id: Identifier of the device to retrieve :return: device information to return to the UI """ device = self.device_repository.get_device_by_id(device_id) response_data = self._format_device_for_response(device) return response_data def _format_device_for_response(self, device: Device) -> dict: """Convert device object into a response object for this endpoint. :param device: the device data retrieved from the database. :return: device information formatted for the UI """ pantacor_config = self._format_pantacor_config(device.pantacor_config) device_status, disconnect_duration = self._format_device_status(device) formatted_device = asdict(device) formatted_device["pantacor_config"].update(pantacor_config) formatted_device["wake_word"].update(name=device.wake_word.name.title()) formatted_device.update( status=device_status, disconnect_duration=disconnect_duration, voice=formatted_device.pop("text_to_speech"), ) return formatted_device def _format_pantacor_config(self, config) -> dict[str, str]: """Converts Pantacor config values in the database into displayable values. :param config: Pantacor config database values :returns: Pantacor config displayable values """ formatted_config = dict(deployment_id=None) manual_update = config.auto_update is not None and not config.auto_update if manual_update: formatted_config.update( deployment_id=get_pantacor_pending_deployment(config.pantacor_id) ) if config.release_channel is not None: formatted_config.update( release_channel=self.pantacor_channels.get(config.release_channel) ) return formatted_config def _format_device_status(self, device: Device) -> tuple[str, Optional[str]]: """Determines the status of the device being returned. :param device: The device to determine the status of :return: status of the device and the duration of disconnect (if applicable) """ last_contact_age = self._get_device_last_contact(device) device_status = self._determine_device_status(last_contact_age) if device_status == DISCONNECTED: disconnect_duration = self._determine_disconnect_duration(last_contact_age) else: disconnect_duration = None return device_status, disconnect_duration def _get_device_last_contact(self, device: Device) -> timedelta: """Get the last time the device contacted the backend. The timestamp returned by this method will be used to determine if a device is active or not. The device table has a last contacted column but it is only updated daily via batch script. The real-time values are kept in Redis. If the Redis query returns nothing, the device hasn't contacted the backend yet. This could be because it was just activated. Give the device a couple of minutes to make that first call to the backend. :param device: the device data retrieved from the database. :return: the timestamp the device was last seen by Selene """ last_contact_ts = self.cache.get( DEVICE_LAST_CONTACT_KEY.format(device_id=device.id) ) if last_contact_ts is None: if device.last_contact_ts is None: last_contact_age = datetime.utcnow() - device.add_ts else: last_contact_age = datetime.utcnow() - device.last_contact_ts else: last_contact_ts = last_contact_ts.decode() last_contact_ts = datetime.strptime(last_contact_ts, "%Y-%m-%d %H:%M:%S.%f") last_contact_age = datetime.utcnow() - last_contact_ts return last_contact_age @staticmethod def _determine_device_status(last_contact_age: timedelta) -> str: """Derive device status from the last time device contacted servers. :param last_contact_age: amount of time since the device was last seen :return: the status of the device """ if last_contact_age <= timedelta(seconds=120): device_status = CONNECTED elif timedelta(seconds=120) < last_contact_age < timedelta(days=30): device_status = DISCONNECTED else: device_status = DORMANT return device_status @staticmethod def _determine_disconnect_duration(last_contact_age: timedelta) -> str: """Derive device status from the last time device contacted servers. :param last_contact_age: amount of time since the device was last seen :return human readable amount of time since the device was last seen """ disconnect_duration = "unknown" days, _ = divmod(last_contact_age, timedelta(days=1)) if days: disconnect_duration = str(days) + " days" else: hours, remaining = divmod(last_contact_age, timedelta(hours=1)) if hours: disconnect_duration = str(hours) + " hours" else: minutes, _ = divmod(remaining, timedelta(minutes=1)) if minutes: disconnect_duration = str(minutes) + " minutes" return disconnect_duration def post(self): """Handle a HTTP POST request.""" self._authenticate() self._validate_request() self._pair_device() return "", HTTPStatus.NO_CONTENT @use_transaction def _pair_device(self): """Add the paired device to the database.""" cache_key = DEVICE_PAIRING_CODE_KEY.format( pairing_code=self.validated_request["pairing_code"] ) pairing_data = self._get_pairing_data(cache_key) device_id = self._add_device() pairing_data["uuid"] = device_id self.cache.delete(cache_key) self._build_pairing_token(pairing_data) def _get_pairing_data(self, cache_key) -> dict: """Checking if there's one pairing session for the pairing code. :return: the pairing code information from the Redis database """ pairing_cache = self.cache.get(cache_key) pairing_data = json.loads(pairing_cache) return pairing_data def _add_device(self) -> str: """Creates a device and associate it to a pairing session. :return: the database identifier of the new device """ self._ensure_geography_exists() device_id = self.device_repository.add(self.account.id, self.validated_request) return device_id def _build_pairing_token(self, pairing_data: dict): """Add a pairing token to the Redis database. :param pairing_data: the pairing data retrieved from Redis """ self.cache.set_with_expiration( key=DEVICE_PAIRING_TOKEN_KEY.format(pairing_token=pairing_data["token"]), value=json.dumps(pairing_data), expiration=ONE_DAY, ) def delete(self, device_id: str): """Handle an HTTP DELETE request. :param device_id: database identifier of a device """ self._authenticate() self._delete_device(device_id) return "", HTTPStatus.NO_CONTENT def _delete_device(self, device_id: str): """Delete the specified device from the database. There are other tables related to the device table in the database. This method assumes that the child tables contain "delete cascade" clauses. :param device_id: database identifier of a device """ self.device_repository.remove(device_id) delete_device_login(device_id, self.cache) def patch(self, device_id: str): """Handle a HTTP PATCH request. :param device_id: database identifier of a device """ self._authenticate() self._validate_request() self._update_device(device_id) self.etag_manager.expire_device_etag_by_device_id(device_id) self.etag_manager.expire_device_location_etag_by_device_id(device_id) self.etag_manager.expire_device_setting_etag_by_device_id(device_id) return "", HTTPStatus.NO_CONTENT def _validate_request(self): """Validate the contents of the HTTP POST request.""" if self.request.method == "POST": device = NewDeviceRequest(self.request.json) else: device = UpdateDeviceRequest(self.request.json) device.validate() self.validated_request = device.to_native() self.validated_request.update( wake_word=self.validated_request["wake_word"].lower() ) if self.validated_request["release_channel"] is not None: self.validated_request.update( release_channel=self.validated_request["release_channel"].lower() ) def _ensure_geography_exists(self): """If the requested geography is not linked to the account, add it. :return: database identifier for the geography """ geography = Geography( city=self.validated_request.pop("city"), country=self.validated_request.pop("country"), region=self.validated_request.pop("region"), time_zone=self.validated_request.pop("timezone"), ) geography_repository = GeographyRepository(self.db, self.account.id) geography_id = geography_repository.get_geography_id(geography) if geography_id is None: geography_id = geography_repository.add(geography) self.validated_request.update(geography_id=geography_id) @use_transaction def _update_device(self, device_id: str): """Update the device attributes on the database based on the request. If the device's continuous delivery is managed by Pantacor, attempt the Pantacor API calls first. That way, if they fail, the database updates won't happen and we won't get stuck in a half-updated state. :param device_id: database identifier of a device """ device = self.device_repository.get_device_by_id(device_id) if device.pantacor_config.pantacor_id is not None: self._update_pantacor_config(device) self._ensure_geography_exists() self.device_repository.update_device_from_account( self.account.id, device_id, self.validated_request ) def _update_pantacor_config(self, device: Device): """Update the Pantacor configuration on the database based on the request. :param device: data object representing a Mycroft-enabled device """ new_pantacor_config = dict( auto_update=self.validated_request.pop("auto_update"), release_channel=self.validated_request.pop("release_channel"), ssh_public_key=self.validated_request.pop("ssh_public_key"), ) pantacor_channel_name = self._convert_release_channel( new_pantacor_config["release_channel"] ) new_pantacor_config.update(release_channel=pantacor_channel_name) old_pantacor_config = asdict(device.pantacor_config) update_pantacor_config(old_pantacor_config, new_pantacor_config) self.device_repository.update_pantacor_config(device.id, new_pantacor_config) def _convert_release_channel(self, release_channel: str) -> str: """Converts the channel sent in the request to one recognized by Pantacor. :param release_channel: the value of the release channel in the request :returns: the release channel as recognized by Pantacor """ pantacor_channel_name = None for channel_name, channel_display in self.pantacor_channels.items(): if channel_display.lower() == release_channel: pantacor_channel_name = channel_name _log.info("pantacor channel name: %s", pantacor_channel_name) return pantacor_channel_name ================================================ FILE: api/account/account_api/endpoints/device_count.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from http import HTTPStatus from selene.api import SeleneEndpoint from selene.data.device import DeviceRepository class DeviceCountEndpoint(SeleneEndpoint): def get(self): self._authenticate() device_count = self._get_devices() return dict(deviceCount=device_count), HTTPStatus.OK def _get_devices(self): device_repository = DeviceRepository(self.db) device_count = device_repository.get_account_device_count(self.account.id) return device_count ================================================ FILE: api/account/account_api/endpoints/geography.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from http import HTTPStatus from selene.api import SeleneEndpoint from selene.data.device import GeographyRepository class GeographyEndpoint(SeleneEndpoint): def get(self): self._authenticate() response_data = self._build_response_data() return response_data, HTTPStatus.OK def _build_response_data(self): geography_repository = GeographyRepository(self.db, self.account.id) geographies = geography_repository.get_account_geographies() response_data = [] for geography in geographies: response_data.append( dict(id=geography.id, name=geography.country, user_defined=True) ) return response_data ================================================ FILE: api/account/account_api/endpoints/membership.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from http import HTTPStatus from selene.api import SeleneEndpoint from selene.data.account import MembershipRepository class MembershipEndpoint(SeleneEndpoint): def get(self): membership_repository = MembershipRepository(self.db) membership_types = membership_repository.get_membership_types() for membership_type in membership_types: membership_type.rate = float(membership_type.rate) return membership_types, HTTPStatus.OK ================================================ FILE: api/account/account_api/endpoints/pairing_code.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from http import HTTPStatus from selene.api import SeleneEndpoint class PairingCodeEndpoint(SeleneEndpoint): def __init__(self): super(PairingCodeEndpoint, self).__init__() self.cache = self.config["SELENE_CACHE"] def get(self, pairing_code): self._authenticate() pairing_code_is_valid = self._get_pairing_data(pairing_code) return dict(isValid=pairing_code_is_valid), HTTPStatus.OK def _get_pairing_data(self, pairing_code: str) -> bool: """Checking if there's one pairing session for the pairing code.""" pairing_code_is_valid = False cache_key = "pairing.code:" + pairing_code pairing_cache = self.cache.get(cache_key) if pairing_cache is not None: pairing_code_is_valid = True return pairing_code_is_valid ================================================ FILE: api/account/account_api/endpoints/preferences.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from dataclasses import asdict from http import HTTPStatus from schematics import Model from schematics.types import StringType from selene.api import SeleneEndpoint from selene.api.etag import ETagManager from selene.data.device import AccountPreferences, PreferenceRepository class PreferencesRequest(Model): date_format = StringType(required=True, choices=["DD/MM/YYYY", "MM/DD/YYYY"]) measurement_system = StringType(required=True, choices=["Imperial", "Metric"]) time_format = StringType(required=True, choices=["12 Hour", "24 Hour"]) class PreferencesEndpoint(SeleneEndpoint): def __init__(self): super(PreferencesEndpoint, self).__init__() self.preferences = None self.cache = self.config["SELENE_CACHE"] self.etag_manager: ETagManager = ETagManager(self.cache, self.config) def get(self): self._authenticate() self._get_preferences() if self.preferences is None: response_data = "" response_code = HTTPStatus.NO_CONTENT else: response_data = asdict(self.preferences) response_code = HTTPStatus.OK return response_data, response_code def _get_preferences(self): preference_repository = PreferenceRepository(self.db, self.account.id) self.preferences = preference_repository.get_account_preferences() def post(self): self._authenticate() self._validate_request() self._upsert_preferences() self.etag_manager.expire_device_setting_etag_by_account_id(self.account.id) return "", HTTPStatus.NO_CONTENT def patch(self): self._authenticate() self._validate_request() self._upsert_preferences() self.etag_manager.expire_device_setting_etag_by_account_id(self.account.id) return "", HTTPStatus.NO_CONTENT def _validate_request(self): self.preferences = PreferencesRequest() self.preferences.date_format = self.request.json["dateFormat"] self.preferences.measurement_system = self.request.json["measurementSystem"] self.preferences.time_format = self.request.json["timeFormat"] self.preferences.validate() def _upsert_preferences(self): preferences_repository = PreferenceRepository(self.db, self.account.id) preferences = AccountPreferences(**self.preferences.to_native()) preferences_repository.upsert(preferences) ================================================ FILE: api/account/account_api/endpoints/region.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from http import HTTPStatus from selene.api import SeleneEndpoint from selene.data.geography import RegionRepository class RegionEndpoint(SeleneEndpoint): def get(self): country_id = self.request.args["country"] region_repository = RegionRepository(self.db) regions = region_repository.get_regions_by_country(country_id) return regions, HTTPStatus.OK ================================================ FILE: api/account/account_api/endpoints/skill_oauth.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import os import requests from selene.api import SeleneEndpoint class SkillOauthEndpoint(SeleneEndpoint): def __init__(self): super(SkillOauthEndpoint, self).__init__() self.oauth_base_url = os.environ["OAUTH_BASE_URL"] def get(self, oauth_id): self._authenticate() return self._get_oauth_url(oauth_id) def _get_oauth_url(self, oauth_id): url = "{base_url}/auth/{oauth_id}/auth_url?uuid={account_id}".format( base_url=self.oauth_base_url, oauth_id=oauth_id, account_id=self.account.id ) response = requests.get(url) return response.text, response.status_code ================================================ FILE: api/account/account_api/endpoints/skill_settings.py ================================================ # Mycroft Server - Backend # Copyright (C) 2019 Mycroft AI Inc # SPDX-License-Identifier: AGPL-3.0-or-later # # This file is part of the Mycroft Server. # # The Mycroft Server is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """Endpoint to return the skill settings for a given skill family.""" from http import HTTPStatus from flask import json, Response from selene.api import SeleneEndpoint from selene.api.etag import ETagManager from selene.data.skill import SkillSettingRepository, AccountSkillSetting class SkillSettingsEndpoint(SeleneEndpoint): _setting_repository = None def __init__(self): super(SkillSettingsEndpoint, self).__init__() self.account_skills = None self.family_settings = None self.etag_manager: ETagManager = ETagManager( self.config["SELENE_CACHE"], self.config ) @property def setting_repository(self): """Only instantiate the SkillSettingsRepository if needed.""" if self._setting_repository is None: self._setting_repository = SkillSettingRepository(self.db) return self._setting_repository def get(self, skill_family_name): """Process an HTTP GET request""" self._authenticate() self.family_settings = self.setting_repository.get_family_settings( self.account.id, skill_family_name ) self._parse_selection_options() response_data = self._build_response_data() # The response object is manually built here to bypass the # camel case conversion so settings are displayed correctly return Response( response=json.dumps(response_data), status=HTTPStatus.OK, content_type="application/json", ) def _parse_selection_options(self): """Parse the dropdown options string into a list of options. Drop-down options are defined in a skill's settingsmeta.json as such: