Beispiel #1
0
def groups_group_add(request):
    if request.user.get_profile().is_card:
        raise Http404
    context = {}
    print 'get = %s'%request.GET
    if request.GET.get('popup_window') == '1':
        context['popup_window'] = True
    else:
        context['popup_window'] = False
    context["title"] = _(u"Adding a group of numbers")
    user_id = None
    if request.GET:
        user_id = request.GET.get("user_id")
        if request.user.is_staff and user_id:
            user_id = int(user_id)
        else:
            user_id = None
    if user_id:
        user = User.objects.get(id = user_id)
        context["to_user"] = user
    else:
        user = request.user
    profile = user.get_profile()
    bac = profile.billing_account
    numbers = []
    try:
        
        numbers = TelNumber.objects.filter(account = bac)
        
        existing_groups = TelNumbersGroup.objects.filter(account = bac)
        
    except Exception, e:
        log.add("Exception 1 in telnumbers.views.group_add: '%s'" % e)
        raise e
Beispiel #2
0
def external_number_delete(request, number_id):
    try:
        package_obj = Package_on_connection_of_service.objects.get(user=request.user, activate=False, deactivate=False)
    except Package_on_connection_of_service.DoesNotExist:
        successfully_create = create_package(request.user, \
                                '/account/localphones/delete/%s/' % number_id, \
                                reverse('external_phones_list'), \
                                '',
                                ['localphone_detach'])
        if not successfully_create:
            raise Http404
        else:
            return HttpResponseRedirect('/account/localphones/delete/%s/' % number_id)
    try:
        now = datetime.datetime.now()
        date_next_start_month_temp = now + relativedelta(months=1)
        date_next_start_month = datetime.datetime(date_next_start_month_temp.year, date_next_start_month_temp.month, 1, 0, 0, 0)
        ext_number_obj = ExternalNumber.objects.get(id=number_id)
        profile = Profile.objects.get(user=request.user)
        bac = profile.billing_account
        zakaz = Zakazy.objects.get(ext_numbers=ext_number_obj, bill_account=bac, date_deactivation=None)
        zakaz.date_deactivation = date_next_start_month
        zakaz.save()
        package_obj.activate = True
        package_obj.save()
        request.notifications.add(_(u"Номер успешно откреплен!"), "success")
    except Exception, e:
        log.add("Exception in external_number_delete: '%s'" % str(e).decode('utf-8'))
        exc_type, exc_obj, exc_tb = sys.exc_info()  # @UnusedVariable
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        log.add("Exception in external_number_delete: file:%s line:%s" % (fname, exc_tb.tb_lineno))
        request.notifications.add(_(u"Не удалось удалить номер, обратитесь в техподдержку!"), "warning")
Beispiel #3
0
def pause_connect(request):
    user = request.user
    package = Package_on_connection_of_service.objects.get(user = user, activate = False, deactivate = False)
    param = eval(package.data)
    profile = user.get_profile()
    account = profile.billing_account
    try:
        with xact():
            with xact(using = settings.BILLING_DB):
                external_number = ExternalNumber.objects.get(number = param['numbers'][0])
                old_zakaz = deactivate_zakaz(account, PAUSE_SERVICE_TYPE, external_number)
                zakaz = Zakazy.objects.get(ext_numbers = external_number, bill_account = account, status_zakaza_id = STATUS_ZAKAZA_DEACTIVATED, service_type_id = ABON_SERVICE_TYPE)
                zakaz.date_deactivation = None
                zakaz.status_zakaza_id = STATUS_ZAKAZA_ACTIVE
                zakaz.save()
                cost = float(cost_dc(zakaz.id))
                zakaz.cost = '%.2f' % cost
                zakaz.save()
                external_number.is_reserved = False
                external_number.save()
                package.activate = True
                package.save()
                findocs = [FinDocSigned.objects.filter(findoc__slug = '800_forma', signed_by = user).order_by('-id')[0]]
                send_to = send_docs(user, findocs, 'INSTRUCTION_PAUSE_CONNECT_800')
                request.notifications.add(u'На %s отправлено письмо с дальнейшими инструкциями для восстановления обслуживания номера!' % send_to, "success")
    except Exception, e:
        package.deactivate = True
        package.save()
        log.add("number800.py connect Exception: %s" % e)
        request.notifications.add(_(u"Произошла непредвиденная ошибка, обратитесь в техподдержку!"), "warning")
Beispiel #4
0
def connect(request, param={}):
    user = request.user
    profile = user.get_profile()
    package = Package_on_connection_of_service.objects.get(user = user, activate = False, deactivate = False)
    if not param:
        param = package.data
    if not param:
        request.notifications.add(_(u"Произошла непредвиденная ошибка, обратитесь в техподдержку!"), "warning")
        return HttpResponseRedirect(reverse("8800_list"))
    param = eval(param)
    account = profile.billing_account
    now = datetime.now()
    try:
        with xact():
            with xact(using = settings.BILLING_DB):
                if param.has_key('group_id'): # Получаем группу
                    group = TelNumbersGroup.objects.get(pk = param['group_id'])
                else:
                    group = create_group(profile, account)
                for number in param['numbers']:
                    external_number = ExternalNumber.objects.get(number = number)
                    bind_number(external_number, group = group, region = NUMBER800_REGION, account = account, date = now)
                    tariff =  ExternalNumberTarif.objects.get(id = external_number.tarif_group)
                    zakaz = create_zakaz(account, ABON_SERVICE_TYPE, external_number)
                    join_zakaz_and_docs(package, zakaz, profile.user)
                findocs = [FinDocSigned.objects.filter(findoc__slug = '800_contract', signed_by = user).order_by('-id')[0]]
                send_to = send_docs(user, findocs, 'INSTRUCTION_800')
                package.activate = True
                package.save()
                request.notifications.add(u'На %s отправлено письмо с дальнейшими инструкциями для подключения номера!' % send_to, "success")
    except Exception, e:
        package.deactivate = True
        package.save()
        log.add("number800.py connect Exception: %s" % e)
        request.notifications.add(_(u"Произошла непредвиденная ошибка, обратитесь в техподдержку!"), "warning")
def add_group(request, user_id):
    "Добавление новой группы"
    try:
        user = User.objects.get(id = user_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.admin_groups.TelNumbersGroupAdmin.add_group: '%s'" % e)
        raise Http404
Beispiel #6
0
def send_email(to_addr, subject, content, debug=True):
    if not all(
        [x in os.environ for x in ["SMTP_LOGIN", "SMTP_PASS", "SMTP_FROM"]]):
        log.add("env variables missing")
        raise KeyError("missing environmental variables needed for SMTP!")

    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = os.environ.get("SMTP_FROM")
    msg["To"] = to_addr
    msg.set_content(content)

    try:
        if debug:
            server = smtplib.SMTP(SMTP_CONFIG["DEBUG_SERVER"],
                                  SMTP_CONFIG["DEBUG_PORT"])
            server.set_debuglevel(1)
            server.send_message(msg)
        else:
            server = smtplib.SMTP_SSL(SMTP_CONFIG["SERVER"],
                                      SMTP_CONFIG["PORT"])
            server.ehlo()
            server.login(os.environ.get("SMTP_LOGIN"),
                         os.environ.get("SMTP_PASS"))
            server.send_message(msg)
    except Exception as e:
        log.add(e)
    finally:
        server.close()
 def CalculateChanges(self):
     """
         Рассчитывает изменения в таблице тарифов и готовит списки с этими изменениями, чтобы потом разом всё применить
     """
     if self.debug: print datetime.now(), "parser.CalculateChanges()"; log.add("parser.CalculateChanges()")
     
     try:
         # переберем все распарсенные тарифы для импортирования
         for tel_zone in self.parsed_tariffs.keys():
             new_t = Tariff()
             new_t.tel_zone = tel_zone
             new_t.billing_group = self.billing_group
             new_t.start_date = self.parsed_tariffs[tel_zone]["start_date"]
             new_t.end_date = self.parsed_tariffs[tel_zone]["end_date"]
             new_t.price = self.parsed_tariffs[tel_zone]["price"]
             c_line = self.parsed_tariffs[tel_zone]["line_num"]
             
             self.add_list.append(new_t)
     except Exception, e:
         # непонятно, правда, откуда тут может быть эксцепшн, но все же...
         self.had_stop = True
         msg = "Exception in CalculateChanges!!! Message: " + str(e)
         self.add_error(
             msg
         )
         log.add(msg)
Beispiel #8
0
def _serverThread():
    s = None
    socketOk = False
    while not socketOk:
        try:
            log.add(
                log.LEVEL_DEBUG, "Setup server socket on {}:{}".format(
                    settings.getSocketIp(), settings.getSocketPort()))
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((settings.getSocketIp(), settings.getSocketPort()))
            s.listen(1)
            socketOk = True
        except:
            time.sleep(10)

    while True:
        conn, addr = s.accept()
        log.add(log.LEVEL_DEBUG, "Socket connection from {}".format(addr))
        data = conn.recv(8192)
        if len(data) > 0:
            log.add(log.LEVEL_DEBUG, "Incoming req: {}".format(data))
            rsp = _handleReq(data)
            if rsp and len(rsp) > 0:
                log.add(log.LEVEL_DEBUG, "Send rsp: {}".format(rsp))
                conn.send(rsp)
        conn.close()
        log.add(log.LEVEL_DEBUG, "Closed connection")
Beispiel #9
0
def getIdByURL(url):
    #print "getIdByURL: %s" % url

    # TODO: solucionar URL's con Ñ
    try:
        urlhash = hashlib.sha1(url).hexdigest()
        _id = getIdByHash(urlhash)
        if _id is None:
            # obtenemos id de host
            o = urlparse(url)
            id_host = getHostIdByHost(o.hostname)
            # creamos enlace
            _url = url.replace("'", "\\'")
            sql = "INSERT INTO as_pages (`hash`, `url`, `id_host`, `id_contenttype`, `id_charset`, `time_fetch`, `value`) VALUES ('%s', '%s', %d, 0, 0, 0, 0)" % (
                urlhash,
                _url,
                id_host,
            )
            dbm.query(sql)
            _id = dbm.lastrowid
            # creamos entrada en caché
            cache.create(_id)

        return _id
    except UnicodeEncodeError:
        log.add('UnicodeEncodeError: getIdByURL: url = %s' % url)
        return 0
Beispiel #10
0
def payment_wm_card_start(request):
    "Создает новый платеж и редиректит на страницу оплаты вебманями"
    context = {}
    context['hide_review'] = True
    if request.method == 'GET':
#        if (not request.GET.has_key('amount')
#            or request.GET.get('amount') not in (u'50', u'100', u'150')):
#            raise Http404
        # context['amount'] = request.GET.get('amount')
        context['meta_title'] = u'Покупка карты Webmoney %s' % request.GET.get('amount')
        form = WMPaymentRequestFormCard()
        context['wm_form'] = form
        # return render_to_response('wm_card.html', context)
        return panel_base_auth(request, context)

    if request.method == 'POST':
        form = WMPaymentRequestFormCard(request.POST.copy())
        context['wm_form'] = form
        if not form.is_valid():
            request.notifications.add(u"Ошибка в заполнении полей", "error")
            # return render_to_response('wm_card.html', context)
            return panel_base_auth(request, context)
        email = form.cleaned_data.get('email', '')
        phone_sms = form.cleaned_data.get('phone_sms', '')
        amount = form.cleaned_data.get('amount')
        if not email and not phone_sms:
            request.notifications.add(u"Вам необходимо указать адрес электронной почты или номер мобильного телефона", "error")
            # return render_to_response('wm_card.html', context)
            return panel_base_auth(request, context)

        context = {}
        context['hide_review'] = True
        context['site'] = settings.CURRENT_SITE
        try:
            # amount = request.GET.get('amount')
            inv = Invoice_wm()
            inv.amount = amount
            inv.desc = _(u"Покупка карты предоплаты %s" % amount)
            inv.currency = 'RUB'
            inv.type = 2
            inv.payer_phone_number = phone_sms
            inv.payer_email = email
            inv.save()

            context["merchant_id"] = payment_settings.WM_MERCHANT_ID
            context["amount"] = inv.amount
            context["currency"] = inv.currency
            context["payment_id"] = inv.id  # наш внутренний номер платежа
            context["payment_name"] = inv.desc  # название платежа
            context["payment_name_base64"] = base64.standard_b64encode(inv.desc.encode('utf-8'))  # название платежа в base64 в (utf-8!!!)
            context["sim_mode"] = payment_settings.WM_SIM_MODE
            context["payer_phone_number"] = inv.payer_phone_number  # номер телефона пользователя
            context["payer_email"] = inv.payer_email  # почта пользователя
            context["account_id"] = ""  # id пользователя в биллинге
            context["type"] = inv.type  # тип платежа
            return panel_base_auth(request, context)
        except Exception, e:
            log.add(u"payment_wm_start Except: %s" % e)
            return {}
Beispiel #11
0
def list_user_groups(request, user_id):
    "Отображает список групп указанного пользователя для их редактирования"
    context = get_ready_context(request, _(u"User's groups"))
    try:
        user = User.objects.get(id = user_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.admin_groups.TelNumbersGroupAdmin.list_user_groups: '%s'" % e)
        raise Http404
Beispiel #12
0
def delete_group(request, group_id):
    "Удаление выбранной группы"
    context = get_ready_context(request, _(u"Delete group"))
    try:
        group = TelNumbersGroup.objects.get(id = group_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.admin_groups.TelNumbersGroupAdmin.delete_group: '%s'" % e)
        raise Http404
Beispiel #13
0
def edit_group(request, group_id):
    "Редактирование выбранной группы"
    context = get_ready_context(request, _(u"Edit group"))
    try:
        group = TelNumbersGroup.objects.get(id = group_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.admin_groups.TelNumbersGroupAdmin.edit_group: '%s'" % e)
        raise Http404
Beispiel #14
0
def findocs_application_sign(request, app_id):
    user = request.user
    context = {}
    try:
        # таблица fin_docs_applications
        app = FinDocSignApplication.objects.get(id=app_id)
    except Exception, e:
        log.add("Exception 1 in findocs.views.findocs_application_sign: '%s'" % e)
        raise Http404
Beispiel #15
0
def _updateSwitch():
	if not _manualOverride:
		if timer.active():
			log.add( log.LEVEL_INFO, "Timer ON" )
			relay.setOn()
		else:
			log.add( log.LEVEL_INFO, "Timer OFF" )
			relay.setOff()
	threading.Timer(settings.getUpdateTimerIntervalSec(), _updateSwitch).start()
Beispiel #16
0
def _updateSwitch():
    if not _manualOverride:
        if timer.active():
            log.add(log.LEVEL_INFO, "Timer ON")
            relay.setOn()
        else:
            log.add(log.LEVEL_INFO, "Timer OFF")
            relay.setOff()
    threading.Timer(settings.getUpdateTimerIntervalSec(),
                    _updateSwitch).start()
Beispiel #17
0
def _cbExtIfcSun(req):
    log.add(log.LEVEL_DEBUG, "Req. sun info")
    now = datetime.datetime.utcnow()
    sunriseToday, sunsetToday = SunriseSunset(
        now,
        latitude=settings.getLatitude(),
        longitude=settings.getLongitude()).calculate()
    rsp = "SUNRISE={}Z;SUNSET={}Z".format(sunriseToday.isoformat(),
                                          sunsetToday.isoformat())
    return rsp
Beispiel #18
0
def robokassa_pay(request, type_pay="full"):
    context = dict()

    if type_pay == "qiwi":
        context["pay_title"] = u"терминал Qiwi"
        context["in_curr"] = u"Qiwi30OceanR"

    else:
        context["pay_title"] = u"терминал Robokassa"
        context["in_curr"] = u""

    formclass = robokassa_money_bank
    profile = request.user.get_profile()
    if profile.is_juridical:
        # raise Http404
        context['no_payment'] = True
    context['placement'] = 1
    form = formclass()
    if request.POST:
        form = formclass(request.POST)
        if form.is_valid():
            try:

                in_rk = Invoice_rk()
                in_rk.account = profile.billing_account
                in_rk.type = 1
                in_rk.operator = context["in_curr"]
                in_rk.amount = int(form.cleaned_data['money'])
                in_rk.desc = "Пополнение счета через Robokassa"
                in_rk.save()

                context["mrh_login"] = "******"  # Идентификатор магазина
                context["mrh_pass1"] = "ndjhtw1ldjhwf"  # Пароль 1
                context["inv_id"] = in_rk.pk  # Номер заказа
                context["inv_desc"] = "Пополнение счета"  # Описание
                context["out_summ"] = form.cleaned_data['money']  # Количество денег
                context["culture"] = "ru"
                context["Shp_accountid"] = profile.billing_account.id
                context["Shp_operationtype"] = 1
                m = hashlib.md5()
                m.update(context["mrh_login"] + ":" + str(context["out_summ"]) + ":" + str(context["inv_id"]) + \
                                 ":" + context["mrh_pass1"] + ":Shp_accountid=" + str(context["Shp_accountid"]) \
                                 + ":Shp_operationtype=" + str(context["Shp_operationtype"]))
                context["crc"] = m.hexdigest()

                return context
            except Exception, e:
                log.add(u"payment_robokassa_start Except: %s" % e)
                raise Http404
        else:
            context['form'] = form
            request.notifications.add(u"Ошибка в заполнении полей", "error")
            return context
Beispiel #19
0
def _cbExtIfcSetSettings( req ):
	log.add( log.LEVEL_DEBUG, "Set settings" )
	reqList = req.split( ";" )
	for s in reqList:
		settingsPair = s.split( "=" )
		if ( len( settingsPair ) == 2 ):
			if ( settingsPair[ 0 ] == "LATITUDE" ):
				settings.setLatitude( settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "LONGITUDE" ):
				settings.setLongitude( settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "TIME_ZONE" ):
				tzStr = settingsPair[ 1 ].replace( "\\", "/" ) 
				settings.setTimeZone( tzStr )
			elif ( settingsPair[ 0 ] == "SUNRISE" ):
				boolStr = settingsPair[ 1 ].lower()
				settings.setSunriseEnabled( boolStr )
			elif ( settingsPair[ 0 ] == "SUNRISE_OFF_DIFF_MINUTES" ):
				settings.setSunriseOffTimeDelta( settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_MON" ):
				settings.setSunriseOnTime( "mon", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_TUE" ):
				settings.setSunriseOnTime( "tue", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_WED" ):
				settings.setSunriseOnTime( "wed", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_THU" ):
				settings.setSunriseOnTime( "thu", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_FRI" ):
				settings.setSunriseOnTime( "fri", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_SAT" ):
				settings.setSunriseOnTime( "sat", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNRISE_ON_SUN" ):
				settings.setSunriseOnTime( "sun", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET" ):
				boolStr = settingsPair[ 1 ].lower()
				settings.setSunsetEnabled( boolStr )
			elif ( settingsPair[ 0 ] == "SUNSET_ON_DIFF_MINUTES" ):
				settings.setSunsetOnTimeDelta( settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_MON" ):
				settings.setSunsetOffTime( "mon", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_TUE" ):
				settings.setSunsetOffTime( "tue", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_WED" ):
				settings.setSunsetOffTime( "wed", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_THU" ):
				settings.setSunsetOffTime( "thu", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_FRI" ):
				settings.setSunsetOffTime( "fri", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_SAT" ):
				settings.setSunsetOffTime( "sat", settingsPair[ 1 ] )
			elif ( settingsPair[ 0 ] == "SUNSET_OFF_SUN" ):
				settings.setSunsetOffTime( "sun", settingsPair[ 1 ] )
	settings.write()
	return "OK"
Beispiel #20
0
def external_edit(request, number_id):
    "Отображает форму редактирования внешнего номера пользователя"
    user = request.user
    profile = user.get_profile()
    if profile.is_card:
        raise Http404
    bac = profile.billing_account
    try:
        number = ExternalNumber.objects.get(id=number_id)
    except Exception, e:
        log.add("Exception 1 in externalnumbers.views.external_edit: '%s'" % e)
        raise e
Beispiel #21
0
 def getValue(self):
     option = self.args[0]
     request = self.init_kwargs["request"]
     user = request.user
     profile = user.get_profile()
     bac = profile.billing_account
     app_id = self.init_kwargs["findocapp_id"]
     try:
         app = FinDocSignApplication.objects.get(id=app_id)
     except Exception, e:
         log.add("Exception 1 in %s.GetVariables.ExternalNumberVarValue: '%s'" % (__name__, e))
         return "<WAS EXCEPTION WHEN GETTING APPLICATION BY ID - in %s.GetVariables.ExternalNumberVarValue>" % __name__
Beispiel #22
0
def findocs_show_signed(request, signed_id):

    user = request.user
    profile = user.get_profile()
    if profile.is_card:
        raise Http404

    context = {}
    try:
        sd = FinDocSigned.objects.get(id=signed_id)
    except Exception, e:
        log.add("Exception 1 in findocs.views.findocs_list_signed: '%s'" % e)
        raise Http404
Beispiel #23
0
def _cbExtIfcGetSettings( req ):
	log.add( log.LEVEL_DEBUG, "Get settings" )
	rsp = "SETTINGS;LATITUDE={};LONGITUDE={};TIME_ZONE={};".format( settings.getLatitude(), settings.getLongitude(), settings.getTimeZone() )
	rsp += "SUNSET={};SUNSET_ON_DIFF_MINUTES={};".format( settings.getSunsetEnabled(), int( settings.getSunsetOnTimeDelta().total_seconds() / 60 ) ).upper()
	rsp += "SUNSET_OFF_MON={};SUNSET_OFF_TUE={};SUNSET_OFF_WED={};SUNSET_OFF_THU={};".format( settings.getSunsetOffTime( 0 ), 
		settings.getSunsetOffTime( 1 ), settings.getSunsetOffTime( 2 ), settings.getSunsetOffTime( 3 ) )
	rsp += "SUNSET_OFF_FRI={};SUNSET_OFF_SAT={};SUNSET_OFF_SUN={};".format( settings.getSunsetOffTime( 4 ), 
		settings.getSunsetOffTime( 5 ), settings.getSunsetOffTime( 6 ) )
	rsp += "SUNRISE={};SUNRISE_OFF_DIFF_MINUTES={};".format( settings.getSunriseEnabled(), int( settings.getSunriseOffTimeDelta().total_seconds() / 60 ) ).upper()
	rsp += "SUNRISE_ON_MON={};SUNRISE_ON_TUE={};SUNRISE_ON_WED={};SUNRISE_ON_THU={};".format( settings.getSunriseOnTime( 0 ), 
		settings.getSunriseOnTime( 1 ), settings.getSunriseOnTime( 2 ), settings.getSunriseOnTime( 3 ) )
	rsp += "SUNRISE_ON_FRI={};SUNRISE_ON_SAT={};SUNRISE_ON_SUN={}".format( settings.getSunriseOnTime( 4 ), 
		settings.getSunriseOnTime( 5 ), settings.getSunriseOnTime( 6 ) )
	return rsp
Beispiel #24
0
def external_delete(request, number_id):
    "Удаление внешнего номера"
    user = request.user
    profile = user.get_profile()
    if profile.is_card:
        raise Http404
#    if not profile.is_juridical:
#        raise Http404
    bac = profile.billing_account
    try:
        number = ExternalNumber.objects.get(id=number_id)
    except Exception, e:
        log.add("Exception 1 in externalnumbers.views.external_edit: '%s'" % e)
        raise e
Beispiel #25
0
 def withdraw_funds(self, value, cause=u""):
     "Снимает средства с баланса пользователя и создает запись в журнале операций по балансу"
     if hasattr(settings, "WITHDRAW_FUNDS"):
         if not settings.WITHDRAW_FUNDS:
             log.add("withdraw_funds. user='******' value='%s' cause='%s'" % (self.user, value, cause))
             return
     BalanceOperation(
         operation_type=OP_TYPE_WITHDRAW,
         user=self.user,
         value=value,
         cause=cause
     ).save()
     bac = self.billing_account
     bac.ballance -= value
     bac.save()
Beispiel #26
0
def _getOnPeriodSunrise(sunrise):
    # stop based on sunrise
    stop = sunrise + settings.getSunriseOffTimeDelta()
    startLocalTime = settings.getSunriseOnTime(stop.weekday())
    start = datetime.datetime.combine(stop.date(), startLocalTime)
    # convert local to UTC
    start = _local2utc(start)
    # check if prev day
    if stop < start and startLocalTime > datetime.time(12):
        log.add(
            log.LEVEL_TRACE,
            "Start time past midnight, decrease start with one day: {} --> {}".
            format(start, start - datetime.timedelta(days=1)))
        start = start - datetime.timedelta(days=1)
    return start, stop
Beispiel #27
0
def groups_group_delete(request, group_id):
    
    if request.user.get_profile().is_card:
        raise Http404
    context = {}
    context["title"] = _(u"Deleting the group of numbers")
    user = request.user
    profile = user.get_profile()
    bac = profile.billing_account
    numbers = []
    try:
        numbers = TelNumber.objects.filter(account = bac)
        group = TelNumbersGroup.objects.get(id = group_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.views.group_delete: '%s'" % e)
        raise e
Beispiel #28
0
def save_model_number(id, number, add, profile, duration, from_file):
    try:
        model_number = ObzvonNumber(
        billing_account_id=profile.billing_account_id,
        number=number,
        add_number=add,
        id_obzvon_id=id,
        duration=duration,
        number_from_file=from_file,)
        model_number.save()
    except Exception, e:
        import log
        log.add("Exception in save_model_number: '%s'" % e)
        exc_type, exc_obj, exc_tb = sys.exc_info()  # @UnusedVariable
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        log.add("Exception in save_model_number: file:%s line:%s" % (fname, exc_tb.tb_lineno))
Beispiel #29
0
def _getOnPeriodSunset(sunset):
    # start based on sunset
    start = sunset + settings.getSunsetOnTimeDelta()
    stopLocalTime = settings.getSunsetOffTime(start.weekday())
    stop = datetime.datetime.combine(start.date(), stopLocalTime)
    # convert local to UTC
    stop = _local2utc(stop)

    # check if stop next day
    if stop < start and stopLocalTime <= datetime.time(12):
        log.add(
            log.LEVEL_TRACE,
            "Stop time past midnight, add one day to stop: {} --> {}".format(
                stop, stop + datetime.timedelta(days=1)))
        stop = stop + datetime.timedelta(days=1)
    return start, stop
Beispiel #30
0
def groups_list(request):
    if request.user.get_profile().is_card:
        raise Http404
    context = {}
    context["title"] = _(u"Groups of numbers")
    user = request.user
    profile = user.get_profile()
    bac = profile.billing_account
    has_phones = (bac.phones.count() > 0)
    context["has_phones"] = has_phones
    context["add"] = True
    groups = None
    try:
        groups = TelNumbersGroup.objects.filter(account = bac)
    except Exception, e:
        log.add("Exception 1 in telnumbers.views.groups_list: '%s'" % e)
        raise e
Beispiel #31
0
def account_phone_edit(request, tel_number_id):

    if request.user.get_profile().is_card:
        raise Http404
    "Редактирование выбранного номера"
    user = request.user
    profile = user.get_profile()
#    if not profile.is_juridical:
#        raise Http404
    bac = profile.billing_account
    context = {}
    context["current_view_name"] = "account_phones_list"
    try:
        phone = TelNumber.objects.get(id=tel_number_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.views.account_phone_edit: '%s'" % e)
        raise e
Beispiel #32
0
def step_2_reg(request):
    context = {}
    errors = {}
    form_reg = UserRegistrationForm(request.GET)
    context['form_reg'] = form_reg
    try:
        param = simplejson.loads((str(request.GET['data'])).strip('/'))
        param['redirect_after_reg'] = reverse('add_number_final')
        context['id_tarif'] = param['id_tarif']
        context['icode'] = param['icode']
        param['numbers']


        context['data'] = simplejson.dumps(param)
    except Exception, e:
        exc_type, exc_obj, exc_tb = sys.exc_info()  # @UnusedVariable
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        log.add("step_2_reg: file:%s row:%s e:%s" % (fname, exc_tb.tb_lineno, e))
        raise Http404
Beispiel #33
0
def payment_wm(request):
    "Отображает интерфейс для оплаты вебманями"
    profile = request.user.get_profile()

    if profile.is_juridical:
        raise Http404
    user = request.user
    context = {}
    form = webmoney_money()
    if request.POST:
        form = webmoney_money(request.POST)
        if form.is_valid():
            try:
                profile = user.get_profile()
                inv = Invoice_wm()
                inv.amount = form.cleaned_data['money']
                inv.desc = _(u"Пополнение счета через WebMoney")
                inv.account = profile.billing_account
                inv.currency = 'RUB'
                inv.type = 1
                # inv.payer_phone_number = request.POST.get("LMI_PAYER_PHONE_NUMBER", "")
                inv.payer_email = request.POST.get("LMI_PAYER_EMAIL", "")
                inv.save()

                context["merchant_id"] = payment_settings.WM_MERCHANT_ID
                context["amount"] = inv.amount
                context["currency"] = inv.currency
                context["payment_id"] = inv.id  # наш внутренний номер платежа
                context["payment_name"] = inv.desc  # название платежа
                context["payment_name_base64"] = base64.standard_b64encode(inv.desc.encode('utf-8'))  # название платежа в base64 в (utf-8!!!)
                context["sim_mode"] = payment_settings.WM_SIM_MODE
                # context["payer_phone_number"] = inv.payer_phone_number # номер телефона пользователя
                context["payer_email"] = inv.payer_email  # почта пользователя
                context["account_id"] = inv.account.id  # id пользователя в биллинге
                context["type"] = inv.type  # тип платежа
                return context
            except Exception, e:
                log.add(u"payment_wm_start Except: %s" % e)
                raise Http404
        else:
            context['form'] = form
            request.notifications.add(u"Ошибка в заполнении полей", "error")
            return context
 def ParseCSVFile(self):
     """
         Разбираю CSV файл и проверяю всякие ошибки только в файле
     """
     if self.debug: print datetime.now(), "parser.ParseCSVFile()"; log.add("parser.ParseCSVFile()")
     file = open(self.fname, "rb")
     reader = csv.reader(file, delimiter = ";")
     
     line_num = 0
     for values in reader:
         line_num += 1
         l = len(values)
         if l == 4 or l == 5:
             code = values[0]
             zone_name = values[1]
             price = float(values[2].replace(",", "."))
             try:
                 start_date = datetime.strptime(values[3], '%d.%m.%Y').date()
             except:
                 e_str = _(u"Parsing file: Cannot parse CSV file in line %(line)s! Wrong values number!").__unicode__()
                 self.add_error(e_str % { "line": line_num })
                 self.had_stop = True
             try:
                 end_date = datetime.strptime(values[4], '%d.%m.%Y').date()
             except Exception, e:
                 end_date = datetime.max.date()
             
             # вот тут запихиваем это дело куда надо
             self.parsed_data.append({
                 "tel_code.code" : code,
                 "tel_zone.name" : zone_name,
                 "price" : price,
                 "start_date" : start_date,
                 "end_date" : end_date,
                 "line_num" : line_num
             })
             
         else:
             e_str = _(u"Parsing file: Cannot parse CSV file in line %(line)s! Wrong values number!").__unicode__()
             seld.add_error( e_str % { "line": line_num } )
             self.had_stop = True
Beispiel #35
0
def groups_group_edit(request, group_id):
    if request.user.get_profile().is_card:
        raise Http404
    context = {}
    context["title"] = _(u"Editing the group of numbers")
    user = request.user
    profile = user.get_profile()
    bac = []
    bac.append(profile.billing_account)
    numbers = []
    try:
        for ww in BillserviceAccount.objects.filter(assigned_to = profile.billing_account_id):
            bac.append(ww)
        for ba in bac:
            for qq in TelNumber.objects.filter(account = ba):
                numbers.append(qq)      
        existing_groups = TelNumbersGroup.objects.filter(account = profile.billing_account)
        group = TelNumbersGroup.objects.get(id = group_id)
    except Exception, e:
        log.add("Exception 1 in telnumbers.views.group_edit: '%s'" % e)
        raise e
Beispiel #36
0
def node():
    path = 'nodeImages/images.jpg'
    data = request.get_json()
    data = data['key']
    print(type(data))
    data = data.split(",")[1]
    data = bytes(data, 'utf-8')
    print(type(data))
    image = base64.b64decode(data)
    with open(path, 'wb') as f:
        f.write(image)
    response = test(path)

    print(response)
    if (response == None):
        try:
            sm(sender_email, reciever_email, subject, messege, path,
               "smtp.gmail.com", 587, sender_user_name, sender_password)
        except:
            print("email courd not be sent")
        os.remove(path)
        return "Intruder"

    else:
        result = gs(response)
        validity = result[0][2]
        if (validity == 0):
            add(response + "," + "valid")
            os.remove(path)
            return response + "," + "valid"
        else:
            try:
                sm(sender_email, reciever_email, subject, messege, path,
                   "smtp.gmail.com", 587, sender_user_name, sender_password)
            except:
                print("Emial could not be sent")

            add(response + "," + "invalid")
            os.remove(path)
            return response + "," + "invalid"
Beispiel #37
0
def android_test():
    path = "androidImages/test.jpg"
    data = request.stream.read()
    image = data
    image = base64.b64decode(image)

    with open(path, 'wb') as f:
        f.write(image)
    response = test(path)

    print(response)
    if (response == None):
        try:

            sm(sender_email, reciever_email, subject, messege, path,
               "smtp.gmail.com", 587, sender_user_name, sender_password)
        except:
            print("Email could not be sent ")
        os.remove(path)
        return "Intruder"
    else:

        result = gs(response)

        validity = result[0][2]
        if (validity == 0):
            add(response + "," + "valid")
            os.remove(path)
            return response + "," + "valid"
        else:
            try:
                sm(sender_email, reciever_email, subject, messege, path,
                   "smtp.gmail.com", 587, sender_user_name, sender_password)

            except:
                print("Email could not be sent")
            add(response + "," + "invalid")
            os.remove(path)
            return response + "," + "invalid"
Beispiel #38
0
def pause_delete(request):
    user = request.user
    package = Package_on_connection_of_service.objects.get(user = user, activate = False, deactivate = False)
    param = eval(package.data)
    profile = user.get_profile()
    account = profile.billing_account
    try:
        with xact():
            with xact(using = settings.BILLING_DB):
                external_number = ExternalNumber.objects.get(number = param['numbers'][0])
                next_month = (now + relativedelta(months = 1)).replace(day = 1, hour = 0, minute = 0, second = 0, microsecond = 0)
                deactivate_zakaz(account, PAUSE_SERVICE_TYPE, external_number, date_deactivation = next_month)
                package.activate = True
                package.save()
                findocs = [FinDocSigned.objects.filter(findoc__slug = '800_forma', signed_by = user).order_by('-id')[0]]
                send_to = send_docs(user, findocs, 'INSTRUCTION_DISCONNECT_800')
                request.notifications.add(u'На %s отправлено письмо с дальнейшими инструкциями для отключения номера!' % send_to, "success")
    except Exception, e:
        package.deactivate = True
        package.save()
        log.add("number800.py connect Exception: %s" % e)
        request.notifications.add(_(u"Произошла непредвиденная ошибка, обратитесь в техподдержку!"), "warning")
 def __init__(self, fname, billing_group_id, replace_names, replace_exists, autocreate_codes_and_zones, ignore_missing_zones, add_mobile_codes):
     self.debug = False
     
     self.messages = []
     self.warnings = []
     self.errors = []
     
     self.max_errors = 50
     self.max_warnings = 50
     self.max_messages = 50
     
     self.had_stop = False
     
     self.parsed_data = []
     self.parsed_tariffs = {}
     
     self.fname = fname
     self.replace_names = replace_names
     self.replace_exists = replace_exists
     self.autocreate = autocreate_codes_and_zones
     self.ignore_missing_zones = ignore_missing_zones
     self.add_mobile_codes = add_mobile_codes
     
     if self.debug: print datetime.now(), "parser.__init__()"; log.add("parser.__init__()")
     
     self.billing_group = TariffGroup.objects.get(id = billing_group_id)
     self.tel_zones = TelZone.objects.all()
     self.tel_codes = TelCode.objects.all()
     
     # подготовим dict с соответствием кода телефонной зоне
     self.tel_zone_by_code = {}
     for code in self.tel_codes:
         self.tel_zone_by_code[code.code] = code.tel_zone
     
     self.add_list = []
     self.err_count = 0
     self.warn_count = 0
     self.msg_count = 0
Beispiel #40
0
def restart():
    log.add(log.LEVEL_DEBUG, "Restart wifi")
    exitCode = subprocess.call(settings.getRestartWifiFile())
    result = exitCode == 0
    if result:
        log.add(log.LEVEL_DEBUG, "Wifi restarted")
    else:
        log.add(log.LEVEL_DEBUG, "Failed to restart wifi")
    return result
Beispiel #41
0
def check():
    log.add(log.LEVEL_DEBUG, "Check wifi")
    exitCode = subprocess.call(settings.getCheckWifiFile())
    result = exitCode == 0
    if result:
        log.add(log.LEVEL_DEBUG, "Wifi up")
    else:
        log.add(log.LEVEL_DEBUG, "Wifi down")
    return result
Beispiel #42
0
def model():
    path = "curlImages/test.jpg"
    filestr = request.files['file'].read()
    npimg = np.fromstring(filestr, np.uint8)
    img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)
    cv2.imwrite(path, img)

    response = test(path)

    print(response)
    if (response == None):
        try:
            sm(sender_email, reciever_email, subject, messege, path,
               "smtp.gmail.com", 587, sender_user_name, sender_password)
        except:
            print("email courd not be sent")
        os.remove(path)
        return "Intruder"

    else:
        result = gs(response)
        validity = result[0][2]
        if (validity == 0):
            add(response + "," + "valid")
            os.remove(path)
            return response + "," + "valid"
        else:
            try:
                sm(sender_email, reciever_email, subject, messege, path,
                   "smtp.gmail.com", 587, sender_user_name, sender_password)
            except:
                print("Emial could not be sent")

            add(response + "," + "invalid")
            os.remove(path)
            return response + "," + "invalid"
Beispiel #43
0
def _cbExtIfcTimer(req):
    global _manualOverride
    _manualOverride = False
    log.add(log.LEVEL_INFO, "Timer mode ON")
    if timer.active():
        log.add(log.LEVEL_INFO, "Timer ON")
        relay.setOn()
    else:
        log.add(log.LEVEL_INFO, "Timer OFF")
        relay.setOff()
    return "OK"
Beispiel #44
0
import sys
import os
import fileinput
import time

import users
import tasks
import fields
import log

if len(sys.argv) == 1:
    taskName = input('enter task name: ')
else:
    taskName = ' '.join(sys.argv[1:])

if os.path.exists(tasks.path(taskName)):
    print('error: task already exists.')
    sys.exit()

print('adding task: ' + taskName)
tasks.add(taskName)
log.add('addtask ' + taskName)
print('task added.')
Beispiel #45
0
def _cbExtIfcGetSettings(req):
    log.add(log.LEVEL_DEBUG, "Get settings")
    rsp = settings.toString()
    return rsp
Beispiel #46
0
def _setOut( p, state ):
	log.add( log.LEVEL_DEBUG, "Set pin {} to state {}".format( p, state ) )
	GPIO.output( p, state )
Beispiel #47
0
def _cbExtIfcSetSettings(req):
    log.add(log.LEVEL_DEBUG, "Set settings")
    # strip starting SETTINGS;
    settingsStr = req[len("SETTINGS;"):]
    settings.fromString(settingsStr)
    return "OK"
Beispiel #48
0
import log
import subprocess


def check():
    log.add(log.LEVEL_DEBUG, "Check wifi")
    exitCode = subprocess.call(settings.getCheckWifiFile())
    result = exitCode == 0
    if result:
        log.add(log.LEVEL_DEBUG, "Wifi up")
    else:
        log.add(log.LEVEL_DEBUG, "Wifi down")
    return result


def restart():
    log.add(log.LEVEL_DEBUG, "Restart wifi")
    exitCode = subprocess.call(settings.getRestartWifiFile())
    result = exitCode == 0
    if result:
        log.add(log.LEVEL_DEBUG, "Wifi restarted")
    else:
        log.add(log.LEVEL_DEBUG, "Failed to restart wifi")
    return result


if __name__ == "__main__":
    if not check():
        log.add(log.LEVEL_WARNING, "Wifi is down")
        restart()
Beispiel #49
0
def init(callback):
    log.add(log.LEVEL_DEBUG, "Start socket thread")
    global _callback
    _callback = callback
    t = threading.Thread(target=_serverThread)
    t.start()
Beispiel #50
0
    threading.Timer(settings.getCheckWifiIntervalSec(), _checkWifi).start()


def main():
    # setup callback dictionary
    cb = {
        "on": _cbExtIfcOn,
        "off": _cbExtIfcOff,
        "timer": _cbExtIfcTimer,
        "state": _cbExtIfcState,
        "settings": _cbExtIfcGetSettings,
        "set_settings": _cbExtIfcSetSettings,
        "sun": _cbExtIfcSun
    }
    externalifc.init(cb)
    relay.init()
    _updateSwitch()
    _checkWifi()
    while True:
        time.sleep(999)
    relay.done()
    return 0


if __name__ == "__main__":
    settings.init()
    log.add(log.LEVEL_INFO, "Starting")
    ret = main()
    log.add(log.LEVEL_INFO, "Done")
    sys.exit(ret)
Beispiel #51
0
log = log.Log()

newest_scraped = scraping.scrape_latest_data()
newest_from_db = db.get_last_stat()

if newest_scraped != newest_from_db:
    content = f"""\
    Here are the newest statistics:
    Date: {newest_scraped.date}
    Healthy: {newest_scraped.healthy}
    Delta: {newest_scraped.delta}
    Cases: {newest_scraped.cases}
    """
    for recipient in recipients:
        mail.send_email(
            to_addr=recipient,
            subject="New COVID data received!",
            content=content,
            debug=config["DEBUG"].getboolean("DEBUG_MODE"),
        )
    db.add_to_db(
        newest_scraped.date,
        newest_scraped.cases,
        newest_scraped.healthy,
        newest_scraped.delta,
    )
    log.add("Changes found, emails sent")
else:
    log.add("Checked, no changes found")
Beispiel #52
0
def _handleReq(data):
    data = data.strip()
    handler = ""
    if data == "SWITCH=ON":
        log.add(log.LEVEL_DEBUG, "Notify switch on from external interface")
        handler = "on"
    elif data == "SWITCH=OFF":
        log.add(log.LEVEL_DEBUG, "Notify switch off from external interface")
        handler = "off"
    elif data == "SWITCH=TIMER":
        log.add(log.LEVEL_DEBUG, "Notify timer mode from external interface")
        handler = "timer"
    elif data == "SWITCH?":
        log.add(log.LEVEL_DEBUG, "Query switch status from external interface")
        handler = "state"
    elif data == "SETTINGS?":
        log.add(log.LEVEL_DEBUG, "Request settings from external interface")
        handler = "settings"
    elif data.startswith("SETTINGS;"):
        log.add(log.LEVEL_DEBUG, "New settings from external interface")
        handler = "set_settings"
    elif data == "SUN?":
        log.add(log.LEVEL_DEBUG, "Query sun info from external interface")
        handler = "sun"
    else:
        log.add(log.LEVEL_WARNING,
                "Unknown req. on external interface: {}".format(data))

    rsp = "ERROR"
    if handler in _callback:
        rsp = _callback[handler](data)
    return rsp
Beispiel #53
0
def activePeriods(nowUtc=None):
    # get current date/time
    now = nowUtc
    if not now:
        now = datetime.datetime.utcnow()
    nowLocal = _utc2Local(now)

    result = {}

    # check timer periods (timer works in local timezone)
    if settings.getTimerEnabled():
        startTimer, stopTimer = _getOnPeriodTimer(nowLocal)
        log.add(
            log.LEVEL_DEBUG, "Now: {} {}, Timer On: {}, Timer Off: {}".format(
                calendar.day_abbr[nowLocal.weekday()], nowLocal, startTimer,
                stopTimer))
        if nowLocal >= startTimer and nowLocal <= stopTimer:
            result["timer"] = {
                "active": True,
                "start": startTimer,
                "stop": stopTimer
            }
        else:
            result["timer"] = {
                "active": False,
                "start": startTimer,
                "stop": stopTimer
            }

    # get sunrise/sunset
    sunrise, sunset = _getRelevantSunriseSunset(now)
    log.add(
        log.LEVEL_DEBUG,
        "Now: {} {} UTC, Sunrise: {} UTC, Sunset: {} UTC".format(
            calendar.day_abbr[now.weekday()], now, sunrise, sunset))
    # get timer start/stop at sunset
    startSunset, stopSunset = _getOnPeriodSunset(sunset)
    # get timer start/stop at sunrise
    startSunrise, stopSunrise = _getOnPeriodSunrise(sunrise)
    if settings.getSunsetEnabled():
        log.add(
            log.LEVEL_DEBUG,
            "Active period at sunset, start: {} UTC, stop: {} UTC".format(
                startSunset, stopSunset))
        if now >= startSunset and now < stopSunset:
            log.add(log.LEVEL_DEBUG, "Timer active at sunset")
            result["sunset"] = {
                "active": True,
                "start": startSunset,
                "stop": stopSunset
            }
        else:
            log.add(log.LEVEL_DEBUG, "Timer inactive at sunset")
            result["sunset"] = {
                "active": False,
                "start": startSunset,
                "stop": stopSunset
            }

    if settings.getSunriseEnabled():
        log.add(
            log.LEVEL_DEBUG,
            "Active period at sunrise, start: {} UTC, stop: {} UTC".format(
                startSunrise, stopSunrise))
        if now >= startSunrise and now < stopSunrise:
            log.add(log.LEVEL_DEBUG, "Timer active at sunrise")
            result["sunrise"] = {
                "active": True,
                "start": startSunrise,
                "stop": stopSunrise
            }
        else:
            log.add(log.LEVEL_DEBUG, "Timer inactive at sunrise")
            result["sunrise"] = {
                "active": False,
                "start": startSunrise,
                "stop": stopSunrise
            }
    return result
Beispiel #54
0
    value = sys.argv[3]
else:
    value = None

if not os.path.exists(taskPath):
    print('error: ' + taskPath + ' does not exist')
    sys.exit()

try:
    field = fields.Field[field]
except:
    print('error: ' + field + ' field does not exist')
    sys.exit()
try:
    value = fields.dataType(field)[value]
except:
    pass

if not fields.isValid(field):
    print('error: ' + field + 'is not a valid field')
    sys.exit()

if value:
    print("deleting value: " + str(value) + ' in field: ' + field.name)
else:
    print("deleting field: " + field.name)

tasks.removeField(taskPath, users.current, field, value)
log.add(' '.join(sys.argv))
print('value deleted.')
Beispiel #55
0
def _cbExtIfcOff(req):
    global _manualOverride
    _manualOverride = True
    log.add(log.LEVEL_INFO, "Manual switch OFF")
    relay.setOff()
    return "OK"