فهرست منبع

Refactor updater

Vassilis Panos 7 سال پیش
والد
کامیت
571dcb7299
4فایلهای تغییر یافته به همراه64 افزوده شده و 61 حذف شده
  1. 58 52
      smartir/__init__.py
  2. 2 3
      smartir/climate.py
  3. 2 3
      smartir/fan.py
  4. 2 3
      smartir/media_player.py

+ 58 - 52
smartir/__init__.py

@@ -16,13 +16,16 @@ from homeassistant.helpers.typing import ConfigType
 _LOGGER = logging.getLogger(__name__)
 
 DOMAIN = 'smartir'
-VERSION = '1.3.6'
+VERSION = '1.3.7'
 VERSION_URL = (
     "https://raw.githubusercontent.com/"
     "smartHomeHub/SmartIR/{}/version.json")
-REMOTE_BASE_DIR = (
+REMOTE_BASE_URL = (
     "https://raw.githubusercontent.com/"
     "smartHomeHub/SmartIR/{}/smartir/")
+COMPONENT_ABS_DIR = os.path.dirname(
+    os.path.abspath(__file__))
+
 CONF_CHECK_UPDATES = 'check_updates'
 CONF_UPDATE_BRANCH = 'update_branch'
 
@@ -55,58 +58,62 @@ async def async_setup(hass, config):
     return True
 
 async def _update(hass, branch, do_update=False, notify_if_latest=True):
-    has_errors = False
-
-    request = requests.get(VERSION_URL.format(branch), stream=True, timeout=10)
-    
-    if request.status_code == 200:
-        data = request.json()
-        last_version = data['version']
-        min_ha_version = data['minHAVersion']
-        release_notes = data['releaseNotes']
-        
-        if StrictVersion(last_version) <= StrictVersion(VERSION):
-            if notify_if_latest:
-                hass.components.persistent_notification.async_create(
-                    "You're already using the latest version!", title='SmartIR')
-            return
-            
-        if StrictVersion(current_ha_version) >= StrictVersion(min_ha_version):
-            if do_update:
-                files = data['files']
-                abspath = os.path.dirname(os.path.abspath(__file__))
-
-                for file in files:
-                    try:
-                        source = REMOTE_BASE_DIR.format(branch) + file
-                        dest = os.path.join(abspath, file)
-                        os.makedirs(os.path.dirname(dest), exist_ok=True)
-                        Helper.downloader(source, dest)
-                    except:
-                        _LOGGER.error("Error updating %s. Please update the file manually.", file)
-                        has_errors = True
-            else:
-                hass.components.persistent_notification.async_create(
-                    release_notes, title='SmartIR')
-
-        else:
+    try:
+        request = requests.get(VERSION_URL.format(branch), stream=True, timeout=10)
+    except:
+        _LOGGER.error("An error occurred while checking for updates. "
+                      "Please check your internet connection.")
+        return
+
+    if request.status_code != 200:
+        _LOGGER.error("Invalid response from the server while "
+                      "checking for a new version")
+        return
+
+    data = request.json()
+    last_version = data['version']
+    min_ha_version = data['minHAVersion']
+    release_notes = data['releaseNotes']
+
+    if StrictVersion(last_version) <= StrictVersion(VERSION):
+        if notify_if_latest:
             hass.components.persistent_notification.async_create(
-                "There is a new version of SmartIR, but it is **incompatible** "
-                "with your HA version. Please first update Home Assistant.", title='SmartIR')
+                "You're already using the latest version!", title='SmartIR')
+        return
+
+    if StrictVersion(current_ha_version) < StrictVersion(min_ha_version):
+        hass.components.persistent_notification.async_create(
+            "There is a new version of SmartIR, but it is **incompatible** "
+            "with your HA version. Please first update Home Assistant.", title='SmartIR')
+        return
+
+    if do_update is False:
+        hass.components.persistent_notification.async_create(
+            release_notes, title='SmartIR')
+        return
+
+    # Begin update
+    files = data['files']
+    has_errors = False
 
+    for file in files:
+        try:
+            source = REMOTE_BASE_URL.format(branch) + file
+            dest = os.path.join(COMPONENT_ABS_DIR, file)
+            os.makedirs(os.path.dirname(dest), exist_ok=True)
+            Helper.downloader(source, dest)
+        except:
+            has_errors = True
+            _LOGGER.error("Error updating %s. Please update the file manually.", file)
+
+    if has_errors:
+        hass.components.persistent_notification.async_create(
+            "There was an error updating one or more files of SmartIR. "
+            "Please check the logs for more information.", title='SmartIR')
     else:
-        _LOGGER.error("Invalid response from the server while checking for a new version")
-        has_errors = True
-
-    if do_update:
-        if has_errors:
-            hass.components.persistent_notification.async_create(
-                "There was an error updating SmartIR. Please "
-                "check the logs for more information.", title='SmartIR')
-        else:
-            hass.components.persistent_notification.async_create(
-                "Successfully updated to {}. Please restart Home Assistant."
-                .format(last_version), title='SmartIR')
+        hass.components.persistent_notification.async_create(
+            "Successfully updated to {}. Please restart Home Assistant."
+            .format(last_version), title='SmartIR')
 
 class Helper():
     @staticmethod
@@ -154,5 +161,4 @@ class Helper():
         remainder = (len(packet) + 4) % 16
         if remainder:
             packet += bytearray(16 - remainder)
-
         return packet

+ 2 - 3
smartir/climate.py

@@ -19,7 +19,7 @@ from homeassistant.core import callback, split_entity_id
 from homeassistant.helpers.event import async_track_state_change
 import homeassistant.helpers.config_validation as cv
 from homeassistant.helpers.restore_state import RestoreEntity
-from . import Helper
+from . import COMPONENT_ABS_DIR, Helper
 
 _LOGGER = logging.getLogger(__name__)
 
@@ -52,9 +52,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
 async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
     """Set up the IR Climate platform."""
     device_code = config.get(CONF_DEVICE_CODE)
-    hass_config_absdir = os.path.dirname(os.path.abspath(__file__))
     device_files_subdir = os.path.join('codes', 'climate')
-    device_files_absdir = os.path.join(hass_config_absdir, device_files_subdir)
+    device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
 
     if not os.path.isdir(device_files_absdir):
         os.makedirs(device_files_absdir)

+ 2 - 3
smartir/fan.py

@@ -18,7 +18,7 @@ from homeassistant.core import callback, split_entity_id
 from homeassistant.helpers.event import async_track_state_change
 import homeassistant.helpers.config_validation as cv
 from homeassistant.helpers.restore_state import RestoreEntity
-from . import Helper
+from . import COMPONENT_ABS_DIR, Helper
 
 _LOGGER = logging.getLogger(__name__)
 
@@ -40,9 +40,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
 async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
     """Set up the IR Fan platform."""
     device_code = config.get(CONF_DEVICE_CODE)
-    hass_config_absdir = os.path.dirname(os.path.abspath(__file__))
     device_files_subdir = os.path.join('codes', 'fan')
-    device_files_absdir = os.path.join(hass_config_absdir, device_files_subdir)
+    device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
 
     if not os.path.isdir(device_files_absdir):
         os.makedirs(device_files_absdir)

+ 2 - 3
smartir/media_player.py

@@ -18,7 +18,7 @@ from homeassistant.const import (
 from homeassistant.core import callback, split_entity_id
 import homeassistant.helpers.config_validation as cv
 from homeassistant.helpers.restore_state import RestoreEntity
-from . import Helper
+from . import COMPONENT_ABS_DIR, Helper
 
 _LOGGER = logging.getLogger(__name__)
 
@@ -40,9 +40,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
 async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
     """Set up the IR Media Player platform."""
     device_code = config.get(CONF_DEVICE_CODE)
-    hass_config_absdir = os.path.dirname(os.path.abspath(__file__))
     device_files_subdir = os.path.join('codes', 'media_player')
-    device_files_absdir = os.path.join(hass_config_absdir, device_files_subdir)
+    device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
 
     if not os.path.isdir(device_files_absdir):
         os.makedirs(device_files_absdir)