chiark / gitweb /
build/checkupdates/update: log current fdroiddata commit to wiki
[fdroidserver.git] / fdroidserver / update.py
index 782d18fcf356b867e80f22022fe543d7b0bece9e..c22ac0f32b70d6add7f64a2367a24ef0e6091761 100644 (file)
@@ -53,15 +53,13 @@ UNSET_VERSION_CODE = -0x100000000
 APK_NAME_PAT = re.compile(".*name='([a-zA-Z0-9._]*)'.*")
 APK_VERCODE_PAT = re.compile(".*versionCode='([0-9]*)'.*")
 APK_VERNAME_PAT = re.compile(".*versionName='([^']*)'.*")
-APK_LABEL_PAT = re.compile(".*label='(.*?)'(\n| [a-z]*?=).*")
-APK_ICON_PAT = re.compile(".*application-icon-([0-9]+):'([^']+?)'.*")
-APK_ICON_PAT_NODPI = re.compile(".*icon='([^']+?)'.*")
+APK_LABEL_ICON_PAT = re.compile(".*\s+label='(.*)'\s+icon='(.*)'")
 APK_SDK_VERSION_PAT = re.compile(".*'([0-9]*)'.*")
 APK_PERMISSION_PAT = \
     re.compile(".*(name='(?P<name>.*?)')(.*maxSdkVersion='(?P<maxSdkVersion>.*?)')?.*")
 APK_FEATURE_PAT = re.compile(".*name='([^']*)'.*")
 
-screen_densities = ['640', '480', '320', '240', '160', '120']
+screen_densities = ['65534', '640', '480', '320', '240', '160', '120']
 screen_resolutions = {
     "xxxhdpi": '640',
     "xxhdpi": '480',
@@ -96,9 +94,10 @@ def px_to_dpi(px):
 
 
 def get_icon_dir(repodir, density):
-    if density == '0':
+    if density == '0' or density == '65534':
         return os.path.join(repodir, "icons")
-    return os.path.join(repodir, "icons-%s" % density)
+    else:
+        return os.path.join(repodir, "icons-%s" % density)
 
 
 def get_icon_dirs(repodir):
@@ -321,7 +320,21 @@ def update_wiki(apps, sortedids, apks):
                     logging.error("...FAILED to create page '{0}': {1}".format(pagename, e))
 
     # Purge server cache to ensure counts are up to date
-    site.pages['Repository Maintenance'].purge()
+    site.Pages['Repository Maintenance'].purge()
+
+    # Write a page with the last build log for this version code
+    wiki_page_path = 'update_' + time.strftime('%s', start_timestamp)
+    newpage = site.Pages[wiki_page_path]
+    txt = ''
+    txt += "* command line: <code>" + ' '.join(sys.argv) + "</code>\n"
+    txt += "* started at " + common.get_wiki_timestamp(start_timestamp) + '\n'
+    txt += "* completed at " + common.get_wiki_timestamp() + '\n'
+    txt += common.get_git_describe_link()
+    txt += "\n\n"
+    txt += common.get_android_tools_version_log()
+    newpage.save(txt, summary='Run log')
+    newpage = site.Pages['update']
+    newpage.save('#REDIRECT [[' + wiki_page_path + ']]', summary='Update redirect')
 
 
 def delete_disabled_builds(apps, apkcache, repodirs):
@@ -1035,10 +1048,10 @@ def scan_apk(apk_file):
         'antiFeatures': set(),
     }
 
-    if SdkToolsPopen(['aapt', 'version'], output=False):
-        scan_apk_aapt(apk, apk_file)
-    else:
+    if common.use_androguard():
         scan_apk_androguard(apk, apk_file)
+    else:
+        scan_apk_aapt(apk, apk_file)
 
     # Get the signature, or rather the signing key fingerprints
     logging.debug('Getting signature of {0}'.format(os.path.basename(apk_file)))
@@ -1055,7 +1068,9 @@ def scan_apk(apk_file):
 
     if 'minSdkVersion' not in apk:
         logging.warning("No SDK version information found in {0}".format(apk_file))
-        apk['minSdkVersion'] = 1
+        apk['minSdkVersion'] = 3  # aapt defaults to 3 as the min
+    if 'targetSdkVersion' not in apk:
+        apk['targetSdkVersion'] = apk['minSdkVersion']
 
     # Check for known vulnerabilities
     if has_known_vulnerability(apk_file):
@@ -1064,6 +1079,27 @@ def scan_apk(apk_file):
     return apk
 
 
+def _get_apk_icons_src(apkfile, icon_name):
+    """Extract the paths to the app icon in all available densities
+
+    """
+    icons_src = dict()
+    density_re = re.compile('^res/(.*)/' + icon_name + '\.(png|xml)$')
+    with zipfile.ZipFile(apkfile) as zf:
+        for filename in zf.namelist():
+            m = density_re.match(filename)
+            if m:
+                folder = m.group(1).split('-')
+                if len(folder) > 1:
+                    density = screen_resolutions[folder[1]]
+                else:
+                    density = '160'
+                icons_src[density] = m.group(0)
+    if icons_src.get('-1') is None:
+        icons_src['-1'] = icons_src['160']
+    return icons_src
+
+
 def scan_apk_aapt(apk, apkfile):
     p = SdkToolsPopen(['aapt', 'dump', 'badging', apkfile], output=False)
     if p.returncode != 0:
@@ -1076,6 +1112,7 @@ def scan_apk_aapt(apk, apkfile):
         else:
             logging.error(_("Failed to get apk information, skipping {path}").format(path=apkfile))
         raise BuildException(_("Invalid APK"))
+    icon_name = None
     for line in p.output.splitlines():
         if line.startswith("package:"):
             try:
@@ -1085,25 +1122,13 @@ def scan_apk_aapt(apk, apkfile):
             except Exception as e:
                 raise FDroidException("Package matching failed: " + str(e) + "\nLine was: " + line)
         elif line.startswith("application:"):
-            apk['name'] = re.match(APK_LABEL_PAT, line).group(1)
-            # Keep path to non-dpi icon in case we need it
-            match = re.match(APK_ICON_PAT_NODPI, line)
-            if match:
-                apk['icons_src']['-1'] = match.group(1)
-        elif line.startswith("launchable-activity:"):
+            m = re.match(APK_LABEL_ICON_PAT, line)
+            if m:
+                apk['name'] = m.group(1)
+                icon_name = os.path.splitext(os.path.basename(m.group(2)))[0]
+        elif not apk.get('name') and line.startswith("launchable-activity:"):
             # Only use launchable-activity as fallback to application
-            if not apk['name']:
-                apk['name'] = re.match(APK_LABEL_PAT, line).group(1)
-            if '-1' not in apk['icons_src']:
-                match = re.match(APK_ICON_PAT_NODPI, line)
-                if match:
-                    apk['icons_src']['-1'] = match.group(1)
-        elif line.startswith("application-icon-"):
-            match = re.match(APK_ICON_PAT, line)
-            if match:
-                density = match.group(1)
-                path = match.group(2)
-                apk['icons_src'][density] = path
+            apk['name'] = re.match(APK_LABEL_ICON_PAT, line).group(1)
         elif line.startswith("sdkVersion:"):
             m = re.match(APK_SDK_VERSION_PAT, line)
             if m is None:
@@ -1111,9 +1136,6 @@ def scan_apk_aapt(apk, apkfile):
                               + ' is not a valid minSdkVersion!')
             else:
                 apk['minSdkVersion'] = m.group(1)
-                # if target not set, default to min
-                if 'targetSdkVersion' not in apk:
-                    apk['targetSdkVersion'] = m.group(1)
         elif line.startswith("targetSdkVersion:"):
             m = re.match(APK_SDK_VERSION_PAT, line)
             if m is None:
@@ -1157,6 +1179,7 @@ def scan_apk_aapt(apk, apkfile):
                 if feature.startswith("android.feature."):
                     feature = feature[16:]
                 apk['features'].add(feature)
+    apk['icons_src'] = _get_apk_icons_src(apkfile, icon_name)
 
 
 def scan_apk_androguard(apk, apkfile):
@@ -1195,27 +1218,14 @@ def scan_apk_androguard(apk, apkfile):
 
     if apkobject.get_max_sdk_version() is not None:
         apk['maxSdkVersion'] = apkobject.get_max_sdk_version()
-    apk['minSdkVersion'] = apkobject.get_min_sdk_version()
-    apk['targetSdkVersion'] = apkobject.get_target_sdk_version()
+    if apkobject.get_min_sdk_version() is not None:
+        apk['minSdkVersion'] = apkobject.get_min_sdk_version()
+    if apkobject.get_target_sdk_version() is not None:
+        apk['targetSdkVersion'] = apkobject.get_target_sdk_version()
 
     icon_id = int(apkobject.get_element("application", "icon").replace("@", "0x"), 16)
     icon_name = arsc.get_id(apk['packageName'], icon_id)[1]
-
-    density_re = re.compile("^res/(.*)/" + icon_name + ".*$")
-
-    for file in apkobject.get_files():
-        d_re = density_re.match(file)
-        if d_re:
-            folder = d_re.group(1).split('-')
-            if len(folder) > 1:
-                resolution = folder[1]
-            else:
-                resolution = 'mdpi'
-            density = screen_resolutions[resolution]
-            apk['icons_src'][density] = d_re.group(0)
-
-    if apk['icons_src'].get('-1') is None:
-        apk['icons_src']['-1'] = apk['icons_src']['160']
+    apk['icons_src'] = _get_apk_icons_src(apkfile, icon_name)
 
     arch_re = re.compile("^lib/(.*)/.*$")
     arch = set([arch_re.match(file).group(1) for file in apkobject.get_files() if arch_re.match(file)])
@@ -1225,33 +1235,41 @@ def scan_apk_androguard(apk, apkfile):
 
     xml = apkobject.get_android_manifest_xml()
 
-    for item in xml.getElementsByTagName('uses-permission'):
-        name = str(item.getAttribute("android:name"))
-        maxSdkVersion = item.getAttribute("android:maxSdkVersion")
-        maxSdkVersion = None if maxSdkVersion is '' else int(maxSdkVersion)
+    for item in xml.findall('uses-permission'):
+        name = str(item.attrib['{' + xml.nsmap['android'] + '}name'])
+        maxSdkVersion = item.attrib.get('{' + xml.nsmap['android'] + '}maxSdkVersion')
+        maxSdkVersion = int(maxSdkVersion) if maxSdkVersion else None
+        permission = UsesPermission(
+            name,
+            maxSdkVersion
+        )
+        apk['uses-permission'].append(permission)
+    for name, maxSdkVersion in apkobject.get_uses_implied_permission_list():
         permission = UsesPermission(
             name,
             maxSdkVersion
         )
         apk['uses-permission'].append(permission)
 
-    for item in xml.getElementsByTagName('uses-permission-sdk-23'):
-        name = str(item.getAttribute("android:name"))
-        maxSdkVersion = item.getAttribute("android:maxSdkVersion")
-        maxSdkVersion = None if maxSdkVersion is '' else int(maxSdkVersion)
+    for item in xml.findall('uses-permission-sdk-23'):
+        name = str(item.attrib['{' + xml.nsmap['android'] + '}name'])
+        maxSdkVersion = item.attrib.get('{' + xml.nsmap['android'] + '}maxSdkVersion')
+        maxSdkVersion = int(maxSdkVersion) if maxSdkVersion else None
         permission_sdk_23 = UsesPermissionSdk23(
             name,
             maxSdkVersion
         )
         apk['uses-permission-sdk-23'].append(permission_sdk_23)
 
-    for item in xml.getElementsByTagName('uses-feature'):
-        feature = str(item.getAttribute("android:name"))
+    for item in xml.findall('uses-feature'):
+        feature = str(item.attrib['{' + xml.nsmap['android'] + '}name'])
         if feature != "android.hardware.screen.portrait" \
                 and feature != "android.hardware.screen.landscape":
             if feature.startswith("android.feature."):
                 feature = feature[16:]
-        apk['features'].append(feature)
+        required = item.attrib.get('{' + xml.nsmap['android'] + '}required')
+        if required is None or required == 'true':
+            apk['features'].append(feature)
 
 
 def process_apk(apkcache, apkfilename, repodir, knownapks, use_date_from_apk=False,
@@ -1299,7 +1317,7 @@ def process_apk(apkcache, apkfilename, repodir, knownapks, use_date_from_apk=Fal
             return True, None, False
 
         # Check for debuggable apks...
-        if common.isApkAndDebuggable(apkfile):
+        if common.is_apk_and_debuggable(apkfile):
             logging.warning('{0} is set to android:debuggable="true"'.format(apkfile))
 
         if options.rename_apks:
@@ -1364,7 +1382,7 @@ def process_apk(apkcache, apkfilename, repodir, knownapks, use_date_from_apk=Fal
                                 .format(apkfilename=apkfile) + str(e))
 
         # extract icons from APK zip file
-        iconfilename = "%s.%s.png" % (apk['packageName'], apk['versionCode'])
+        iconfilename = "%s.%s" % (apk['packageName'], apk['versionCode'])
         try:
             empty_densities = extract_apk_icons(iconfilename, apk, apkzip, repodir)
         finally:
@@ -1429,10 +1447,12 @@ def process_apks(apkcache, repodir, knownapks, use_date_from_apk=False):
 
 
 def extract_apk_icons(icon_filename, apk, apkzip, repo_dir):
-    """
-    Extracts icons from the given APK zip in various densities,
-    saves them into given repo directory
-    and stores their names in the APK metadata dictionary.
+    """Extracts PNG icons from an APK with the supported pixel densities
+
+    Extracts icons from the given APK zip in various densities, saves
+    them into given repo directory and stores their names in the APK
+    metadata dictionary.  If the icon is an XML icon, then this tries
+    to find PNG icon that can replace it.
 
     :param icon_filename: A string representing the icon's file name
     :param apk: A populated dictionary containing APK metadata.
@@ -1440,7 +1460,17 @@ def extract_apk_icons(icon_filename, apk, apkzip, repo_dir):
     :param apkzip: An opened zipfile.ZipFile of the APK file
     :param repo_dir: The directory of the APK's repository
     :return: A list of icon densities that are missing
+
     """
+    res_name_re = re.compile(r'res/(drawable|mipmap)-(x*[hlm]dpi|anydpi).*/(.*)_[0-9]+dp.(png|xml)')
+    pngs = dict()
+    for f in apkzip.namelist():
+        m = res_name_re.match(f)
+        if m and m.group(4) == 'png':
+            density = screen_resolutions[m.group(2)]
+            pngs[m.group(3) + '/' + density] = m.group(0)
+
+    icon_type = None
     empty_densities = []
     for density in screen_densities:
         if density not in apk['icons_src']:
@@ -1448,69 +1478,79 @@ def extract_apk_icons(icon_filename, apk, apkzip, repo_dir):
             continue
         icon_src = apk['icons_src'][density]
         icon_dir = get_icon_dir(repo_dir, density)
-        icon_dest = os.path.join(icon_dir, icon_filename)
+        icon_type = '.png'
 
         # Extract the icon files per density
         if icon_src.endswith('.xml'):
-            png = os.path.basename(icon_src)[:-4] + '.png'
-            for f in apkzip.namelist():
-                if f.endswith(png):
-                    m = re.match(r'res/(drawable|mipmap)-(x*[hlm]dpi).*/', f)
-                    if m and screen_resolutions[m.group(2)] == density:
-                        icon_src = f
+            m = res_name_re.match(icon_src)
+            if m:
+                name = pngs.get(m.group(3) + '/' + str(density))
+                if name:
+                    icon_src = name
             if icon_src.endswith('.xml'):
                 empty_densities.append(density)
-                continue
+                icon_type = '.xml'
+        icon_dest = os.path.join(icon_dir, icon_filename + icon_type)
+
         try:
             with open(icon_dest, 'wb') as f:
                 f.write(get_icon_bytes(apkzip, icon_src))
-            apk['icons'][density] = icon_filename
+            apk['icons'][density] = icon_filename + icon_type
         except (zipfile.BadZipFile, ValueError, KeyError) as e:
             logging.warning("Error retrieving icon file: %s %s", icon_dest, e)
             del apk['icons_src'][density]
             empty_densities.append(density)
 
+    # '-1' here is a remnant of the parsing of aapt output, meaning "no DPI specified"
     if '-1' in apk['icons_src']:
         icon_src = apk['icons_src']['-1']
-        icon_path = os.path.join(get_icon_dir(repo_dir, '0'), icon_filename)
+        icon_type = icon_src[-4:]
+        icon_path = os.path.join(get_icon_dir(repo_dir, '0'), icon_filename + icon_type)
         with open(icon_path, 'wb') as f:
             f.write(get_icon_bytes(apkzip, icon_src))
-        try:
-            im = Image.open(icon_path)
-            dpi = px_to_dpi(im.size[0])
-            for density in screen_densities:
-                if density in apk['icons']:
-                    break
-                if density == screen_densities[-1] or dpi >= int(density):
-                    apk['icons'][density] = icon_filename
-                    shutil.move(icon_path,
-                                os.path.join(get_icon_dir(repo_dir, density), icon_filename))
-                    empty_densities.remove(density)
-                    break
-        except Exception as e:
-            logging.warning(_("Failed reading {path}: {error}")
-                            .format(path=icon_path, error=e))
-        finally:
-            im.close()
+        if icon_type == '.png':
+            im = None
+            try:
+                im = Image.open(icon_path)
+                dpi = px_to_dpi(im.size[0])
+                for density in screen_densities:
+                    if density in apk['icons']:
+                        break
+                    if density == screen_densities[-1] or dpi >= int(density):
+                        apk['icons'][density] = icon_filename + icon_type
+                        shutil.move(icon_path,
+                                    os.path.join(get_icon_dir(repo_dir, density), icon_filename + icon_type))
+                        empty_densities.remove(density)
+                        break
+            except Exception as e:
+                logging.warning(_("Failed reading {path}: {error}")
+                                .format(path=icon_path, error=e))
+            finally:
+                if im and hasattr(im, 'close'):
+                    im.close()
 
     if apk['icons']:
-        apk['icon'] = icon_filename
+        apk['icon'] = icon_filename + icon_type
 
     return empty_densities
 
 
 def fill_missing_icon_densities(empty_densities, icon_filename, apk, repo_dir):
     """
-    Resize existing icons for densities missing in the APK to ensure all densities are available
+    Resize existing PNG icons for densities missing in the APK to ensure all densities are available
 
     :param empty_densities: A list of icon densities that are missing
     :param icon_filename: A string representing the icon's file name
     :param apk: A populated dictionary containing APK metadata. Needs to have 'icons' key
     :param repo_dir: The directory of the APK's repository
+
     """
+    icon_filename += '.png'
     # First try resizing down to not lose quality
     last_density = None
     for density in screen_densities:
+        if density == '65534':  # not possible to generate 'anydpi' from other densities
+            continue
         if density not in empty_densities:
             last_density = density
             continue
@@ -1757,6 +1797,7 @@ def create_metadata_from_template(apk):
 
 config = None
 options = None
+start_timestamp = time.gmtime()
 
 
 def main():