Пример #1
0
def set_key(key, include_accidentals):
	arr = [ 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B' ]

	if key not in arr:
		G.error("key %s is invalid.  Select one of %s" % (key, arr))
		return None

	offset = arr.index(key)
	notes = ["%s%d" % (note,octave) 
		for (i, (octave,note)) in enumerate(itertools.product(range(0, 9), arr)) 
		if include_accidentals or ((i - offset) % 12 not in [ 1, 3, 6, 8, 10 ]) # filter accidentals
	]

	# Center on octave 4
	center = notes.index(key + '4')
	min = center - G.NSTAIRS / 2

	# Reduce to G.NSTAIRS notes
	assert min >= 0 and len(notes) >= G.NSTAIRS
	G.note_from_stair = notes[min : G.NSTAIRS + min]
	assert len(G.note_from_stair) == G.NSTAIRS

	if G.gui:
		G.gui.selected_key.set(key)
		G.gui.use_accidentals.set(include_accidentals)
		G.gui.draw_keyboard()

	if include_accidentals:
		G.output('Include all notes (centered on %s)' % (key))
	else:
		G.output('Key = %s' % (key))
Пример #2
0
 def _listen(self):
     #delete socket file
     if self._check():
         self._delete()
     #init root socket
     socket_file = config.config('socket_folder') + '/' + self._socket
     fsocket = FileSocket(socket_file)
     fsocket.server()
     while True:
         data = fsocket.receive()
         if not data:
             continue
         try:
             param = json.loads(data)
         except Exception, e:
             param = False
         if not param:
             result = config.error('NOT_JSON', data)
         elif not isinstance(param, dict):
             result = config.error('PARAM_ILLEGAL', data)
         elif not param.get('option'):
             result = config.error('MISSING_VALUE', 'Option key error.')
         else:
             result = self._deal(param.get('option'), param.get('task'), param.get('flag'))
         fsocket.send(result)
         fsocket.close()
         #check stop
         if config.running == False:
             self._status['running'] = False
             break
Пример #3
0
 def start(self):
     root_alive = root.alive()
     if self._setting.node == 'root':
         if root_alive:
             print config.error('ROOT_RUNNING')
             return
         root.start()
     return
Пример #4
0
 def search_by_task_id(self, task_id):
     cursor = self.db.cursor()
     try:
         stmt = "select item_name, jan_code from %s  where" \
                "tasks_id = %s" % (self.table_name, task_id)
         cursor.execute(stmt)
         result = cursor.fetchall()
         return Item(result[0])
     except Exception as e:
         config.error("could not find data with task_id: %s" % task_id)
Пример #5
0
 def set_complete(self, jan_code):
     cursor = self.db.cursor()
     try:
         stmt = "update %s set completed = 1 where jan_code = %s" % (
             self.table_name, jan_code)
         cursor.execute(stmt)
         result = cursor.fetchall()
         return result
     except Exception as e:
         config.error("database.set_complete :: %s" % e)
Пример #6
0
def set_instrument(name):
	# We assume that the files were set up properly, so if C4 exists, the rest do as well
	name = name.replace(' ', '_')
	fname = get_sound_file(name, 'C4')
	if not name in list_instruments():
		G.error("%s is not a valid instrument" % (name))
		return None

	G.instrument = name
	if G.gui: G.gui.selected_instrument.set(G.instrument)
	G.output('Instrument = ' + G.instrument.replace('_', ' '))
Пример #7
0
def sound_play(note):
	if G.mute: return

	fname = get_sound_file(G.instrument, note)
	if not os.path.isfile(fname):
		G.error('File not found: ' + fname)
		return
	channel = pygame.mixer.Channel(G.index_from_note[note])
	sound = pygame.mixer.Sound(fname)
	sound.set_volume(G.volume)
	channel.play(sound)
	G.output('Play %s' % (note))
	G.debug("start %s on channel %d at volume %.1f" % (fname, G.index_from_note[note], 11.0 * G.volume))
Пример #8
0
 def search_by_jan(self, jan_code):
     cursor = self.db.cursor()
     try:
         stmt = "select item_name from %s  where " \
                "jan_code = %s" % (self.table_name, jan_code)
         cursor.execute(stmt)
         result = cursor.fetchall()
         if len(result) is not 0:
             return result[0][0]
         else:
             return None
     except Exception as e:
         config.error(
             "database.search_by_jan :: could not find data with jan_code: %s (%s)"
             % (jan_code, e))
Пример #9
0
 def search_by_jan(self, jan_code, is_complete=None):
     cursor = self.db.cursor()
     try:
         stmt = "select tasks_id from %s  where " \
                "jan_code = %s" % (self.table_name, jan_code)
         if is_complete is not None:
             stmt += " and completed = %s" % int(is_complete)
         print(stmt)
         cursor.execute(stmt)
         result = cursor.fetchall()
         return [r[0] for r in result]
     except Exception as e:
         config.error(
             "database.search_by_jan :: could not find data with jan_code: %s (%s)"
             % (jan_code, e))
Пример #10
0
    def isrooted(self, serial):
        '''
            Doesn't return all reasons by default. First match will return.
            TODO: make consistent with iOS isrooted, which returns all reasons discovered.
        '''

        cmd = "{cli} -s {serial} shell 'command -v su'"
        s = catch_err(run_command(cmd, serial=shlex.quote(serial)))
        if not s or s == -1 or 'not found' in s or len(s) == 0 or (
                s == "[android]: Error running ''. Error (1):"):
            print(config.error())
            reason = "couldn't find 'su' tool on the phone."
            return (False, reason)
        else:
            reason = "found '{}' tool on the phone. Verify whether this is a su binary.".format(
                s.strip())
            return (True, reason)

        installed_apps = self.installed_apps
        if not installed_apps:
            installed_apps = self.get_apps(serial)

        # FIXME: load these from a private database instead.  from OWASP,
        # https://sushi2k.gitbooks.io/the-owasp-mobile-security-testing-guide/content/0x05j-Testing-Resiliency-Against-Reverse-Engineering.html
        root_pkgs = ['com.noshufou.android.su','com.thirdparty.superuser',\
                'eu.chainfire.supersu', 'com.koushikdutta.superuser',\
                'com.zachspong.temprootremovejb' ,'com.ramdroid.appquarantine']
        root_pkgs_check = list(set(root_pkgs) & set(installed_apps))
        if root_pkgs_check:
            reason = "found the following app(s) on the phone: '{}'."\
                    .format(str(root_pkgs_check))
            return (True, reason)
Пример #11
0
 def isrooted(self, serial):
     cmd = '{cli} -s {serial} shell su'
     s = self.catch_err(self.run_command(cmd, serial=shlex.quote(serial)))
     if s == -1 or 'su: not found' in s:
         print(config.error())
         return False
     else:
         return True
Пример #12
0
def scan():
    """
    Needs three attribute for a device
    :param device: "android" or "ios" or test
    :return: a flask view template
    """
    clientid = request.form.get('clientid', request.args.get('clientid'))
    device = request.form.get('device', request.args.get('device'))
    action = request.form.get('action', request.args.get('action'))
    print("--> Action = ", action)
    # if action == "Privacy Check":
    #     return redirect(url_for(privacy, device=device), code=302)
    sc = get_device(device)
    print("SC inside scan --------->", sc)
    if not sc:
        return render_template("result.html",
                               task="home",
                               apps={},
                               error="Please pick one device.",
                               clientid=clientid)
    print("sc.devices() in scan---------->", sc.devices())
    ser = first_element_or_none(sc.devices())
    # clientid = new_client_id()
    print(">>>scanning_device", device, ser, "<<<<<")
    error = "If an iPhone is connected, open iTunes, click through the connection dialog and wait for the \"Trust this computer\" prompt " \
            "to pop up in the iPhone, and then scan again." if device == 'ios' else \
        "If an Android device is connected, disconnect and reconnect the device, make sure " \
        "developer options is activated and USB debugging is turned on on the device, and then scan again."

    if not ser:
        return render_template(
            "result.html",
            task="home",
            apps={},
            #    error="No device is connected!! {}".format(error)
            error="No device is connected!!")
    #scanid = create_scan(clientid, ser, device)
    # @apps have appid, title, flags, TODO: add icon
    apps = sc.find_spyapps(serialno=ser).fillna('').to_dict(orient='index')
    print("Creating appinfo...")
    # create_mult_appinfo([(scanid, appid, json.dumps(info['flags']), '', '<new>')
    #                      for appid, info in apps.items()])
    rooted = sc.isrooted(ser)
    return render_template(
        'result.html',
        task="home",
        isrooted="Yes" if rooted else "Don't know" if rooted is None else "No",
        apps=apps,
        # scanid=scanid,
        clientid=clientid,
        sysapps=set(),  #sc.get_system_apps(serialno=ser)),
        serial=ser,
        device=device,
        error=config.error(),
    )
Пример #13
0
 def set_new_name(self, jan_code, item_name):
     cursor = self.db.cursor()
     try:
         if self.search_by_jan(jan_code):
             # if given jan_code exists
             stmt = "update %s set item_name = %s where jan_code = %s" % (
                 self.table_name, item_name, jan_code)
             cursor.execute(stmt)
             result = cursor.fetchall()
             return result
         else:
             # if not exists
             stmt = "insert into %s (item_name, jan_code) values (N'%s', %s)" \
                    % (self.table_name, item_name, jan_code)
             cursor.execute(stmt)
             result = cursor.fetchall()
             return result
     except Exception as e:
         config.error("database.set_new_name :: could not set name (%s)" %
                      e)
    def setUpClass(inst):
        #global driver
        inst.browserdriver = webdriver.Chrome('chromedriver')
        inst.browserdriver.maximize_window()

        try:
            inst.browserdriver.get(config.url)
        except Exception as exc:
            config.error('Error in page in browser: Exception: %s' % (exc))

        #inst.driver = config.loadWebDriver(inst.driver)
        #global start_time
        inst.start_time = time.time()
        #global element
        try:
            inst.element = config.ensureCanvasIsClickable(inst.browserdriver)
            """wait = WebDriverWait(inst.browserdriver, config.pageloaddelayduration)
            inst.element = wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'canvas')))"""

        except Exception as exc:
            config.error(
                'Error in waiting for clickable canvas: Exception: %s' % (exc))
Пример #15
0
def delete_app(scanid):
    device = get_device_from_db(scanid)
    serial = get_serial_from_db(scanid)
    sc = get_device(device)
    appid = request.form.get('appid')
    remark = request.form.get('remark')
    action = "delete"
    # TODO: Record the uninstall and note
    r = sc.uninstall(serial=serial, appid=appid)
    if r:
        r = update_appinfo(
            scanid=scanid, appid=appid, remark=remark, action=action
        )
        print("Update appinfo failed! r={}".format(r))
    else:
        print("Uinstall failed. r={}".format(r))
    return is_success(r, "Success!", config.error())
    def test_startButton_click(self):
        try:
            xTarget = self.element.size['width'] * 0.5
            yTarget = self.element.size['height'] * 0.75
            config.clickMouseAtXY(self.browserdriver, self.element, xTarget,
                                  yTarget)
            config.show("Testcase passed: Start button clicked")

        except Exception as exc:
            config.error('Error in clicking start button: Exception: %s' %
                         (exc))
            config.error("Testcase failed: Start button could not be clicked")

        try:
            config.asserturl(self.browserdriver, config.assertpage)
            config.show("Url %s asserted" % (config.assertpage))

        except Exception as exc:
            config.error('Assert page for %s failed: Exception: %s' %
                         (config.assertpage, exc))
Пример #17
0
def playsong_aux(fname):
	infile = open(fname, 'r')
	tempo = 120 # andante
	prev_tones = []
	line = ''

	while G.gui and G.gui.button_demo.get():
		line = line.strip()
		#G.output('parse line: "%s"' % (line))

		if (not len(line)):
			line = infile.readline()
			if ('' == line):
				pygame.mixer.stop()
				# turn itself off gui-side
				G.gui.buttom_demo.set(0)
				G.gui.draw_keyboard()
				return None
		elif re.match(r'#', line):
			G.debug(line)
			line = ''
		elif re.match(r'\\tempo ([1-9][0-9]*)\s*$', line):
			# Yay! I get to pointlessly repeat myself because python doesn't trust the programmer with assignments that evaluate to a value!
			matches = re.match(r'\\tempo ([1-9][0-9]*)\s*$', line)
			try:
				tempo = int(matches.group(1))
				G.output('Tempo = %s' % (tempo))
			except:
				G.error("Can't happen. Invalid tempo: \"" + line + '"')
			line = ''
		elif re.match(r'\\instrument (.*)', line):
			matches = re.match(r'\\instrument (.*)', line)
			player.set_instrument(matches.group(1))
			line = '' # instruments can have spaces, so this command always uses the entire line
		elif re.match(r'\\key (.*)', line):
			matches = re.match(r'\\key (.*)', line)
			player.set_key(matches.group(1), 0)
			line = '' # instruments can have spaces, so this command always uses the entire line
		elif re.match(r'\(([~A-G0-8b ]*)\)([1-9][0-9]*\.?)(.*)', line): 
			matches = re.match(r'\(([~A-G0-8b ]*)\)([1-9][0-9]*\.?)(.*)', line)
			# Does admit a few notes that aren't on the keyboard, like G8, but those will get caught by sound_play()
			# Also admits things like (C4~3 A)3. If I can nest groups, I *could* catch those, but again, sound_play will handle it.
			# The checks here just need to make sure it doesn't do anything that could escape the SOUNDS_DIR
			tones = matches.group(1).split()
			try:
				s = matches.group(2)
				duration = 4.0 / float(s) # now equals number of quarter notes
				if '.' == s[len(s) - 1]: # dotted note
					duration = duration * 1.5;
				
				# Stop the previous set of notes
				for tone in prev_tones:
					if ('~' + tone) not in tones:
						player.sound_stop(tone)
						G.gui.key_up(tone)

				# Play this set
				for (i, tone) in enumerate(tones):
					if ('~' != tone[0]):
						# If it's a tie, we don't start it over
						player.sound_play(tone)
						G.gui.key_down(tone)
					else:
						tones[i] = tone[1:len(tone)] # prev_tones won't care if it was already a tie

				prev_tones = tones
				
				# (duration beats) / (tempo beats/minute) * 60 s/min* 1000 ms/s = x ms
				ms = int(1000 * 60 * duration / tempo)
				pygame.time.delay(ms)
				line = matches.group(3)
			except:
				G.error('Invalid note: "' + line + '"')
				print sys.exc_info()
				traceback.print_tb(sys.exc_info()[2])
				print ''

				line = ''
		else:
			G.error('Syntax error: "' + line + '"')
			line = ''

	pygame.mixer.stop()
Пример #18
0
def scan():
    """
    Needs three attribute for a device
    :param device: "android" or "ios" or test
    :return: a flask view template
    """
    #clientid = request.form.get('clientid', request.args.get('clientid'))
    if 'clientid' not in session:
        return redirect(url_for('index'))

    device_primary_user = request.form.get(
        'device_primary_user',
        request.args.get('device_primary_user'))
    device = request.form.get('device', request.args.get('device'))
    action = request.form.get('action', request.args.get('action'))
    device_owner = request.form.get(
        'device_owner', request.args.get('device_owner'))

    currently_scanned = get_client_devices_from_db(session['clientid'])
    template_d = dict(
        task="home",
        title=config.TITLE,
        device=device,
        device_primary_user=config.DEVICE_PRIMARY_USER,   # TODO: Why is this sent
        device_primary_user_sel=device_primary_user,
        apps={},
        currently_scanned=currently_scanned,
        clientid=session['clientid']
    )
    # lookup devices scanned so far here. need to add this by model rather
    # than by serial.
    print('CURRENTLY SCANNED: {}'.format(currently_scanned))
    print('DEVICE OWNER IS: {}'.format(device_owner))
    print('PRIMARY USER IS: {}'.format(device_primary_user))
    print('-' * 80)
    print('CLIENT ID IS: {}'.format(session['clientid']))
    print('-' * 80)
    print("--> Action = ", action)

    sc = get_device(device)
    if not sc:
        template_d["error"] = "Please choose one device to scan."
        return render_template("main.html", **template_d), 201
    if not device_owner:
        template_d["error"] = "Please give the device a nickname."
        return render_template("main.html", **template_d), 201

    ser = sc.devices()

    print("Devices: {}".format(ser))
    if not ser:
        # FIXME: add pkexec scripts/ios_mount_linux.sh workflow for iOS if
        # needed.
        error = "<b>A device wasn't detected. Please follow the "\
            "<a href='/instruction' target='_blank' rel='noopener'>"\
            "setup instructions here.</a></b>"
        template_d["error"] = error
        return render_template("main.html", **template_d), 201

    ser = first_element_or_none(ser)
    # clientid = new_client_id()
    print(">>>scanning_device", device, ser, "<<<<<")

    if device == "ios":
        error = "If an iPhone is connected, open iTunes, click through the "\
                "connection dialog and wait for the \"Trust this computer\" "\
                "prompt to pop up in the iPhone, and then scan again."
    else:
        error = "If an Android device is connected, disconnect and reconnect "\
                "the device, make sure developer options is activated and USB "\
                "debugging is turned on on the device, and then scan again."
    error += "{} <b>Please follow the <a href='/instruction' target='_blank'"\
             " rel='noopener'>setup instructions here,</a> if needed.</b>"
    if device == 'ios':
        # go through pairing process and do not scan until it is successful.
        isconnected, reason = sc.setup()
        template_d["error"] = error.format(reason)
        template_d["currently_scanned"] = currently_scanned
        if not isconnected:
            return render_template("main.html", **template_d), 201

    # TODO: model for 'devices scanned so far:' device_name_map['model']
    # and save it to scan_res along with device_primary_user.
    device_name_print, device_name_map = sc.device_info(serial=ser)

    # Finds all the apps in the device
    # @apps have appid, title, flags, TODO: add icon
    apps = sc.find_spyapps(serialno=ser).fillna('').to_dict(orient='index')
    if len(apps) <= 0:
        print("The scanning failed for some reason.")
        error = "The scanning failed. This could be due to many reasons. Try"\
            " rerunning the scan from the beginning. If the problem persists,"\
            " please report it in the file. <code>report_failed.md</code> in the<code>"\
            "phone_scanner/</code> directory. Checn the phone manually. Sorry for"\
            " the inconvenience."
        template_d["error"] = error
        return render_template("main.html", **template_d), 201

    scan_d = {
        'clientid': session['clientid'],
        'serial': config.hmac_serial(ser),
        'device': device,
        'device_model': device_name_map.get('model', '<Unknown>').strip(),
        'device_version': device_name_map.get('version', '<Unknown>').strip(),
        'device_primary_user': device_owner,
    }

    if device == 'ios':
        scan_d['device_manufacturer'] = 'Apple'
        scan_d['last_full_charge'] = 'unknown'
    else:
        scan_d['device_manufacturer'] = device_name_map.get(
            'brand', "<Unknown>").strip()
        scan_d['last_full_charge'] = device_name_map.get(
            'last_full_charge', "<Unknown>")

    rooted, rooted_reason = sc.isrooted(ser)
    scan_d['is_rooted'] = rooted
    scan_d['rooted_reasons'] = json.dumps(rooted_reason)

    # TODO: here, adjust client session.
    scanid = create_scan(scan_d)

    if device == 'ios':
        pii_fpath = sc.dump_path(ser, 'Device_Info')
        print('Revelant info saved to db. Deleting {} now.'.format(pii_fpath))
        cmd = os.unlink(pii_fpath)
        # s = catch_err(run_command(cmd), msg="Delete pii failed", cmd=cmd)
        print('iOS PII deleted.')

    print("Creating appinfo...")
    create_mult_appinfo([(scanid, appid, json.dumps(
        info['flags']), '', '<new>') for appid, info in apps.items()])

    currently_scanned = get_client_devices_from_db(session['clientid'])
    template_d.update(dict(
        isrooted=(
            "<strong class='text-info'>Maybe (this is possibly just a bug with our scanning tool).</strong> Reason(s): {}"
            .format(rooted_reason) if rooted
            else "Don't know" if rooted is None 
            else "No"
        ),
        device_name=device_name_print,
        apps=apps,
        scanid=scanid,
        sysapps=set(),  # sc.get_system_apps(serialno=ser)),
        serial=ser,
        currently_scanned=currently_scanned,
        # TODO: make this a map of model:link to display scan results for that
        # scan.
        error=config.error()
    ))
    return render_template("main.html", **template_d), 200
Пример #19
0
def mainLoad(ld):
    global load
    global commands
    global cmdHistory
    global printString
    global usrError

    global mw
    global w
    global entryTxt
    global labelTxt

    cmdHistory = []
    commands = []

    # Tkinter init
    windowWidth = 600
    windowHeight = 200
    textFieldHeight = 50

    mainBG = '#fff3e6'

    mw = Tk()
    mw.configure(background='#fff3e6')
    mw.minsize(width=windowWidth, height=windowHeight)
    mw.maxsize(width=windowWidth, height=windowHeight)
    mw.grid_columnconfigure([0, 1, 2, 3], minsize=150)
    mw.grid_rowconfigure([0, 1, 2, 3], minsize=50)
    mw.pack_propagate(0)

    labelFrame = Frame(mw, width=580, height=140)
    labelFrame.configure(background='#ffe6e6')
    labelFrame.grid(row=0,
                    column=0,
                    columnspan=1,
                    rowspan=3,
                    padx=(10, 0),
                    pady=(10, 0),
                    sticky='NW')
    labelFrame.pack_propagate(0)

    textFrame = Frame(mw, width=430, height=30)
    textFrame.configure(background=mainBG)  #'#ccffcc')
    textFrame.grid(row=3,
                   column=0,
                   columnspan=2,
                   rowspan=3,
                   padx=(10, 0),
                   pady=(10, 0),
                   sticky="NW")
    textFrame.pack_propagate(0)

    w = Text(labelFrame)
    scrollbar = Scrollbar(labelFrame, command=w.yview)
    w.config(yscrollcommand=scrollbar.set)

    scrollbar.pack(side="right", fill=BOTH)
    w.pack(side="left")

    entryTxt = StringVar()
    e = Entry(textFrame, textvariable=entryTxt, width=52)
    e.grid(sticky="NW")

    b = Button(mw, text="send", width=10, command=main)
    b.grid(row=3, column=0, sticky="E")

    load = ld
    print(load)
    load()

    reload(config)
    # loadDefaultCmd(config.defcmdConfig)

    printString = ''
    for i in range(1, len(config.inpConfig)):
        printString += (config.inpConfig[i])
    printString += config.inpConfig[0]

    try:
        usrError = config.error()
    except AttributeError:
        scw("Undefined usrError in config.py.")

    print()
    scw("done")
    mw.mainloop()