コード例 #1
0
def runSpecial(sdk, srcDir, destDir, sdkConfigFile, XcodeProject):
    print "[runSpecial] sdk is [%s]" % sdk
    print "[srcDir] is = ", srcDir
    print "[destDir] is = ", destDir
    print "[sdkConfigFile] is = ", sdkConfigFile

    phases = XcodeProject.get_build_phases_by_name('XCBuildConfiguration')
    base = 'buildSettings'
    key = "INFOPLIST_FILE"
    for build_phase in phases:
        if base in build_phase and key in build_phase[base]:
            infoPlist = build_phase[base][key]
    if infoPlist is not None:
        infoPlist = os.path.join(destDir, infoPlist)
        plist = biplist.readPlist(infoPlist)
    specialScript = os.path.join(srcDir, "special.py")
    if os.path.exists(specialScript):
        sysPath = copy.deepcopy(sys.path)
        sys.path.append(os.path.abspath(srcDir))
        import special
        ret = special.run(sdk, sdkConfigFile, os.path.abspath(destDir), plist,
                          XcodeProject)

        if ret:
            print "[ %s ] Error! run special script" % sdk
            return 1
        del sys.modules["special"]
        if infoPlist is not None:
            biplist.writePlist(plist, infoPlist, False)
        sys.path = sysPath
    return 0
コード例 #2
0
def ios_sim_location_authorize(bundle_id, on_off='on'):
    '''
    Give location authorization to app according to the Bundle ID.
    Change the .plist file in simulator folder.
    '''

    tmp = os.path.join(os.path.expanduser("~/Library"), "Application Support", "iPhone Simulator", "*.*", "Library")
    paths = glob.glob(tmp)

    for sim_dir in paths:
        sim_dir = os.path.join(sim_dir, 'Caches')
        if not os.path.exists(sim_dir):
            os.mkdir(sim_dir)
        sim_dir = os.path.join(sim_dir, 'locationd')
        if not os.path.exists(sim_dir):
            os.mkdir(sim_dir)

        existing_path = os.path.join(sim_dir, 'clients.plist')
        if os.path.exists(existing_path):
            plist = biplist.readPlist(existing_path)
        else:
            plist = {}

        if bundle_id not in plist:
            plist[bundle_id] = {}

        plist[bundle_id]["BundleId"] = bundle_id
        plist[bundle_id]["Authorized"] = True if on_off == "on" else False
        plist[bundle_id]["LocationTimeStarted"] = 0

        biplist.writePlist(plist, existing_path)
コード例 #3
0
def write_plist_to_file(deserialised_plist, output_path):
    #Using plistLib to write plist
    out_file = None
    try:
        print('Writing out .. ' + output_path)
        out_file = open(output_path, 'wb')
        try:
            plistlib.dump(deserialised_plist,
                          out_file,
                          fmt=plistlib.FMT_BINARY)
            out_file.close()
            return True
        except (TypeError, OverflowError, OSError) as ex:
            out_file.close()
            print('Had an exception (error)')
            traceback.print_exc()
    except OSError as ex:
        print('Error opening file for writing: Error={} Path={}'.format(
            output_path, str(ex)))
    # Try using biplist
    try:
        print('Writing out (using biplist) .. ' + output_path)
        biplist.writePlist(deserialised_plist, output_path)
        return True
    except (biplist.InvalidPlistException, biplist.NotBinaryPlistException,
            OSError) as ex:
        print('Had an exception (error)')
        traceback.print_exc()
コード例 #4
0
def modifyInfoPlist(sdk, srcDir, destDir, XcodeProject):
    configData = getForXcodeConfigFile(sdk)
    if not configData:
        return 1

    if configData.has_key("bundleId") or configData.has_key("infoSetting"):
        infoPlist = getInfoPlistPath(XcodeProject)
        if not infoPlist:
            print "[ %s ] Error! doesnt find info.plist" % sdk
            return 1

        infoPlist = os.path.join(destDir, infoPlist)
        if not os.path.exists(infoPlist):
            print("[%s] Error! info.plist file not exist , path = %s\n" %
                  (sdk, infoPlist))
            return 1

        plist = biplist.readPlist(infoPlist)

        if configData.has_key("bundleId"):
            newBundleId = configData["bundleId"]
            ret = modifyBundleId(sdk, newBundleId, plist, XcodeProject)
            if ret:
                return 1

        if configData.has_key("infoSetting"):
            infoSettings = configData["infoSetting"]
            ret = addSettingsToInfoPlist(sdk, infoSettings, plist)
            if ret:
                return 1

        biplist.writePlist(plist, infoPlist, False)

    return 0
コード例 #5
0
ファイル: chromify.py プロジェクト: s-heiden/gists
def main():
    home_path = os.environ['HOME']

    safari_path = home_path + "/Library/Safari/Bookmarks.plist"
    chrome_path = home_path + "/Library/Application Support/Google/Chrome/Default/Bookmarks"

    if not os.path.exists(safari_path):
        print "[Error] The bookmark files of safari do not exist! path: " + safari_path
        return

    if not os.path.exists(chrome_path):
        print "[Error] The bookmark files of chrome do not exist! path: " + chrome_path
        return

    bookmark_manager = BookmarkManager()

    with open(chrome_path, "r") as f:
        chrome_info = json.load(f)
        print chrome_info
        bookmark_manager.load_from_chrome(chrome_info)

    safari_info = readPlist(safari_path)
    bookmark_manager.save_to_safari(safari_info)
    # create backup
    shutil.copyfile(safari_path, safari_path + ".bak")
    writePlist(safari_info, safari_path)
    print "Done! %i bookmarks have been imported" % bookmark_manager.get_number(
    )
コード例 #6
0
ファイル: main.py プロジェクト: gonejack/python-webarchive
async def scrape(client, url):
    tasks = []
    url_queue = Queue()

    archive = {
        'top': url,
        'seen': {},
        'items': []
    }
    await url_queue.put(url)

    def task_completed(future):
        exc = future.exception()
        if exc:
            log.error('Worker finished with error: {} '.format(exc), exc_info=True)

    for _ in range(CONCURRENCY):
        crawler_future = ensure_future(crawler(client, url_queue, archive))
        crawler_future.add_done_callback(task_completed)
        tasks.append(crawler_future)

    await wait_for(url_queue.join(), TIMEOUT)

    for task in tasks:
        task.cancel()
    client.close()

    webarchive = {
        'WebMainResource': archive['items'].pop(0),
        'WebSubresources': archive['items']
    }

    writePlist(webarchive, OUTPUT_FILENAME)
コード例 #7
0
ファイル: __init__.py プロジェクト: wooster/gitlogger
	def add_email(self, username, email):
		users = biplist.readPlist(self.user_file_path)
		user_info = users.get(username)
		if email not in user_info['email_addresses']:
			user_info['email_addresses'].append(email)
		users[username] = user_info
		biplist.writePlist(users, self.user_file_path)
コード例 #8
0
def main():
    global usage
    global use_as_library
    use_as_library = False
    if sys.version_info.major == 2:
        print(
            'ERROR-This will not work with python2. Please run again with python3!'
        )
        return
    argc = len(sys.argv)

    if argc < 2 or sys.argv[1].lower() == '-h':
        print(usage)
        return

    input_path = sys.argv[1]
    if not os.path.exists(input_path):
        print('Error, file does not exist! Check file path!\r\n')
        print(usage)
        return

    # All OK, process the file now
    try:
        f = open(input_path, 'rb')
        deserialised_plist = process_nsa_plist(input_path, f)
        output_path = input_path + '_deserialized.plist'
        print('Writing out .. ' + output_path)
        biplist.writePlist(deserialised_plist, output_path)
        f.close()
    except Exception as ex:
        print('Had an exception (error)')
        traceback.print_exc()

    print('Done !')
コード例 #9
0
ファイル: ibooks_api.py プロジェクト: gchehab/Apple_iBooks
 def commit(self):
     try:
         if self.has_changed > 0:
             if prefs['backup'] and not self.has_backup:
                 for filename in ['bookcatalog']:
                     if prefs['debug']:
                         print(
                             str(datetime.now()) + ": Backing up " +
                             filename)
                     copy2(prefs[filename], prefs[filename] + ".bkp")
                 self.has_backup = True
             self.__kill_ibooks()
             if prefs['debug']:
                 print(str(datetime.now()) + ": Commmiting library DB")
             self.__library_db.commit()
             if prefs['debug']:
                 print(str(datetime.now()) + ": Commmiting series DB")
             self.__series_db.commit()
             if prefs['debug']:
                 print(str(datetime.now()) + ": Commmiting plist catalog")
             writePlist(self.catalog,
                        self.IBOOKS_BKAGENT_CATALOG_FILE + ".tmp",
                        binary=False)
             move(self.IBOOKS_BKAGENT_CATALOG_FILE + ".tmp",
                  self.IBOOKS_BKAGENT_CATALOG_FILE)
             if prefs['debug']:
                 print(str(datetime.now()) + ": Commmit finished")
             self.has_changed = 0
     except Exception:
         print(sys.exc_info()[0])
         raise
コード例 #10
0
    def update_info_props(self, new_props):
        if self.orig_info is None:
            self.orig_info = copy.deepcopy(self.info)

        changed = False
        if ('CFBundleIdentifier' in new_props
                and 'CFBundleURLTypes' in self.info
                and 'CFBundleURLTypes' not in new_props):
            # The bundle identifier changed. Check CFBundleURLTypes for
            # CFBundleURLName values matching the old bundle
            # id if it's not being set explicitly
            old_bundle_id = self.info['CFBundleIdentifier']
            new_bundle_id = new_props['CFBundleIdentifier']
            for url_type in self.info['CFBundleURLTypes']:
                if 'CFBundleURLName' not in url_type:
                    continue
                if url_type['CFBundleURLName'] == old_bundle_id:
                    url_type['CFBundleURLName'] = new_bundle_id
                    changed = True

        for key, val in new_props.iteritems():
            is_new_key = key not in self.info
            if is_new_key or self.info[key] != val:
                if is_new_key:
                    log.warn("Adding new Info.plist key: {}".format(key))
                self.info[key] = val
                changed = True

        if changed:
            biplist.writePlist(self.info, self.info_path, binary=True)
        else:
            self.orig_info = None
コード例 #11
0
ファイル: plist.py プロジェクト: samurai-labs/macbuild
def do_plist(module, filename, values, backup=False):
    working_values = values
    changed = False

    try:
        f = open(filename)
        plist = biplist.readPlist(f)
    except IOError:
        plist = {}
    except biplist.InvalidPlistException:
        module.fail_json(msg="an invalid plist already exists")

    changed = not equal(plist, working_values)

    if changed and not module.check_mode:
        if backup:
            module.backup_local(filename)

        try:
            update(plist, working_values)
            plist_dir = os.path.dirname(filename)
            if not os.path.exists(plist_dir):
                os.makedirs(plist_dir)
            f = open(filename, 'w')
            biplist.writePlist(plist, f)
        except Exception as e:
            module.fail_json(msg="Can't change %s" % filename, error=str(e))

    return changed
コード例 #12
0
ファイル: bundle.py プロジェクト: lianz/isign
    def update_info_props(self, new_props):
        if self.orig_info is None:
            self.orig_info = copy.deepcopy(self.info)

        changed = False
        if ('CFBundleIdentifier' in new_props and
                'CFBundleURLTypes' in self.info and
                'CFBundleURLTypes' not in new_props):
            # The bundle identifier changed. Check CFBundleURLTypes for
            # CFBundleURLName values matching the old bundle
            # id if it's not being set explicitly
            old_bundle_id = self.info['CFBundleIdentifier']
            new_bundle_id = new_props['CFBundleIdentifier']
            for url_type in self.info['CFBundleURLTypes']:
                if 'CFBundleURLName' not in url_type:
                    continue
                if url_type['CFBundleURLName'] == old_bundle_id:
                    url_type['CFBundleURLName'] = new_bundle_id
                    changed = True

        for key, val in new_props.iteritems():
            is_new_key = key not in self.info
            if is_new_key or self.info[key] != val:
                if is_new_key:
                    log.warn("Adding new Info.plist key: {}".format(key))
                self.info[key] = val
                changed = True

        if changed:
            biplist.writePlist(self.info, self.info_path, binary=True)
        else:
            self.orig_info = None
コード例 #13
0
def _get_valid_nska_plist(f):
    '''Checks if there is an embedded NSKeyedArchiver plist as a data blob. On 
       ios, several files are like that. Also converts any xml based plist to 
       binary plist. Returns a file object representing a binary plist file and
       a plist object packaged as a tuple (file_obj, plist).
    '''
    f, plist = _verify_fix_plist_file(f)
    if isinstance(plist, bytes):  # If there is an embedded plist
        data = plist
        f = io.BytesIO(data)
        f, plist = _verify_fix_plist_file(f)
    f.seek(0)

    # Check if file to be returned is an XML plist
    header = f.read(8)
    f.seek(0)
    if header[0:6] != b'bplist':  # must be xml
        # Convert xml to binary (else ccl_bplist wont load!)
        tempfile = io.BytesIO()
        if sys.version_info >= (3, 9):
            _convert_CFUID_to_UID(plist, True)
            plistlib.dump(plist, tempfile, fmt=plistlib.FMT_BINARY)
        else:
            _convert_CFUID_to_UID(plist, False)
            biplist.writePlist(plist, tempfile)
        tempfile.seek(0)
        return tempfile, plist

    return f, plist
コード例 #14
0
ファイル: deserializer.py プロジェクト: ecm3321/MacForensics
def extract_nsa_plist(f):
    '''Return the embedded plist, if this is such a file.
       Sometimes there is a single data blob which then has 
       the NSKeyedArchiver plist in it.
    '''
    try:
        plist = biplist.readPlist(f)
        if isinstance(plist, bytes):
            data = plist
            f.close()
            f = io.BytesIO(data)
    except biplist.InvalidPlistException:
        print('Had an exception (error) trying to read plist using biplist')
        return None
    f.seek(0)

    # Check if file to be returned is an XML plist
    header = f.read(8)
    f.seek(0)
    if header[0:6] != b'bplist':  # must be xml
        # Convert xml to binary (else ccl_bplist wont load!)
        try:
            tempfile = io.BytesIO()
            plist = biplist.readPlist(f)
            ConvertCFUID_to_UID(plist)
            biplist.writePlist(plist, tempfile)
            f.close()
            tempfile.seek(0)
            return tempfile
        except biplist.InvalidPlistException:
            print('Had exception (error) trying to read plist using biplist')
            return None
    return f
コード例 #15
0
ファイル: todo2weekly.py プロジェクト: slegetank/WorkHelper
def getGerritAccountPass():
    global wiimu_account
    global wiimu_pass

    if os.path.exists(configPlistPath):
        configPlist = biplist.readPlist(configPlistPath)
        wiimu_account = configPlist.get('wiimuaccount', '')
        wiimu_pass = configPlist.get('wiimupass', '')
    else:
        configPlist = {'wiimuaccount': '', 'wiimupass': ''}
        biplist.writePlist(configPlist, configPlistPath)

    if len(wiimu_account) == 0 or len(wiimu_pass) == 0:
        print 'This is your first time use this.'
    while (len(wiimu_account) == 0 or len(wiimu_pass) == 0):
        tempAccount = raw_input('Please enter your Wiimu account:')
        tempPass = raw_input('Please enter your Wiimu pass:'******'https://sh.linkplay.com:8081/artifactory/api/security/encryptedPassword',
            auth=(tempAccount, tempPass))
        if response.status_code == 200:
            wiimu_account = tempAccount
            wiimu_pass = tempPass

            configPlist = biplist.readPlist(configPlistPath)
            configPlist['wiimuaccount'] = wiimu_account
            configPlist['wiimupass'] = wiimu_pass
            biplist.writePlist(configPlist, configPlistPath)
            print 'Login success! Enjoy!'
        else:
            print 'Wrong account or password, please enter again'
コード例 #16
0
ファイル: bundle.py プロジェクト: dweinstein/isign
 def create_entitlements(self, team_id):
     entitlements = {
         "keychain-access-groups": [team_id + '.*'],
         "com.apple.developer.team-identifier": team_id,
         "application-identifier": team_id + '.*',
         "get-task-allow": True
     }
     biplist.writePlist(entitlements, self.entitlements_path, binary=False)
コード例 #17
0
def setPlist(path, value):
    plist = biplist.readPlist(path)
    mergeDict(plist, value)
    try:
        biplist.writePlist(plist, path, False)
    except Exception as e:
        print
        "Something bad happened:", e
コード例 #18
0
ファイル: bundle.py プロジェクト: dweinstein/isign
 def create_entitlements(self, team_id):
     entitlements = {
         "keychain-access-groups": [team_id + '.*'],
         "com.apple.developer.team-identifier": team_id,
         "application-identifier": team_id + '.*',
         "get-task-allow": True
     }
     biplist.writePlist(entitlements, self.entitlements_path, binary=False)
コード例 #19
0
def init_export_options():
    global bundle_id
    bar.log("Read project configuration...")
    team_id = None
    signing_style = 'Automatic'
    strip_swift_symbols = False
    bitcode_enable = False
    code = os.system(
        'xcodebuild -showBuildSettings| tee %s/settings.log >/dev/null 2>&1' %
        log_dir)
    if code != 0:
        error('Damn! Check the log %s/settings.log' % log_dir)
    f = open('%s/settings.log' % log_dir, 'r')
    settings_info = ''
    for line in f.readlines():
        settings_info += line
    s = re.search(r'PRODUCT_BUNDLE_IDENTIFIER = (.+)\n', settings_info)
    result = s.group(1)
    if len(result) > 0:
        bundle_id = result
    else:
        error('[Error]Please input the project\'s bundle id.')

    if os.path.isfile(exportOptionsPlist):
        return
    s = re.search(r'DEVELOPMENT_TEAM = (.+)\n', settings_info)

    result = s.group(1)
    if len(result) > 0:
        team_id = result
    else:
        error('[Error]Development team is invalid.')
    s = re.search(r'CODE_SIGN_STYLE = (.+)\n', settings_info)
    result = s.group(1)
    if len(result) > 0:
        signing_style = result
    s = re.search(r'STRIP_SWIFT_SYMBOLS = (.+)\n', settings_info)
    result = s.group(1)
    if len(result) > 0:
        strip_swift_symbols = result
    s = re.search(r'ENABLE_BITCODE = (.+)\n', settings_info)
    result = s.group(1)
    if len(result) > 0:
        bitcode_enable = result
    f.close()

    if sys.version_info < (3, 0):
        from biplist import writePlist
    plist = {
        'compileBitcode': bitcode_enable,
        'method': 'ad-hoc',
        'signingStyle': signing_style.lower(),
        'stripSwiftSymbols': strip_swift_symbols,
        'teamID': team_id,
        'thinning': '<none>',
    }
    bar.log("Init export options plist...")
    writePlist(plist, exportOptionsPlist)
コード例 #20
0
def delPlist(key, path):
    plist = biplist.readPlist(path)
    if plist.has_key(key):
        del plist[key]
    try:
        biplist.writePlist(plist, path, False)
    except Exception as e:
        print
        "Something bad happened:", e
コード例 #21
0
ファイル: build_steps.py プロジェクト: homerjam/file2
def set_in_biplist(build_params, filename, key, value):
	if isinstance(value, str) or isinstance(value, unicode):
		value = pystache.render(value, build_params['app_config'])
	
	found_files = glob.glob(filename)
	for found_file in found_files:
		plist = biplist.readPlist(found_file)
		plist = utils.transform(plist, key, lambda _: value, allow_set=True)
		biplist.writePlist(plist, found_file)
コード例 #22
0
ファイル: project.py プロジェクト: ZXLLPW/src
 def writeConfigPlist(self):
     fileName = self.configFileName
     exceptLongKey = self.configFileLongKey()
     commaDic = readCommaFile(fileName,exceptLongKey)
     print('----commaDic----%s----' % commaDic)
     files = self.configFiles()
     for file in files:
         print('----file----%s---' % file)
         biplist.writePlist(commaDic,file)
コード例 #23
0
def set_in_biplist(build_params, filename, key, value):
    if isinstance(value, str) or isinstance(value, unicode):
        value = pystache.render(value, build_params['app_config'])

    found_files = glob.glob(filename)
    for found_file in found_files:
        plist = biplist.readPlist(found_file)
        plist = utils.transform(plist, key, lambda _: value, allow_set=True)
        biplist.writePlist(plist, found_file)
コード例 #24
0
 def create_status_plist(self):
     #Creating Status file for backup
     statusDict = { 'UUID': '82D108D4-521C-48A5-9C42-79C5E654B98F', #FixMe We Should USE an UUID generator uuid.uuid3(uuid.NAMESPACE_DNS, hostname)
                'BackupState': 'new', 
                'IsFullBackup': True, 
                'Version': '2.4', 
                'Date': datetime.datetime.fromtimestamp(mktime(gmtime())),
                'SnapshotState': 'finished'
              }
     writePlist(statusDict,self.check_filename("Status.plist"))
コード例 #25
0
 def create_status_plist(self,fullBackup=True):
     #Creating Status file for backup
     statusDict = { 'UUID': str(uuid4()).upper(),
                'BackupState': 'new',
                'IsFullBackup': fullBackup,
                'Version': '2.4',
                'Date': datetime.datetime.fromtimestamp(mktime(gmtime())),
                'SnapshotState': 'finished'
              }
     writePlist(statusDict,self.check_filename("Status.plist"))
コード例 #26
0
ファイル: core.py プロジェクト: ohlookemus/alp
def writePlist(obj, path, binary=False):
    if not os.path.isabs(path):
        path = storage(path)
        
    if binary:
        biplist.writePlist(obj, path, binary)
    
    s = biplist.writePlistToString(obj)
    with codecs.open(path, "w", "utf-8") as f:
        f.write(s)
コード例 #27
0
def set_apptentive_distribution_key():
	# Update the Info.plist in the ApptentiveResources.bundle.
	bundle_plist_path = os.path.join(os.getcwd(), "assets/ApptentiveResources.bundle/Info.plist")
	if not os.path.exists(bundle_plist_path):
		print("Unable to find bundle Info.plist at %s" % bundle_plist_path)
		return False
	plist = biplist.readPlist(bundle_plist_path)
	plist_key = "ATInfoDistributionKey"
	plist[plist_key] = "Titanium"
	biplist.writePlist(plist, bundle_plist_path)
コード例 #28
0
 def create_status_plist(self,fullBackup=True):
     #Creating Status file for backup
     statusDict = { 'UUID': str(uuid4()).upper(),
                'BackupState': 'new',
                'IsFullBackup': fullBackup,
                'Version': '2.4',
                'Date': datetime.datetime.fromtimestamp(mktime(gmtime())),
                'SnapshotState': 'finished'
              }
     writePlist(statusDict,self.check_filename("Status.plist"))
コード例 #29
0
ファイル: bundle.py プロジェクト: iMokhles/isign
    def create_entitlements(self, provision_path):
        bundle_id = self.info['CFBundleIdentifier']
        provision_file = file(provision_path,'r')
        provision_content = provision_file.read()
        provision_file.close()
        start_index = provision_content.find('<?xml version="1.0" encoding="UTF-8"?>')
        end_index = provision_content.find('</plist>')
        provision_info = plistlib.readPlistFromString(provision_content[start_index:end_index+8])
        entitlements = provision_info['Entitlements']

        biplist.writePlist(entitlements, self.entitlements_path, binary=False)
コード例 #30
0
def set_apptentive_distribution_key():
    # Update the Info.plist in the ApptentiveResources.bundle.
    bundle_plist_path = os.path.join(
        os.getcwd(), "assets/ApptentiveResources.bundle/Info.plist")
    if not os.path.exists(bundle_plist_path):
        print("Unable to find bundle Info.plist at %s" % bundle_plist_path)
        return False
    plist = biplist.readPlist(bundle_plist_path)
    plist_key = "ATInfoDistributionKey"
    plist[plist_key] = "Titanium"
    biplist.writePlist(plist, bundle_plist_path)
コード例 #31
0
ファイル: build_steps.py プロジェクト: homerjam/file2
def ios_add_background_mode(build_params, mode, filename='ForgeInspector/ForgeInspector-Info.plist'):
	if isinstance(mode, str) or isinstance(mode, unicode):
		mode = pystache.render(mode, build_params['app_config'])
	
	found_files = glob.glob(filename)
	for found_file in found_files:
		plist = biplist.readPlist(found_file)
		if "UIBackgroundModes" in plist:
			plist["UIBackgroundModes"].append(mode)
		else:
			plist["UIBackgroundModes"] = [mode]
		biplist.writePlist(plist, found_file)
コード例 #32
0
ファイル: bundle.py プロジェクト: asionius/isign
 def create_entitlements(self, team_id, entitlements_bundleid):
     if not entitlements_bundleid:
         bundle_id = self.info['CFBundleIdentifier']
     else:
         bundle_id = entitlements_bundleid
     entitlements = {
         "keychain-access-groups": [team_id + '.' + bundle_id],
         "com.apple.developer.team-identifier": team_id,
         "application-identifier": team_id + '.' + bundle_id,
         "get-task-allow": True
     }
     biplist.writePlist(entitlements, self.entitlements_path, binary=False)
コード例 #33
0
 def create_status_plist(self, fullBackup=True):
     #Creating Status file for backup
     statusDict = {
         'UUID':
         '82D108D4-521C-48A5-9C42-79C5E654B98F',  #FixMe We Should USE an UUID generator uuid.uuid3(uuid.NAMESPACE_DNS, hostname)
         'BackupState': 'new',
         'IsFullBackup': fullBackup,
         'Version': '2.4',
         'Date': datetime.datetime.fromtimestamp(mktime(gmtime())),
         'SnapshotState': 'finished'
     }
     writePlist(statusDict, self.check_filename("Status.plist"))
コード例 #34
0
ファイル: build_steps.py プロジェクト: homerjam/file2
def ios_add_url_handler(build_params, scheme, filename='ForgeInspector/ForgeInspector-Info.plist'):
	if isinstance(scheme, str) or isinstance(scheme, unicode):
		scheme = pystache.render(scheme, build_params['app_config'])
	
	found_files = glob.glob(filename)
	for found_file in found_files:
		plist = biplist.readPlist(found_file)
		if "CFBundleURLTypes" in plist:
			plist["CFBundleURLTypes"][0]["CFBundleURLSchemes"].append(scheme)
		else:
			plist["CFBundleURLTypes"] = [{"CFBundleURLSchemes": [scheme]}]
		biplist.writePlist(plist, found_file)
コード例 #35
0
 def _refactor_xcode_plist(p):
     print('refactor:', p)
     plist = biplist.readPlist(p)
     # print(plist)
     Collect.safe_pop(plist, 'CFBundleIcons')
     Collect.safe_pop(plist, 'CFBundleIcons~ipad')
     Collect.safe_pop(plist, 'CFBundleSignature')
     Collect.safe_pop(plist, 'LSApplicationCategoryType')
     Collect.safe_pop(plist, 'UIPrerenderedIcon')
     Collect.safe_pop(plist, 'UIViewControllerBasedStatusBarAppearance')
     plist['UIRequiredDeviceCapabilities'] = ['armv7']
     biplist.writePlist(plist, p, binary=False)
コード例 #36
0
ファイル: bundle.py プロジェクト: asionius/isign
 def create_entitlements(self, team_id, entitlements_bundleid):
     if not entitlements_bundleid:
         bundle_id = self.info['CFBundleIdentifier']
     else:
         bundle_id = entitlements_bundleid
     entitlements = {
         "keychain-access-groups": [team_id + '.' + bundle_id],
         "com.apple.developer.team-identifier": team_id,
         "application-identifier": team_id + '.' + bundle_id,
         "get-task-allow": True
     }
     biplist.writePlist(entitlements, self.entitlements_path, binary=False)
コード例 #37
0
ファイル: app.py プロジェクト: anantgarg/orchardlab
        def generate():
            # Checkout the branch, fetch new commits and update submodules
            git = sh.git.bake(_cwd=wd)
            yield (x for x in [chr(127) * 1024 + '\nChecking out branch...\n'])
            yield git.checkout('-B', branch, '-t', 'origin/' + branch,
                    _iter=True, _out_bufsize=0)
            yield (x for x in ['Pulling from remote repository...\n'])
            yield git.pull('--ff-only', _iter=True)
            yield (x for x in ['Updating submodules...\n'])
            yield git.submodule('update', '--init',
                    _iter=True, _out_bufsize=0)

            # Do the build!
            yield (x for x in ['Starting build...\n'])
            xcodebuild = sh.xcodebuild.bake(_cwd=wd)
            yield xcodebuild.build('-configuration', 'Debug', '-arch', 'armv7',
                    '-sdk', 'iphoneos',
                    _iter=True, _out_bufsize=0)

            # Create the output folder structure if needed
            if not os.path.exists(output):
                os.makedirs(output)

            # Get the .app in the build output folder
            app_path = os.path.join(wd, glob.glob(os.path.join(wd,
                'build/Debug-iphoneos/*.app'))[0])

            # Package the .app to .ipa
            xcrun = sh.xcrun.bake(_cwd=wd)
            yield (x for x in ['Compiling app...\n'])
            yield xcrun('-sdk', 'iphoneos', 'PackageApplication', app_path,
                    '-o', os.path.join(output, 'application.ipa'),
                    _iter=True, _out_bufsize=0)

            # Write the .plist we'll need for downloading later
            yield (x for x in ['Writing plist...\n'])
            plist = biplist.readPlist(os.path.join(app_path, 'Info.plist'))
            data = {'items': [{
                'assets': [{
                    'kind': 'software-package',
                    'url': urlparse.urljoin(cherrypy.url(), 'application.ipa'),
                }],
                'metadata': {
                    'kind': 'software',
                    'bundle-identifier': plist['CFBundleIdentifier'],
                    'title': plist['CFBundleName']
                }
            }]}
            biplist.writePlist(data, os.path.join(output, 'application.plist'),
                    binary=False)

            yield (x for x in ['Done!\n'])
コード例 #38
0
def ios_add_url_handler(build_params,
                        scheme,
                        filename='ForgeInspector/ForgeInspector-Info.plist'):
    if isinstance(scheme, str) or isinstance(scheme, unicode):
        scheme = pystache.render(scheme, build_params['app_config'])

    found_files = glob.glob(filename)
    for found_file in found_files:
        plist = biplist.readPlist(found_file)
        if "CFBundleURLTypes" in plist:
            plist["CFBundleURLTypes"][0]["CFBundleURLSchemes"].append(scheme)
        else:
            plist["CFBundleURLTypes"] = [{"CFBundleURLSchemes": [scheme]}]
        biplist.writePlist(plist, found_file)
コード例 #39
0
def parseAPPFont():
    fontConfigPath = os.path.abspath(
        "%s/src/Resources/Fonts/fontConfig.json" % ROOTPATH)
    if (os.path.exists(fontConfigPath) == False):
        raise Exception('Not found config')
    load_dict = None
    with open(fontConfigPath) as load_f:
        load_dict = json.load(load_f)
    fonts = load_dict['fonts']
    fontDirPath = os.path.abspath(
        "%s/src/Resources/Fonts/Files" % ROOTPATH)
    projectName = getProjectName()
    plistPath = os.path.abspath(
        "%s/ios/%s/info.plist" % (ROOTPATH, projectName))
    infoPlist = readPlist(plistPath)

    oldAppUIFonts = infoPlist.get('UIAppFonts', [])
    newUIAppFonts = oldAppUIFonts[:]

    fontConfigText = 'export default {'
    for font in fonts:
        fileName = font['fileName']
        fontName = font['fontType']
        fontPath = os.path.join(fontDirPath, fileName)
        if os.path.exists(fontPath) == False:
            print('Not found font file:' + fontPath)
            continue
        postScriptName = getFontPostScriptName(fontPath)
        if postScriptName:
            lineText = '\n    %s:"%s",' % (fontName, postScriptName)
            fontConfigText += lineText
            fileType = os.path.splitext(fontPath)[-1]
            newFontName = postScriptName + fileType
            if newFontName not in newUIAppFonts:
                newUIAppFonts.append(newFontName)
            addFontToIOS(fontPath, postScriptName)
            addFontToAndroid(fontPath, postScriptName)

    fontConfigText += '\n}'
    cfPath = os.path.abspath(
        "%s/src/Configs/ConfigFiles/fontConfigs.js" % ROOTPATH)
    with open(cfPath, 'w') as f:
        f.write(fontConfigText)

    infoPlist['UIAppFonts'] = newUIAppFonts
    try:
        writePlist(infoPlist, plistPath)
    except Exception as e:
        print(e)
        raise Exception("Write  Info plist Error")
コード例 #40
0
def create_plist():
    print("Creating Info.plist")

    global ICON_FILE
    global VERSION

    if 'LONG_VERSION' in globals():
        global LONG_VERSION
    else:
        LONG_VERSION = VERSION

    info_plist_data = {
        'CFBundleDevelopmentRegion': 'en',
        'CFBundleExecutable': APP_NAME,
        'CFBundleIdentifier': IDENTIFIER,
        'CFBundleInfoDictionaryVersion': '6.0',
        'CFBundleName': APP_NAME,
        'CFBundleDisplayName': APP_NAME,
        'CFBundlePackageType': 'APPL',
        'CFBundleVersion': LONG_VERSION,
        'CFBundleShortVersionString': VERSION,
        'CFBundleSignature': '????',
        'LSMinimumSystemVersion': '10.7.0',
        'LSUIElement': False,
        'NSAppTransportSecurity': {
            'NSAllowsArbitraryLoads': True
        },
        'NSHumanReadableCopyright':
        "(c) 2012-2022, Baycrest Centre for Geriatric Care ('Baycrest') and others",
        'NSMainNibFile': 'MainMenu',
        'NSPrincipalClass': 'NSApplication',
        'NSHighResolutionCapable': True,
    }

    if ICON_FILE:
        info_plist_data['CFBundleIconFile'] = ICON_FILE

    if 'APP_SUPPORTED_FILES' in globals():
        global APP_SUPPORTED_FILES
        info_plist_data['CFBundleDocumentTypes'] = APP_SUPPORTED_FILES[
            'CFBundleDocumentTypes']

        if 'UTExportedTypeDeclarations' in APP_SUPPORTED_FILES:
            info_plist_data['UTExportedTypeDeclarations'] = \
                APP_SUPPORTED_FILES['UTExportedTypeDeclarations']

    biplist.writePlist(info_plist_data,
                       os.path.join(APP_FILE, 'Contents', 'Info.plist'),
                       binary=False)
コード例 #41
0
def delInfoPlistKey(sdk, destDir, XcodeProject, key):
    infoPlist = getInfoPlistPath(XcodeProject)
    if not infoPlist:
        print "[ %s ] Error! doesnt find info.plist" % sdk
        return 1
    infoPlist = os.path.join(destDir, infoPlist)
    plist = biplist.readPlist(infoPlist)
    modified = False
    for pKey in plist.keys():
        if pKey == key:
            plist.pop(pKey)
            modified = True
    if modified:
        biplist.writePlist(plist, infoPlist, False)
    return 0
コード例 #42
0
ファイル: project.py プロジェクト: ZXLLPW/src
 def modifyConfig(self,key,value):
     files = self.configFiles()
     for file in files:
         if fileExist(file):
             try:
                 plist = biplist.readPlist(file)
                 plist[key] = value
             
                 try:
                     biplist.writePlist(plist,file)
                 except (InvalidPlistException, NotBinaryPlistException), e:
                     print('Something bad happened:%s' % e)
                 print(plist)
             except (InvalidPlistException, NotBinaryPlistException), e:
                 print('Not a plist:%s' % e)
コード例 #43
0
def ios_add_background_mode(
        build_params,
        mode,
        filename='ForgeInspector/ForgeInspector-Info.plist'):
    if isinstance(mode, str) or isinstance(mode, unicode):
        mode = pystache.render(mode, build_params['app_config'])

    found_files = glob.glob(filename)
    for found_file in found_files:
        plist = biplist.readPlist(found_file)
        if "UIBackgroundModes" in plist:
            plist["UIBackgroundModes"].append(mode)
        else:
            plist["UIBackgroundModes"] = [mode]
        biplist.writePlist(plist, found_file)
コード例 #44
0
ファイル: customer_tasks.py プロジェクト: nadu/Creo
def set_in_biplist(build, filename, key, value):
    # biplist import must be done here, as in the server context, biplist doesn't exist
    import biplist

    value = utils.render_string(build.config, value)

    build.log.debug("settings {key} to {value} in {files}".format(key=key, value=value, files=filename))

    found_files = glob.glob(filename)
    if len(found_files) == 0:
        build.log.warning('No files were found to match pattern "%s"' % filename)
    for found_file in found_files:
        plist = biplist.readPlist(found_file)
        plist[key] = value
        biplist.writePlist(plist, found_file)
コード例 #45
0
    def extract_entitlements(self, provision_path):
        cmd = [
            "smime",
            "-inform", "der",
            "-verify",
            "-in", provision_path
        ]

        profile_text = signer.openssl_command(cmd, None)
        plist_dict = biplist.readPlistFromString(profile_text)

        if "Entitlements" in plist_dict:
            biplist.writePlist(plist_dict["Entitlements"], self.entitlements_path, binary=False)
            log.debug("wrote Entitlements to {0}".format(self.entitlements_path))
        else:
            log.debug("failed to write entitlements")
コード例 #46
0
ファイル: wiimupush.py プロジェクト: slegetank/WorkHelper
def getCurrentUserIdentity():
    global git_account
    global gerrit_currentuser_id

    configPlist = biplist.readPlist(configPlistPath)
    gerrit_currentuser_id = configPlist.get('gerrit_identity')

    if gerrit_currentuser_id != None:
        return

    response = requests.get("https://sh.linkplay.com:8010/a/accounts/?q=%s" % git_account, auth=requests.auth.HTTPDigestAuth(git_account, git_pass))
    jsonStr = response.text[4:]

    gerrit_currentuser_id = json.loads(jsonStr)[0]['_account_id']
    configPlist['gerrit_identity'] = gerrit_currentuser_id
    biplist.writePlist(configPlist, configPlistPath)
コード例 #47
0
def cache(tag):
    tab_arr = getCurrentTabs()

    if not os.path.exists(cache_plist):
        web_cache_dic = {}
    else:
        web_cache_dic = biplist.readPlist(cache_plist)

    # timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H:%M:%S')
    # tag = tag if tag else timestamp

    web_cache_dic[tag] = {
        "timestamp": datetime.datetime.now(),
        "tabs": tab_arr
    }
    biplist.writePlist(web_cache_dic, cache_plist)
コード例 #48
0
def mark_uuid(plugin_abspath, uuid, mark = True):

    global nr_of_updated_plugins
    info_file_path = os.path.abspath(plugin_abspath) + os.path.sep + "Contents/Info.plist"

    try:
        pl = biplist.readPlist(info_file_path)

        key = "DVTPlugInCompatibilityUUIDs"
        if not key in pl.keys():
            print("Could not find the UUIDs in '" + info_file_path + "'.")
            return False

        uuids = pl[key]
        updated = False

        if mark:
            if uuid not in uuids:
                uuids.append(uuid)
                updated = True
        else:
            if uuid in uuids:
                uuids.remove(uuid)
                updated = True

        try:
            biplist.writePlist(pl, info_file_path)

            if updated:
                if mark:
                    print("Marked '" + os.path.basename(plugin_abspath) + "'.")
                else:
                    print("Unmarked '" + os.path.basename(plugin_abspath) + "'.")
                nr_of_updated_plugins += 1

            return updated

        except Exception as e:
            print("Could not update the file '" + info_file_path + "'.")
            syslog.syslog(syslog.LOG_ERR, str(e))
            return False

    except Exception as e:
        print("Could not open file '" + info_file_path + "'.")
        syslog.syslog(syslog.LOG_ERR, str(e))
コード例 #49
0
ファイル: main.py プロジェクト: leiyue/ss-launcher
def update_plist_with_config(path, config):
    try:
        plist_obj = biplist.readPlist(path)
    except (biplist.InvalidPlistException, biplist.NotBinaryPlistException) as err:
        print("Not a plist: {}".format(err))
    else:
        plist_obj['config'] = json.dumps(config).encode()
        plist_obj['ShadowsocksIsRunning'] = True
        plist_obj['ShadowsocksMode'] = 'global'
        plist_obj['public server'] = False
        plist_obj['proxy encryption'] = config['profiles'][config['current']]['method']
        plist_obj['proxy ip'] = config['profiles'][config['current']]['server']
        plist_obj['proxy password'] = config['profiles'][config['current']]['password']
        plist_obj['proxy port'] = str(config['profiles'][config['current']]['server_port'])
        try:
            biplist.writePlist(plist_obj, path)
        except (biplist.InvalidPlistException, biplist.NotBinaryPlistException) as err:
            print("Something bad happened: {}".format(err))
コード例 #50
0
ファイル: PlistReader.py プロジェクト: JoeyWNK/MercJP
 def __init__(self, filename):
     self.read = readPlist(filename)
     if not self.read.get("VID"):
         text = raw_input("Please input VID:").upper()
         if patten.match(text):
             newlist = {
                 'VID': text,
                 'UUID': self.userid,
                 'DeviceToken': self.devicetoken,
                 'IID': self.iid
             }
             try:
                 newfile = raw_input("Please input new Plist file name:")
                 writePlist(newlist, newfile)
                 self.read = readPlist(newfile)
             except (InvalidPlistException, NotBinaryPlistException), e:
                 print "Fail to write File"
         else:
             print "Fail"
コード例 #51
0
ファイル: tabs.py プロジェクト: kfix/icloud-tabs
def generate_plist(with_payload, tabs, uuid, name, registry_version="need-something-here"):
    b = {
          "DeviceName": name,
          "LastModified": datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
          "Tabs": tabs
        }

    # Write b into a binary plist and base64 encode it.
    out = StringIO.StringIO()
    biplist.writePlist(b, out)
    #plistlib.dump(b, out, fmt=plistlib.FMT_BINARY) #py3.4
    # There is a required 12 byte header here. Don't know what it's supposed to contain.
    b_encoded = "".join(map(chr, [1, 0, 0, 0, 0,  0, 0, 23, 0, 0, 0, 0])) + out.getvalue()

    #codesign --display --entitlements - /Applications/Safari.app
    #https://developer.apple.com/library/ios/documentation/General/Conceptual/iCloudDesignGuide/Chapters/iCloudFundametals.html
    #http://www.undsoversum.de/2012/09/11/about-apns-tokens-and-duplicate-udids/
    p = {
          #"apns-token": plistlib.Data(APNS_TOKEN),
          "apps": [
            {
              "bundle-id": "com.apple.Safari",
              "keys": [
                {
                  "data": plistlib.Data(b_encoded), #bytes(b_encoded) py3.4
                  "name": uuid # a unique id for your device
                }
              ],
              "kvstore-id": "com.apple.Safari.SyncedTabs",
              "registry-version": registry_version, # no idea
            }
          ],
          "service-id":"iOS"
        }

    if with_payload == False:
      p["apps"][0].pop("keys")

    # Write p into a regular plist and return its string value.
    out = StringIO.StringIO()
    plistlib.writePlist(p, out)
    return out.getvalue()
コード例 #52
0
def do_plist(module, filename, value, key=None):
    working_value = value if key == None else {key: value}
    changed = False

    try:
        f = open(filename)
        plist = biplist.readPlist(f)
    except:
        plist = dict()

    changed = not equal(plist, working_value)

    if changed and not module.check_mode:
        try:
            update(plist, working_value)
            f = open(filename, 'w')
            biplist.writePlist(plist, f)
        except Exception as e:
            module.fail_json(msg="Can't change %s" % filename, error=str(e))

    return changed
コード例 #53
0
ファイル: update.py プロジェクト: hunner/icloud-tabs
def generate_plist(with_payload, tabs, registry_version="need-something-here"):
    b = {
          "DeviceName": DEVICE_NAME,
          "LastModified": strftime("%Y-%m-%dT%H:%M:%SZ", gmtime()),
          "Tabs": tabs
        }

    # Write b into a binary plist and base64 encode it.
    out = StringIO.StringIO()
    biplist.writePlist(b, out)
    # There is a required 12 byte header here. Don't know what it's supposed to contain.
    b_encoded = "".join(map(chr, [1, 0, 0, 0, 0,  0, 0, 23, 0, 0, 0, 0])) + out.getvalue()

    p = {
          "apns-token": plistlib.Data(APNS_TOKEN),
          "apps": [
            {
              "bundle-id": "com.apple.Safari",
              "keys": [
                {
                  "data": plistlib.Data(b_encoded),
                  "name": DEVICE_UUID # a unique id for your device
                }
              ],
              "kvstore-id": "com.apple.Safari.SyncedTabs",
              "registry-version": registry_version, # no idea
            }
          ],
          "service-id":"iOS"
        }

    if with_payload == False:
      p["apps"][0].pop("keys")

    # Write p into a regular plist and return its string value.
    out = StringIO.StringIO()
    plistlib.writePlist(p, out)
    return out.getvalue()
コード例 #54
0
	def build(self):
		# First, build the simulator target.
		with chdir(self._project_dir()):
			sim_build_command = self._build_command(is_simulator=True)
			(status, output) = run_command(sim_build_command, verbose=self.verbose)
			if status != 0:
				log("Building for simulator failed with code: %d" % status)
				log(output)
				return False
			dev_build_command = self._build_command()
			(status, output) = run_command(dev_build_command, verbose=self.verbose)
			if status != 0:
				log("Building for device failed with code: %d" % status)
				log(output)
				return False
			library_dir = self._output_dir()
			try:
				if os.path.exists(library_dir):
					shutil.rmtree(library_dir)
				os.makedirs(library_dir)
				os.makedirs(os.path.join(library_dir, 'include'))
			except Exception as e:
				log("Exception %s" % e)
				pass
			if not os.path.exists(library_dir):
				log("Unable to create output directory at: %s" % library_dir)
				return False
			(status, output) = run_command(self._lipo_command(), verbose=self.verbose)
			if status != 0:
				log("Unable to lipo static libraries")
				log(output)
				return False
			paths_to_copy = [("source/ATConnect.h", "include/ATConnect.h"), ("source/Rating Flow/ATAppRatingFlow.h", "include/ATAppRatingFlow.h"), ("source/Surveys/ATSurveys.h", "include/ATSurveys.h"), ("../LICENSE.txt", "LICENSE.txt"), ("../README.md", "README.md"), ("../CHANGELOG.md", "CHANGELOG.md")]
			for (project_path, destination_path) in paths_to_copy:
				full_project_path = project_path
				full_destination_path = os.path.join(self._output_dir(), destination_path)
				(status, output) = self._ditto_file(full_project_path, full_destination_path)
				if status != 0:
					log("Unable to ditto project path: %s" % full_project_path)
					log(output)
					return False
			# Copy the ApptentiveResources.bundle.
			bundle_source = os.path.join(self._products_dir(), "ApptentiveResources.bundle")
			bundle_dest = os.path.join(self._output_dir(), "ApptentiveResources.bundle")
			(status, output) = self._ditto_file(bundle_source, bundle_dest)
			# Update the Info.plist in the ApptentiveResources.bundle.
			bundle_plist_path = os.path.join(bundle_dest, "Info.plist")
			if not os.path.exists(bundle_plist_path):
				log("Unable to find bundle Info.plist at %s" % bundle_plist_path)
				return False
			plist = biplist.readPlist(bundle_plist_path)
			plist_key = "ATInfoDistributionKey"
			if self.dist_type == self.COCOAPODS_DIST:
				plist[plist_key] = "CocoaPods"
			elif self.dist_type == self.BINARY_DIST:
				plist[plist_key] = "binary"
			else:
				log("Unknown dist_type")
				return False
			biplist.writePlist(plist, bundle_plist_path)
		
		# Try to get the version.
		version = None
		header_contents = open(os.path.join(self._project_dir(), "source", "ATConnect.h")).read()
		match = re.search(r"#define kATConnectVersionString @\"(?P<version>.+)\"", header_contents, re.MULTILINE)
		if match and match.group('version'):
			version = match.group('version')
		with chdir(self._output_dir()):
			filename = 'apptentive_ios_sdk.tar.gz'
			if version:
				if self.dist_type == self.BINARY_DIST:
					filename = 'apptentive_ios_sdk-%s.tar.gz' % version
				elif self.dist_type == self.COCOAPODS_DIST:
					filename = 'apptentive_ios_sdk-cocoapods-%s.tar.gz' % version
			tar_command = "tar -zcvf ../%s ." % filename
			(status, output) = run_command(tar_command, verbose=self.verbose)
			if status != 0:
				log("Unable to create library archive")
				log("output")
				return False
			run_command("open .")
		return True
コード例 #55
0
    return result

theFile = MP_SRV_BASE + "/conf/etc/gov.llnl.mpavdl.plist"
isBinPlist = isBinaryPlist(theFile)

if isBinPlist === True:
	prefs = biplist.readPlist(theFile)
else:
	prefs = plistlib.readPlist(theFile)

prefs['MPServerAddress'] = server_name
prefs['MPServerSSL'] = str(server_ssl)
prefs['MPServerPort'] = str(server_port)
try:
	if isBinPlist === True:
		biplist.writePlist(prefs,theFile)	
	else:
		plistlib.writePlist(prefs,theFile)	
except Exception, e:
	print("Error: %s" % e)	


'''	
# ----------------------------------	
# Enable Startup Scripts
# ----------------------------------
'''
if OS_TYPE == "Darwin":
	if os.path.exists("/Library/MacPatch/Server/conf/LaunchDaemons/gov.llnl.mp.AVDefsSync.plist"):
		if os.path.exists("/Library/LaunchDaemons/gov.llnl.mp.AVDefsSync.plist"):
			os.remove("/Library/LaunchDaemons/gov.llnl.mp.AVDefsSync.plist")
コード例 #56
0
ファイル: bundle.py プロジェクト: lianz/isign
 def write_entitlements(self, signer, provisioning_path):
     """ Given a path to a provisioning profile, write its entitlements to
         self.entitlements_path """
     entitlements = self.extract_entitlements(provisioning_path)
     biplist.writePlist(entitlements, self.entitlements_path, binary=False)
     log.debug("wrote Entitlements to {0}".format(self.entitlements_path))
コード例 #57
0
ファイル: ios_tasks.py プロジェクト: inokon/JoyList
	def _sign_app(self, build, provisioning_profile, entitlements_file, certificate=None, certificate_path=None, certificate_password=None):
		app_folder_name = self._locate_ios_app(error_message="Couldn't find iOS app in order to sign it")
		path_to_app = path.abspath(path.join(self.path_to_ios_build, 'ios', app_folder_name))

		embedded_profile = 'embedded.mobileprovision'
		path_to_embedded_profile = path.abspath(path.join(path_to_app, embedded_profile))

		path_to_pp = path.join(build.orig_wd, provisioning_profile)
		if not path.isfile(path_to_pp):
			self._missing_provisioning_profile(build, path_to_pp)

		try:
			os.remove(path_to_embedded_profile)
		except Exception:
			LOG.warning("Couldn't remove {profile}".format(profile=path_to_embedded_profile))
		shutil.copy2(path_to_pp, path_to_embedded_profile)
		
		if not sys.platform.startswith('darwin'):
			if not certificate_path:
				lib.local_config_problem(
					build,
					message="To deploy iOS apps to a device, you must specify a "
						"path to a certificate to sign with.",
					examples={
						"ios.profiles.DEFAULT.developer_certificate_path": path.abspath("/Users/Bob/certificate.pfx")
					},
					more_info="http://current-docs.trigger.io/tools/ios-windows.html"
				)

			if not certificate_password:
				lib.local_config_problem(
					build,
					message="To deploy iOS apps to a device, you must specify a "
						"path the password to unlock your certificate.",
					examples={
						"ios.profiles.DEFAULT.developer_certificate_password": "******"
					},
					more_info="http://current-docs.trigger.io/tools/ios-windows.html"
				)

			cache_file = None
			development_certificate = False
			try:
				cert_name = subprocess.check_output(['java', '-jar', ensure_lib_available(build, 'p12name.jar'), certificate_path, certificate_password]).strip()
				if cert_name.startswith('iPhone Developer:'):
					development_certificate = True
			except Exception:
				pass

			if development_certificate:
				# Development certificate signings can be cached
				# Hash for Forge binary + signing certificate + profile + info.plist
				h = hashlib.sha1()
				with open(path.join(path_to_app, 'Forge'), 'rb') as binary_file:
					h.update(binary_file.read())
				with open(path.join(path_to_app, 'Info.plist'), 'rb') as info_plist_file:
					h.update(info_plist_file.read())
				with open(certificate_path, 'rb') as certificate_file:
					h.update(certificate_file.read())
				with open(path_to_embedded_profile, 'rb') as embedded_file:
					h.update(embedded_file.read())

				if not path.exists(path.abspath(path.join(self.path_to_ios_build, '..', '.template', 'ios-signing-cache'))):
					os.makedirs(path.abspath(path.join(self.path_to_ios_build, '..', '.template', 'ios-signing-cache')))
				cache_file = path.abspath(path.join(self.path_to_ios_build, '..', '.template', 'ios-signing-cache', h.hexdigest()))

			# XXX: Currently cache file is never saved, see below.
			if cache_file is not None and path.exists(cache_file):
				with temp_file() as resource_rules_temp:
					shutil.copy2(path.join(path_to_app, 'ResourceRules.plist'), resource_rules_temp)
					zip_to_extract = ZipFile(cache_file)
					zip_to_extract.extractall(path_to_app)
					zip_to_extract.close()
					shutil.copy2(resource_rules_temp, path.join(path_to_app, 'ResourceRules.plist'))
				return

			# Remote
			LOG.info('Sending app to remote server for codesigning. Uploading may take some time.')
			
			# Zip up app
			with temp_file() as app_zip_file:
				if cache_file is None:
					with ZipFile(app_zip_file, 'w', compression=ZIP_DEFLATED) as app_zip:
						for root, dirs, files in os.walk(path_to_app, topdown=False):
							for file in files:
								app_zip.write(path.join(root, file), path.join(root[len(path_to_app):], file))
								os.remove(path.join(root, file))
							for dir in dirs:
								os.rmdir(path.join(root, dir))
				else:
					with ZipFile(app_zip_file, 'w', compression=ZIP_DEFLATED) as app_zip:
						app_zip.write(path.join(path_to_app, 'Forge'), 'Forge')
						app_zip.write(path.join(path_to_app, 'Info.plist'), 'Info.plist')
						app_zip.write(path_to_embedded_profile, 'embedded.mobileprovision')
						with temp_file() as tweaked_resource_rules:
							import biplist
							rules = biplist.readPlist(path.join(path_to_app, 'ResourceRules.plist'))
							# Don't sign anything
							rules['rules']['.*'] = False
							with open(tweaked_resource_rules, 'wb') as tweaked_resource_rules_file:
								biplist.writePlist(rules, tweaked_resource_rules_file)
							app_zip.write(tweaked_resource_rules, 'ResourceRules.plist')
								
							
				from poster.encode import multipart_encode
				from poster.streaminghttp import register_openers
				import urllib2

				class FileWithProgress:
					def __init__(self, path, flags):
						self.total_size = os.path.getsize(path)
						self.file = open(path, flags)
						self.name = self.file.name
						self.path = path
						self.amount_read = 0;
						self.last_progress = 0;
					def read(self, length):
						data = self.file.read(length)
						if data != "":
							self.amount_read = self.amount_read + len(data)
							# TODO: Nicer progress output
							progress = 10*self.amount_read/self.total_size
							if progress > self.last_progress:
								self.last_progress = progress
								LOG.info(str(10*progress) + " percent uploaded: "+self.path)
						else:
							self.file.close()
						return data
					def fileno(self):
						return self.file.fileno()
					def seek(self, pos):
						return self.file.seek(pos)

				files = {
					'app': FileWithProgress(app_zip_file, 'rb'),
					'entitlements': FileWithProgress(entitlements_file, 'rb'),
					'certificate': FileWithProgress(certificate_path, 'rb'),
					'password': certificate_password
				}

				# Register the streaming http handlers with urllib2
				register_openers()

				# headers contains the necessary Content-Type and Content-Length
				# datagen is a generator object that yields the encoded parameters
				datagen, headers = multipart_encode(files)

				# Create the Request object
				request = urllib2.Request("https://trigger.io/codesign/sign", datagen, headers)

				with temp_file() as signed_zip_file:
					resp = urllib2.urlopen(request)
					
					# Read the log lines from the start of the response
					while True:
						data = resp.readline()
						if data == "--failure\n":
							raise IOSError("Remote codesign failed")
						elif data == "--data\n" or data == "":
							break
						LOG.info(data.rstrip('\r\n'))
					
					# Read the binary data from the 2nd part of the response
					# TODO: Chunked download and progress
					with open(signed_zip_file, 'wb') as signed_zip:
						signed_zip.write(resp.read())

					# Unzip response
					zip_to_extract = ZipFile(signed_zip_file)
					zip_to_extract.extractall(path_to_app)
					zip_to_extract.close()

					# XXX: Caching currently disabled as Info.plist changes on every build
					"""if cache_file is not None:
						shutil.copy2(signed_zip_file, cache_file)"""
					LOG.info('Signed app received, continuing with packaging.')

		else:
			# Local
			codesign = self._check_for_codesign()
			resource_rules = path.abspath(path.join(path_to_app, 'ResourceRules.plist'))
			run_shell(codesign, '--force', '--preserve-metadata',
					'--entitlements', entitlements_file,
					'--sign', certificate,
					'--resource-rules={0}'.format(resource_rules),
					path_to_app)
コード例 #58
0
ファイル: __init__.py プロジェクト: jamfit/HipStatus
 def _save_default(self, root):
     logging.info("Writing default com.jamfsw.hipstatus preferences file")
     biplist.writePlist(root, self._plist_path)
コード例 #59
0
ファイル: __init__.py プロジェクト: jamfit/HipStatus
 def update(self):
     logging.info("Updating com.jamfsw.hipstatus preferences file")
     biplist.writePlist(self._plist, self._plist_path)