예제 #1
0
def test_authenticate_created_account():
    # there is a user device
    device_id = fake(schema.string.non_empty)

    # with this device user creates an account and receives token
    create_account_response = API().create_account(device_id=device_id)
    assert create_account_response.status_code == 200
    created_account = create_account_response.json()

    created_account_token = created_account['token']

    # with received token user authenticates an account
    authenticate_account_response = API(
        created_account_token).authenticaticate_account(
            username=fake(schema.string.non_empty),
            password=fake(schema.string.non_empty),
            device_id=device_id)
    assert authenticate_account_response.status_code == 200
    authenticated_account = authenticate_account_response.json()

    decoded_auth_token = decode_token(authenticated_account['token'])

    # profileId from a decoded authentication token matches profileId from a created account
    assert decoded_auth_token['profileId'] == created_account['profileId']
    # and an account state is not automatically approved
    assert decoded_auth_token['accountState'] == 'pending_approval'
def index():
    """
    Main add-on popup
    :return:
    """
    api = API()

    # check if current window is arwork or intro:
    window_id = getCurrentWindowDialogId()
    window = WindowDialog(window_id)

    if isinstance(window, IntroWindow) or isinstance(window, ArtworkWindow):
        log('Either IntroWindow or ArtworkWindow are already open')
    else:
        intro_window = IntroWindow(api)
        intro_window.doModal()
        section_id = intro_window.getProperty('section')
        if section_id:
            section_id = int(section_id)
            category_id = int(intro_window.getProperty('category'))
            del intro_window

            if section_id == 1:  # channels
                show_channels(
                    section_id,
                    category_id) if section_id != 99 else show_favorites()
            elif section_id == 3:  # atmospheres
                show_categories(section_id)
            else:
                show_favorites()  # favorites
        else:
            del intro_window
예제 #3
0
    def onStart(self):
        self.debugging = Parameters["Mode6"]
        if self.debugging == "Verbose":
            Domoticz.Debugging(2 + 4 + 8 + 16 + 64)
        if self.debugging == "Debug":
            Domoticz.Debugging(2)
        DumpConfigToLog()
        Domoticz.Log("Chirpstack2Domoticz Plugin started")
        #App ID Base TOPIC
        if (Parameters["Mode1"].strip() != ""):
            self.base_topic = "application/" + Parameters["Mode1"].strip()
        else:
            Domoticz.Log(
                "Warning : No Application ID submitted. It will subscribe to all application topics"
            )
            self.base_topic = "application"
        self.subscribed_for_devices = False
        self.create_new_devices = Parameters["Mode2"].strip()
        mqtt_server_address = Parameters["Address"].strip()
        mqtt_server_port = Parameters["Port"].strip()
        mqtt_client_id = Parameters["Mode3"].strip()

        self.mqttClient = MqttClient(mqtt_server_address, mqtt_server_port,
                                     mqtt_client_id, self.onMQTTConnected,
                                     self.onMQTTDisconnected,
                                     self.onMQTTPublish, self.onMQTTSubscribed)
        self.api = API(Devices, self.publishToMqtt)
예제 #4
0
    def mouseDoubleClickEvent(self, QMouseEvent):
        api = API(self.session, self.token)
        response = api.wall.delete(post_id=self.post_id)

        if response['response'] == 1:
            self.deleteLater()
        print('Response by delete post', response)
예제 #5
0
def test_create_and_compose():
    api = API('http://pythoncanarias.es/api/v1')
    assert isinstance(api, API)
    assert isinstance(api.status, API)
    assert len(api.status.path) == 1
    assert api.status.path == ['status']
    assert api.status.get_url() == 'http://pythoncanarias.es/api/v1/status'
예제 #6
0
    def __init__(self, consumer_key, consumer_secret, connection_params=None):

        self.scheme = 'http'
        self.host = 'localhost'
        #self.host = 'indivo.genepartnership.org'
        #self.host = 'indivo-staging.informedcohort.org'
        #self.host = 'indivobig.genepartnership.org'
        #self.host = 'x-staging.indivo.org'
        self.port = '8000'

        if connection_params:
            if connection_params.has_key('scheme'):
                self.scheme = connection_params['scheme']
            if connection_params.has_key('host'):
                self.host = connection_params['host']
            if connection_params.has_key('port'):
                self.port = connection_params['port']

        if self.scheme and self.host and self.port:
            self.utils_obj = IUtils(self.scheme, self.host, self.port)
        else:
            raise APIConnectorError("Scheme, host, port needed")

        self.api = API(self.utils_obj)
        self.ds = DataStore()
        self.ds.reset()
        self.ds.app_info['consumer_key'] = consumer_key
        self.ds.app_info['consumer_secret'] = consumer_secret
        self.count = 0
예제 #7
0
    def __init__(self, parent=None, session=None, token=None):
        QWidget.__init__(self, parent)
        self.pixmap = QtGui.QPixmap()
        self.api = API(session, token)

        self.nameLayout = QHBoxLayout()
        self.icon = QLabel()
        self.name = QLabel()
        self.id = 0
        self.deletGroup = QPushButton('Del')
        self.nameLayout.addWidget(self.icon, 0)
        self.nameLayout.addWidget(self.name, 1)
        self.nameLayout.addWidget(self.deletGroup, 2, QtCore.Qt.AlignRight)

        self.frame = QFrame()
        self.frame.setFrameShape(QFrame.Panel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setLayout(self.nameLayout)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.frame)

        self.setLayout(self.mainLayout)

        self.name.setStyleSheet('''color: rgb(60,  50,  130);''')
        self.frame.setStyleSheet('''background-color:rgb(255, 255, 255);''')

        self.deletGroup.clicked.connect(self.delete)
예제 #8
0
    def do_POST(self):
        self.send_response(200)
        self.send_header('Content-type', 'text-html')
        self.end_headers()

        length = int(self.headers['Content-Length'])
        post_body = self.rfile.read(length).decode('utf-8')
        post_body = json.loads(post_body)

        req_id = post_body['request_id']

        audio_name = req_id

        resp = post_body['response']
        if self.path.startswith('/denoise/emotion'):
            my_api = API(API_KEY, URL)
            filename = self.__denoise(audio_name, resp)
            my_api.get_emotion(filename)
            self.wfile.write(json.dumps(post_body).encode())
        elif self.path.startswith('/denoise'):
            self.__denoise(audio_name, resp)
            self.wfile.write(json.dumps(post_body).encode())
        elif self.path.startswith('/emotion'):
            emotions, sorted_emotions = self.__emotion(resp)
            print('emotion from audio:', audio_name)
            for item in sorted_emotions:
                print(item[0] + ':', item[1])
            self.wfile.write(json.dumps(post_body).encode())
        else:
            self.wfile.write(bytes("oi", "utf8"))
        return
예제 #9
0
async def check_service(request: CheckRequest) -> Verdict:
    async with API(request.hostname) as api:
        try:
            creds = get_reg_creds()
            status = await api.registration(creds)
            if status != 302:
                print(f'REGISTRATION: Wait 302, but return {status}')
                return Verdict.MUMBLE("Registration error")
            status = await api.update_user({
                "login": creds['login'],
                "additionalInfo": grs(25)
            })
            if status != 200:
                print(f'UPDATE USER: Wait 200, but return {status}')
                return Verdict.MUMBLE("Can't update user")
            status, res_json = await api.create_planner(get_planner())
            if status != 201 and len(res_json) != 0:
                print(
                    f'CREATE PANNER: Wait 201 with not empty json, but return {status} with {res_json}'
                )
                return Verdict.MUMBLE("Can't create planner")
            planner_id = res_json['id']
            status = await api.create_task(planner_id, get_task())
            if status != 201:
                print(f'CREATE TASK: Wait 201, but return {status}')
                Verdict.MUMBLE("Can't create task")
        except Exception as ex:
            print(traceback.format_exc())
            return Verdict.DOWN('DOWN')
    return Verdict.OK()
예제 #10
0
async def put_second_flag_into_the_service(request: PutRequest) -> Verdict:
    async with API(request.hostname) as api:
        try:
            creds = get_reg_creds()
            status = await api.registration(creds)
            if status != 302:
                print(f'ON PUT 2 REGISTRATION: Wait 302, but return {status}')
                return Verdict.MUMBLE("Registration error")

            planner = get_planner()
            status, planner = await api.create_planner(planner)
            if status != 201 or len(planner) == 0:
                print(f'ON GET 2 GET PLANNER: Wait 201, but return {status}')
                return Verdict.MUMBLE("Can't create planner")

            status, text = await api.get_planners()
            planner_id = planner["id"]

            if status != 200 or len(text.split(f'<tr id="{planner_id}">')) < 1:
                print(f'ON GET 2 GET PLANNERS: Wait 200, but return {status}')
                return Verdict.MUMBLE("Can't get planner")

            task = get_task()
            task['description'] = request.flag
            status = await api.create_task(planner_id, task)
            if status != 201:
                print(f'ON GET 2 CREATE TASK: Wait 201, but return {status}')
                Verdict.MUMBLE("Can't create task")

        except Exception as ex:
            print(traceback.format_exc())
            return Verdict.DOWN('DOWN')
    return Verdict.OK(f"{creds['login']}:{creds['password']}:{planner['id']}")
예제 #11
0
async def exploit():
    login = os.urandom(5).hex()
    flag = os.urandom(10).hex() + '=='

    async with API(HOSTNAME) as api:
        pub_key = await get_pub_key(api, login)
        s, h = await put_flag(api, login, flag)

        print('Real signature:', s.hex())
        print('Flag:', flag)

        parts = list(split_message(h, 8, 18))
        signature = split_signature(s, 16 * 2)

        fake_signature = []
        for i in range(len(parts) - 2):
            test_flag = await brute(i, parts)
            test_s, test_h = await put_flag(api, login, test_flag)
            fake_signature.append(split_signature(test_s, 16 * 2)[i])
        fake_signature.extend(split_signature(test_s, 16 * 2)[-2:])
        fake_signature = b''.join(fake_signature)

        print('Fake signature:', fake_signature.hex())
        print('Recovered?', fake_signature == s)
        recovered_flag = await get_flag(api, login, fake_signature.hex(),
                                        h.hex())
        print('Flag from service:', recovered_flag)
예제 #12
0
async def get_flag(request: GetRequest) -> Verdict:
    fuel_id = request.flag_id

    meat = flag_meat()
    index = randint(0, len(meat) - 1)
    payload = meat[:index] + request.flag + meat[index:]

    result = f'{request.flag} ({index} -> {index + len(request.flag) - 1})'

    async with API(request.hostname) as api:
        try:
            status, fuel_ids = await api.list_fuel()
        except Exception as ex:
            return Verdict.DOWN('Connection error', traceback.format_exc())

        if status != 200 or fuel_id not in fuel_ids:
            return Verdict.CORRUPT('Can\'t find fuel', f'Status: {status}')

        try:
            status, response = await api.check_fuel_property(fuel_id, payload)
        except Exception as ex:
            return Verdict.DOWN('Connection error', traceback.format_exc())

        if status != 200 or response != result:
            return Verdict.CORRUPT('Can\'t check property',
                                   f'Status: {status}')

    return Verdict.OK()
예제 #13
0
    def do_GET(self):
        path = self.path
        api = API(path, self.headers)
        options = api.options
        params = api.params

        try:
            processed_params = api.preprocess_params(params, **options)
            result = api.execute_request(path, **processed_params)
            result = api.postprocess_result(result, **options)
            response = api.generate_response(result, path, **processed_params)

        except OptionsException as options_exception:
            return self.yell(body=bytes(options_exception))

        except PermissionsException:
            return self.do_AUTHHEAD()

        except ExecutionException as execution_exception:
            return self.yell(
                status_code=execution_exception.status_code,
                body=bytes(execution_exception)
            )

        return self.respond(body=bytes(response))
예제 #14
0
def main():
    uvicorn.run(
        app=API(),
        host=config.HOST,
        port=config.PORT,
        log_level=config.LOG_LEVEL
    )
def show_categories(section_id):
    """
    Categories page
    :param section_id: Selected section ID
    :return:
    """
    api = API()

    for item in api.get_categories(int(section_id)):
        # list item:
        li = ListItem(
            item['name'].capitalize(),
            iconImage='{0}/{1}'.format(config['urls']['calm_arts_host'],
                                       item['image']),
            thumbnailImage='{0}/{1}'.format(config['urls']['calm_arts_host'],
                                            item['image']))
        li.setArt({
            'fanart':
            '{0}{1}'.format(config['urls']['calm_blurred_arts_host'],
                            item['image'])
        })
        # directory item:
        addDirectoryItem(
            PLUGIN.handle,
            PLUGIN.url_for(show_channels,
                           section_id=section_id,
                           category_id=item['id']), li, True)
    # end of directory:
    endOfDirectory(PLUGIN.handle)
    executebuiltin('Container.SetViewMode({0})'.format(
        config['viewmodes']['thumbnail'][getSkinDir() if getSkinDir(
        ) in config['viewmodes']['thumbnail'] else 'skin.confluence']))
예제 #16
0
def save_macaddress():
    mac_local = RpiDatabase().get_all_mac()
    mac_server = API().get_server(api['Macaddress'])
    lcd_.teks(text1='MENGAMBIL', text2='DATA', text3='MACADDRESS')
    time.sleep(1.2)
    if mac_server is 'ServerConnectionError' or mac_server is None:
        #tampilkan bahwa koneksi error
        lcd_.teks(text1='GAGAL', text2='MENGAMBIL', text3='DATA MACADDRESS')
        time.sleep(1.2)
    else:
        for progress, mac_server_ in enumerate(mac_server):
            lcd_.progress_bar(progress + 1,
                              len(mac_server),
                              text="CHECKING MAC")
            lcd_.disp.image(lcd_.image)
            lcd_.disp.display()
            #check_macaddress_exists
            if RpiDatabase().is_macaddress_registered(
                    mac_server_['macaddress']):
                # print 'mac terdaftar'
                continue
            else:
                # print 'mendaftarkan'+mac_server_['macaddress']
                RpiDatabase().insert('macaddress', 'mac_',
                                     mac_server_['macaddress'])
예제 #17
0
    def __init__(self, wrapper):
        self.wrapper = wrapper
        self.api = API(wrapper, "Web", internal=True)
        self.log = log.PluginLog(self.wrapper.log, "Web")
        self.config = wrapper.config
        self.socket = False
        self.data = storage.Storage("web", self.log)
        if "keys" not in self.data: self.data["keys"] = []
        #if not self.config["Web"]["web-password"] == None:
        #			self.log.info("Changing web-mode password because web-password was changed in wrapper.properties")
        #			self.data["password"] = md5.md5(self.config["Web"]["web-password"]).hexdigest()
        #			self.config["Web"]["web-password"] = None
        #			self.wrapper.configManager.save()

        self.api.registerEvent("server.consoleMessage", self.onServerConsole)
        self.api.registerEvent("player.message", self.onPlayerMessage)
        self.api.registerEvent("player.join", self.onPlayerJoin)
        self.api.registerEvent("player.leave", self.onPlayerLeave)
        self.api.registerEvent("irc.message", self.onChannelMessage)
        self.consoleScrollback = []
        self.chatScrollback = []
        self.memoryGraph = []
        self.loginAttempts = 0
        self.lastAttempt = 0
        self.disableLogins = 0
예제 #18
0
def task1():
    email = EMail()
    body = """
    <h1>测试图片</h1>
    <img src="cid:image1"/>    # 引用图片
    """

    try:
        driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps1)
        driver.implicitly_wait(10)
        api = API(driver)
        element = api.isElement(By.ID, 'et_pwd_login')
        if element:
            driver.find_element(by=By.ID, value='et_pwd_login').send_keys('lihang1988')
            driver.find_element(by=By.ID, value='btn_next').click()

        time.sleep(3)
        driver.save_screenshot('UEUNW17221002815.png')
        email.send_mail('打卡成功', content='打卡截图', image_body=body, image='UEUNW17221002815.png')

    except:
        email.send_mail('打开失败了,赶紧找人吧!')

    time.sleep(2)
    driver.quit()
예제 #19
0
파일: main.py 프로젝트: miguelfc/alligator2
    def all(cls, project_id, language, flags):
        api = API(project_id, language, flags)
        accounts = api.accounts()
        num_accounts = len(accounts)
        ac_ctr = 1

        for account in accounts:
            logging.info("Processing account {} of {}...".format(
                ac_ctr, num_accounts))
            account_name = account.get("name")
            locations = api.locations(account_name)
            num_locations = len(locations)
            loc_ctr = 1

            for location in locations:
                logging.info("Processing location {} of {}...".format(
                    loc_ctr, num_locations))
                location_name = location.get("name")
                if flags[INSIGHTS]:
                    api.insights(location_name)
                if flags[DIRECTIONS]:
                    api.directions(location_name)
                if flags[HOURLY_CALLS]:
                    api.hourly_calls(location_name)
                if flags[REVIEWS]:
                    api.reviews(location_name)

                loc_ctr = loc_ctr + 1
            ac_ctr = ac_ctr + 1

        if flags[SENTIMENT]:
            api.sentiments()
예제 #20
0
def task2():
    email = EMail()
    body = """
    <h1>测试图片</h1>
    <img src="cid:image1"/>    # 引用图片
    """

    try:
        driver = webdriver.Remote('http://*****:*****@qq.com', image_body=body, image='64de8478.png')

    except:
        email.send_mail('打开失败了,赶紧找人吧!')

    time.sleep(2)
    driver.quit()
예제 #21
0
    def __init__(self, parent=None, session=None, token=None):
        super().__init__(parent, Qt.Window)
        self.sizeMonitor = QApplication.desktop().availableGeometry()
        self.setGeometry(self.sizeMonitor.width() / 6, 0,
                         (2 * self.sizeMonitor.width()) / 3,
                         self.sizeMonitor.height())

        myForm = QFormLayout()

        # Create scroll and put in general layout
        scrollWidget = QWidget()
        scrollWidget.setLayout(myForm)
        scroll = QScrollArea()
        scroll.setWidget(scrollWidget)
        scroll.setWidgetResizable(True)
        layout = QVBoxLayout(self)
        layout.addWidget(scroll)

        downloader = DownloadDecorator(session)
        api = API(session, token)

        groups = api.groups.get(extended=1)
        for group in groups['response']['items']:
            downloader(group["photo_100"], 'None', 'group', group['name'],
                       group['id'])

        download = downloader.download()
        for item in download:
            g = Group(session=session, token=token)
            g.setGroup(item[0].content, item[3][0], item[3][1])
            myForm.addWidget(g)

        self.show()
예제 #22
0
	def validar(self):                               
		clear = lambda: os.system('cls')
		clear()
		self.list.delete(0, END)
		self.w.delete("all")
		self.dibujar()
		eng = pyttsx3.init()
		voices = eng.getProperty('voices')       #para reproducir la voz
		eng.setProperty('voice', voices[1].id)
		eng.setProperty('rate', 118)
		try:
			if len(self.palabra.get())%2 == 0:
				automata = APP("ab", self)
				aux = automata.crear_matriz()
				self.isPalindromePar(aux, "ab", self.palabra.get())
			else:
				automata = API("ab", "c", self)
				aux = automata.crear_matriz()
				self.isPalindromeImpar(self.palabra.get(), aux, "ab")
			self.list.insert(END, "Palabra Aceptada")
			eng.say("palabra aceptada")
			eng.runAndWait()
		except:
			self.list.insert(END, "Palabra No Aceptada")
			print(False)
			eng.say("palabra no aceptada")
			eng.runAndWait()
예제 #23
0
    def run_server(self):
        app = web.Application(middlewares=[])

        self.api = API(self.network_id, self.tx_storage)

        routes = {
            '/api/v1/leaderboard': self.api.handler_leaderboard,
            '/api/v1/progress': self.api.handler_sync_progress
        }

        for route, handler in routes.items():
            app.add_routes([web.get(route, handler)])

        # run bg tasks
        cfg = self.cfg.get('thorchain')

        app.on_startup.append(self.init_db)

        if bool(cfg.get('scanner.tx.enabled', True)):
            app.on_startup.append(self.run_scanner)
        else:
            logging.info('Scanner is disabled by Config')

        if bool(cfg.get('value_filler.enabled', True)):
            app.on_startup.append(self.run_fill_job)
        else:
            logging.info('Value filler is disabled by Config')

        api_port = int(self.cfg.get('api.port', 5000))
        web.run_app(app, port=api_port)
예제 #24
0
def push_all_jobs(sample_order):
    """get jobs for all cities, then push to download queue."""
    job_api = API()
    ok, summaries = job_api.summary()
    if not ok:
        return [0]
    return [push_city_jobs(s['city'], sample_order) for s in summaries]
예제 #25
0
 def populateAPIs(self, count=10):
     """
     "apiDefinition": "{ \"paths\": { \"/*\": { \"get\": { \"description\": \"Global Get\" } } }, \"swagger\": \"2.0\" }",
         "cacheTimeout": 10,
         "transport": ["https"],
         "policies": ["Unlimited"],
         "visibility": "PUBLIC",
         "businessInformation": {},
         "corsConfiguration": {}
     :param count:
     :return:
     """
     template = {
         "name": None,
         "context": None,
         "version": "1.0.0",
         "service_url": "http://sample.knnect.com/api/endpoint",
         "description": "",
         "wsdlUri": "http://www.webservicex.com/globalweather.asmx?wsdl",
         "isDefaultVersion": True,
         "responseCaching": "Disabled",
         "cacheTimeout": 300,
         "destinationStatsEnabled": "Disabled",
         "businessInformation": {
             "businessOwner": "Kasun Thennakoon",
             "businessOwnerEmail": "*****@*****.**",
             "technicalOwner": "Knnect",
             "technicalOwnerEmail": "*****@*****.**"
         },
         "tags": [
             "test_tag1",
             "fintech"
         ],
         "transport": [
             "http",
             "https"
         ],
         "visibility": "PUBLIC",
         "securityScheme": [
             "string"
         ],
         "scopes": [
             "string"
         ],
     }
     policies = ["Gold", "Silver", "Bronze"]
     apis = []
     for index in range(count):
         random_char = random.choice(
             string.ascii_lowercase) + random.choice(string.ascii_lowercase)
         name_context = "{}_sample_{}".format(random_char, index)
         template['name'] = name_context
         template['description'] = "A Sample API for testing APIM 3.0 " + name_context
         template['context'] = "/" + name_context
         api = API(**template)
         api.set_rest_client(self.client)
         api.save()
         api.set_policies(policies)
         apis.append(api)
     return apis
예제 #26
0
async def check_service(request: CheckRequest) -> Verdict:
    async with API(request.hostname) as api:
        try:
            await api.health_check()
        except Exception as ex:
            return Verdict.DOWN('', traceback.format_exc())
    return Verdict.OK()
예제 #27
0
def main():
    os.listdir(os.getenv('BASEPATH_DATA'))
    # db
    db = MONGODB[os.getenv('MONGODB_DATABASE')]
    db.command('ping')

    # api
    api = API(**settings.API)

    # parse
    WpPreparator.process('/data/wp_sample.xml', db)

    # import
    images = importer.ImageImporter(db, api)
    failed_images = images.upload_all()
    print(len(failed_images))

    authors = importer.AuthorsImporter(db, api)
    failed_authors = authors.upload_all()
    print(len(failed_authors))

    sections = importer.SectionsImporter(db, api)
    failed_sections = sections.upload_all()
    print(len(failed_sections))

    posts = importer.PostsImporter(db, api)
    failed_posts = posts.upload_all()
    print(len(failed_posts))
예제 #28
0
async def get_flag_lwe(request: GetRequest) -> Verdict:
    login, note_hash, signature = request.flag_id.split(':')
    algo = 'lwe'

    async with API(request.hostname) as api:
        try:
            users = await api.get_users()
            if login not in users['users']:
                return Verdict.MUMBLE('No user', 'No user')
        except Exception as e:
            return Verdict.MUMBLE("Can't get users", traceback.format_exc())

        try:
            notes = await api.get_notes(algo, login)
            if note_hash not in notes['notes']:
                return Verdict.MUMBLE('No note', 'No note')
        except Exception as e:
            return Verdict.MUMBLE("Can't get notes", traceback.format_exc())

        try:
            pub_key = await api.get_pub_key(algo, login, note_hash)
            pub_key = list(list(map(int, x.split(','))) for x in b64decode(pub_key['pub_key']).decode().split(';'))
        except Exception as e:
            return Verdict.MUMBLE("No public key", traceback.format_exc())
        
        try:
            verified = await api.verify(algo, login, signature, note_hash)
            flag = verified['data']
        except Exception as e:
            return Verdict.MUMBLE("Can't validate", traceback.format_exc())

        if flag != request.flag:
            return Verdict.MUMBLE('Wrong data')
        return Verdict.OK()
예제 #29
0
 def set_access_token(self, access_token, expires):
     '''
         set access_token and expires time to this instance
     '''
     self.access_token = access_token
     self.expires = float(expires)
     self.api = API(access_token, self.client_secret)
예제 #30
0
    def process(self, url):
        """ Downloads all requested files from specified server """
        self.ignored = 0
        self.not_selected = 0
        self.processed = 0

        api = API(url, self.user, self.password)

        if self.recording_id:
            recording = api.get(self.recording_id).get("recording")
            self._download(recording, api, Path(self.out_folder))
            return
        print("Querying server {0}".format(url))
        print("Limit is {0}".format(self.limit))
        print("Tag mode {0}".format(self.tag_mode))
        print("Dates are {0} - {1}".format(self.start_date, self.end_date))
        print("Required tags are {0}".format(self.only_tags))
        print("Ignore tags are {0}".format(self.ignore_tags))

        rows = api.query(
            limit=self.limit,
            startDate=self.start_date,
            endDate=self.end_date,
            tagmode=self.tag_mode,
            tags=self.only_tags,
        )

        if self.auto_delete:
            self.update_file_locations()

        pool = Pool(self.workers, self._downloader, api, Path(self.out_folder))
        for row in rows:
            pool.put(row)
        pool.stop()