sensor:
  - platform: youtube
    channel_id: UClFSU9_bUb4Rc6OYfTt5SPw
  - platform: folder
    folder: /config/www/audio/youtube/pds
  - platform: folder
    folder: /config/www/audio/youtube

input_text:
  youtube_download_url:
    name: Youtube download URL
    icon: mdi:link
    initial: ""
  youtube_download_name:
    name: Youtube download name
    icon: mdi:format-letter-case
    initial: ""

shell_command:
  youtube_download: python3.7 /config/custom_scripts/youtube_download.py {{ url }} {{ name }} {{ folder }}

script:
  youtube_play_file:
    alias: Youtube · Play file
    sequence:
      - service: script.sonos_join_bedroom
      - service: media_player.play_media
        entity_id: media_player.master_bedroom
        data_template:
          media_content_id: >
            {{ states('sensor.sarah_url') }}/local{{ file.split('/config/www') | last }}
          media_content_type: "music"

  youtube_play_latest_pds:
    alias: Youtube · Play latest PDS
    sequence:
      - service: script.youtube_play_file
        data_template:
          file: "{{ state_attr('sensor.pds', 'file_list') | sort | last }}"


  youtube_download_selected:
    alias: Youtube · Download selected video
    sequence:
      - service: shell_command.youtube_download
        data_template:
          url: "{{ states('input_text.youtube_download_url') }}"
          name: "{{ states('input_text.youtube_download_name') }}"
      - service: input_text.set_value
        entity_id:
          - input_text.youtube_download_url
          - input_text.youtube_download_name
        data:
          value: ""

  youtube_download_and_play:
    alias: Youtube · Download and play selected video
    sequence:
      - service: shell_command.youtube_download
        data_template:
          url: "{{ states('input_text.youtube_download_url') }}"
          name: "{{ states('input_text.youtube_download_name') }}"

      - service: script.sonos_join_bedroom
      - service: media_player.play_media
        entity_id: media_player.master_bedroom
        data_template:
          media_content_id: >-
            {% set name = states('input_text.youtube_download_name') %}
            {{ states('sensor.sarah_url') }}/local/audio/youtube/{{ name }}.mp3
          media_content_type: "music"

      - service: input_text.set_value
        entity_id:
          - input_text.youtube_download_url
          - input_text.youtube_download_name
        data:
          value: ""

automation:
  - alias: Youtube · Download latest PDS
    trigger:
      platform: state
      entity_id: sensor.philip_defranco
    action:
      - service: shell_command.youtube_download
        data_template:
          url: "{{ state_attr('sensor.philip_defranco', 'url') }}"
          name: "{{ state_attr('sensor.philip_defranco', 'published')[0:10] }}"
          folder: "pds/"
      - service: script.say
        data:
          message: "Just wanted to let you know - a new PDS is available!"
