Esempio n. 1
0
    def content(self, request, cxt):
        status = self.getStatus(request)

        res = yield self.getAuthz(request).actionAllowed("cleanShutdown",
                                                            request)

        if request.path == '/shutdown':
            if res:
                eventually(status.cleanShutdown)
                yield defer.returnValue(redirectTo("/", request))
                return
            else:
                yield defer.returnValue(
                        redirectTo(path_to_authzfail(request), request))
                return
        elif request.path == '/cancel_shutdown':
            if res:
                eventually(status.cancelCleanShutdown)
                yield defer.returnValue(redirectTo("/", request))
                return
            else:
                yield defer.returnValue(
                        redirectTo(path_to_authzfail(request), request))
                return

        cxt.update(
                shutting_down = status.shuttingDown,
                shutdown_url = request.childLink("shutdown"),
                cancel_shutdown_url = request.childLink("cancel_shutdown"),
                )
        template = request.site.buildbot_service.templates.get_template("root.html")
        yield defer.returnValue(template.render(**cxt))
Esempio n. 2
0
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).get_session_user()
        session_user['action'] = 'withdraw_bid'

        is_confirmed = request.args.get('is_confirmed')[0]
        if is_confirmed == 'no':
            return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))
        
        try:
            bid_id = int(request.args.get('bid_id')[0])
        except:
            return redirectTo('../', request)
        
        bid = db.query(Bid).filter(Bid.id == bid_id).first()

        if bid.user_id != session_user['id']:
            return redirectTo('../', request)

        timestamp = config.create_timestamp()
        
        bid.updated_at = timestamp 
        bid.status = 'withdrawn'

        db.commit()
        return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)
        session_user = SessionManager(request).get_session_user()
        session_user['action'] = 'process_offer'

        response = {'error': True}
        try:
            action = request.args.get('action')[0]
        except:
            return redirectTo('../', request)

        if action == 'complete':
            try:
                offer_id = int(request.args.get('id')[0])
            except:
                return redirectTo('../offers', request)

            response['error'] = False
            response['action'] = action

            response['offer'] = {
                    'id': str(offer_id)
                } 

            return json.dumps(response)
    def render(self, request):

        session_user = SessionManager(request).getSessionUser()
        userType = session_user['type']
        if userType != 0:
            return redirectTo('../', request)

        try:
            userId = int(request.args.get('id')[0])
        except:
            return redirectTo('../', request)

        profile = db.query(Profile).filter(Profile.userId == userId).first()
        user = db.query(User).filter(User.id == userId).first()
        store = db.query(Store).filter(Store.ownerId == userId).first()

        jsonUser = {}
        jsonUser['id'] = str(userId)
        jsonUser['email'] = str(user.email)
        jsonUser['first'] = str(profile.first)
        jsonUser['last'] = str(profile.last)
        jsonUser['currencyId'] = str(profile.currencyId)
        jsonUser['unreadCount'] = str(profile.unreadCount)
        jsonUser['bitcoinAddress'] = str(profile.bitcoinAddress)
        jsonUser['type'] = str(user.type)
        jsonUser['loginTimestamp'] = str(user.loginTimestamp)
        jsonUser['isEmailVerified'] = str(user.isEmailVerified)
        jsonUser['createTimestamp'] = str(profile.createTimestamp)
        jsonUser['updateTimestamp'] = str(profile.updateTimestamp)
        jsonUser['receivedSellOrders'] = str(profile.receivedSellOrders)
        jsonUser['receivedBuyOrders'] = str(profile.receivedBuyOrders)
        jsonUser['ip'] = str(user.ip)
        jsonUser['store'] = str(store.name)
        return json.dumps(jsonUser)
Esempio n. 5
0
 def checkSession(authinfo):
     if authinfo.username:
         redirectURL = utils.getRequestArg(request, "_r", sanitize=False) or "/feed/"
         util.redirectTo(urllib.unquote(redirectURL), request)
         request.finish()
     else:
         self._renderSigninForm(request)
Esempio n. 6
0
    def render_GET(self, request):
	res = None
	logged = session.get_user(request)
	if not logged:
		return redirectTo('/', request)
	parts = request.path.split("/")
	if len(parts) > 2 and logged.admin:
		user_ext = parts[2]
	else:
		user_ext = logged.voip_id
	args = {'ext': user_ext, 'lowquality': '', 'tls': '', 'srtp': '', 'voicemail': ''}
	options = get_options(user_ext)
	if 'codecs' in options and 'gsm' in options['codecs']:
		args['lowquality'] = ' checked '
	if options['tls']:
		args['tls'] = ' checked '
	if options['srtp']:
		args['srtp'] = ' checked '
	if options['voicemail']:
		args['voicemail'] = ' checked '
        model = Model()
        user = model.query(User).filter_by(voip_id=user_ext).first()
        if user and (logged.admin or user.id == logged.id):
            args['bitcoin'] = self.render_btc(logged, user, wallet)
        else:
            return redirectTo('/', request)
	content = print_template('options', args)
	return print_template('content-pbx-lorea', {'content': content})
Esempio n. 7
0
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).get_session_user()
        session_user['action'] = 'withdraw_ask'

        is_confirmed = request.args.get('is_confirmed')[0]
        if is_confirmed == 'no':
            return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))
        
        try:
            ask_id = int(request.args.get('ask_id')[0])
        except:
            return redirectTo('../', request)
        
        ask = db.query(Ask).filter(Ask.id == ask_id).first()

        if ask.user_id != session_user['id']:
            return redirectTo('../', request)

        timestamp = config.create_timestamp()
        
        ask.updated_at = timestamp 
        ask.status = 'withdrawn'

        client = db.query(Profile).filter(Profile.user_id == session_user['id']).first()
        client.available_balance += ask.cost * (ask.goal - ask.target)
        client.reserved_balance -= ask.cost * (ask.goal - ask.target)

        db.commit()
        return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))
Esempio n. 8
0
    def render_POST(self, request):
	logged = get_user(request)
	if not logged:
		return redirectTo("/", request)
	args = {}
	options = {}
	user_ext = logged.voip_id
        for a in request.args:
            args[a] = request.args[a][0]

	if logged:
		if 'tls' in args and args['tls']:
			options['tls'] = args['tls']
		else:
			options['tls'] = False
		if 'srtp' in args and args['srtp']:
			options['srtp'] = args['srtp']
		else:
			options['srtp'] = False
		options['voicemail'] = args.get('voicemail', False)
		if 'ext' in args and args['ext'] and logged.admin:
			user_ext = args['ext']
		if 'lowquality' in args and args['lowquality']:
			options['codecs'] = ['gsm']
		change_options(user_ext, options)
		return redirectTo('/options/' + user_ext, request)
	return redirectTo('/', request)
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).get_session_user()
        session_user['action'] = 'approve_user'

        try:
            user_id = int(request.args.get('user_id')[0])
        except:
            return redirectTo('../users', request)

        user = db.query(Transaction).filter(Transaction.id == user_id).first()

        if user.client_id != session_user['id']:
            return redirectTo('../', request)

        is_confirmed = request.args.get('is_confirmed')[0]
        if is_confirmed == 'no':
            return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))

        timestamp = config.create_timestamp()
        
        #bid = db.query(Bid).filter(Bid.id == ).first()

        user.updated_at = timestamp 
        user.status = 'approved'
        db.commit()

        return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).get_session_user()
        session_user['action'] = 'disapprove'

        try:
            user_id = int(request.args.get('user_id')[0])
        except:
            return redirectTo('../users', request)

        user = db.query(Transaction).filter(Transaction.id == user_id).first()

        if user.client_id != session_user['id']:
            return redirectTo('../', request)

        is_confirmed = request.args.get('is_confirmed')[0]
        if is_confirmed == 'no':
            return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))

        timestamp = config.create_timestamp()
        
        user.updated_at = timestamp 
        user.status = 'cancelled'

        client = db.query(Profile).filter(Profile.user_id == user.client_id).first()
        client.user_count -= 1
        client.available_balance += user.charge
        client.reserved_balance -= user.charge

        promoter = db.query(Profile).filter(Profile.user_id == user.promoter_id).first()
        promoter.transaction_count -= 1
        
        db.commit()
        return json.dumps(dict(response=1, text=definitions.MESSAGE_SUCCESS))
Esempio n. 11
0
    def _saveSessionAndRedirect(self, request, data, remember=False):
        authinfo = yield defer.maybeDeferred(request.getSession,
                                             IAuthInfo, True, remember)
        authinfo.username = data["user"]
        authinfo.organization = data.get("org", None)
        authinfo.isAdmin = True if data.has_key("isAdmin") else False

        yield request._saveSessionToDB()
        redirectURL = utils.getRequestArg(request, "_r", sanitize=False) or "/feed/"
        util.redirectTo(urllib.unquote(redirectURL), request)
        request.finish()
Esempio n. 12
0
    def render(self, request):
        if not request.args:
            return redirectTo('../', request)

        session_user = SessionManager(request).getSessionUser()
        session_user['action'] = 'lend'

        lenderId = session_user['id']

        session_transaction = SessionManager(request).getSessionTransaction()

        btc_amount = request.args.get('btc_loan_amount')[0]

        session_transaction['lenderId'] = lenderId
        session_transaction['amount'] = btc_amount
        bitcoinAddress = explorer.getNewAddress('')['result']

        if error.amount(request, btc_amount):
            return redirectTo('../lend', request)

        btc_amount = float(btc_amount)

        if request.args.get('button')[0] == 'Get Address':
            timestamp = config.createTimestamp()

            data = {
                'status': 'open',
                'createTimestamp': timestamp,
                'updateTimestamp': timestamp,
                'userId': lenderId,
                'amount': btc_amount,
                'bitcoinAddress': bitcoinAddress,
                'statement': '',
                'signature': ''    
                }

            newTransaction = Transaction(data)
            
            db.add(newTransaction)

            db.commit()

            report.createPdf(newTransaction)

            session_transaction['id'] = newTransaction.id
            session_transaction['amount'] = newTransaction.amount
            session_transaction['createTimestamp'] = timestamp
            session_transaction['bitcoinAddress'] = newTransaction.bitcoinAddress
            session_transaction['isSigned'] = 0 

            return redirectTo('../contract', request)
Esempio n. 13
0
 def render_GET(self, request):
     error = request.args.get("error", [""])[0]
     code = request.args.get("code", [""])[0]
     if error:
         return str(error)
     elif not code:
         return redirectTo(self.authz.getLoginURL(), request)
     else:
         details = self.verifyCode(code)
         if "xamarin" not in details["groups"]:
             return "no xamarin employee, no power (make sure your membership is public: https://github.com/orgs/xamarin/people)"
         cookie, s = self.authz.sessions.new(details["userName"], details)
         request.addCookie(COOKIE_KEY, cookie, expires=s.getExpiration(), path="/")
         request.received_cookies = {COOKIE_KEY: cookie}
         return redirectTo(self.authz.root_uri, request)
Esempio n. 14
0
    def content(self, request, cxt):
        status = self.getStatus(request)

        if request.path == '/shutdown':
            return redirectTo(path_to_authfail(request), request)
        elif request.path == '/cancel_shutdown':
            return redirectTo(path_to_authfail(request), request)

        cxt.update(
                shutting_down = status.shuttingDown,
                shutdown_url = request.childLink("shutdown"),
                cancel_shutdown_url = request.childLink("cancel_shutdown"),
                )
        template = request.site.buildbot_service.templates.get_template("root.html")
        return template.render(**cxt)
Esempio n. 15
0
    def content(self, req, ctx):
        # check for False or True on showUsersPage, redirect immediately
        authz = self.getAuthz(req)
        if not authz.needAuthForm(self.action):
            if authz.advertiseAction(self.action):
                yield redirectTo("users/table", req)
                return
            else:
                yield redirectTo(path_to_authzfail(req), req)
                return

        ctx['authz'] = self.getAuthz(req)
        ctx['table_link'] = req.childLink("table")
        template = req.site.buildbot_service.templates.get_template("users.html")
        yield template.render(**ctx)
Esempio n. 16
0
 def render_GET(self, request):
     error = request.args.get("error", [""])[0]
     code = request.args.get("code", [""])[0]
     if error:
         return str(error)
     elif not code:
         return redirectTo(self.authz.getLoginURL(), request)
     else:
         details = self.verifyCode(code)
         if not details["email"].split("@")[-1] == "xamarin.com":
             return "no xamarin employee, no power"
         cookie, s = self.authz.sessions.new(details["userName"], details)
         request.addCookie(COOKIE_KEY, cookie, expires=s.getExpiration(), path="/")
         request.received_cookies = {COOKIE_KEY: cookie}
         return redirectTo(self.authz.root_uri, request)
Esempio n. 17
0
 def flattened(spam):
     # Join the bits to make a complete URL.
     u = ''.join(bits)
     # It might also be relative so resolve it against the current URL
     # and flatten it again.
     u = flat.flatten(URL.fromContext(ctx).click(u), ctx)
     return redirectTo(u, inevow.IRequest(ctx))
Esempio n. 18
0
    def render_GET(self, request):
	logged = session.get_user(request)
	if logged and logged.admin:
		content = self.render_stats(request)
		content = "<pre>%s</pre>" % (content,)
		return templates.print_template('content-pbx-lorea', {'content': content})
	return redirectTo("/", request)
Esempio n. 19
0
 def renderHTTP(self, ctx):
     # The URL may have deferred parts so flatten it
     u = flatten(self.original, ctx)
     # It might also be relative so resolve it against the current URL
     # and flatten it again.
     u = flatten(URL.fromContext(ctx).click(u), ctx)
     return redirectTo(u, inevow.IRequest(ctx))
Esempio n. 20
0
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).getSessionUser()

        if session_user['id'] == 0:
            return redirectTo('../', request)

        sessionResponse = SessionManager(request).getSessionResponse()

        session_user['page'] = 'lend'

        session_transaction = SessionManager(request).getSessionTransaction()

        if not session_transaction.get('amount'):
            session_transaction['amount'] = 1

        session_user['page'] = 'lend'

        Page = pages.Lend('Smart Property Group - Lend', 'lend')
        Page.session_user = session_user
        Page.sessionResponse = sessionResponse
        Page.session_transaction = session_transaction

        print "%ssession_user: %s%s" % (config.color.BLUE, session_user, config.color.ENDC)
        print "%ssessionResponse: %s%s" % (config.color.BLUE, sessionResponse, config.color.ENDC)
        print "%ssession_transaction: %s%s" % (config.color.BLUE, session_transaction, config.color.ENDC)

        SessionManager(request).clearSessionResponse()
        request.write('<!DOCTYPE html>\n')
        return renderElement(request, Page)
Esempio n. 21
0
 def render_GET(self, request):
     """
     :type request: bouser.web.request.BouserRequest
     :param request:
     :return:
     """
     token = request.getCookie(self.service.cookie_name)
     session = request.getSession()
     fm = IWebSession(session)
     if 'back' in request.args:
         fm.back = request.args['back'][0]
     elif not fm.back:
         fm.back = request.getHeader('Referer') or '/'
     try:
         if token:
             token = token.decode('hex')
             yield self.service.check_token(token)
         else:
             defer.returnValue(request.render_template('login.html'))
     except EExpiredToken:
         defer.returnValue(request.render_template('login.html'))
     else:
         # Token is valid - just redirect
         back, fm.back = fm.back, None
         defer.returnValue(redirectTo(back, request))
Esempio n. 22
0
    def _renderDeferred(self, checkedRequest):
        """Render this resource asynchronously.

        :type checkedRequest: tuple
        :param checkedRequest: A tuple of ``(bool, request)``, as returned
            from :meth:`checkSolution`.
        """
        try:
            valid, request = checkedRequest
        except Exception as err:
            logging.error("Error in _renderDeferred(): %s" % err)
            return

        logging.debug("Attemping to render %svalid request %r"
                      % ('' if valid else 'in', request))
        if valid is True:
            try:
                rendered = self.resource.render(request)
            except Exception as err:  # pragma: no cover
                rendered = replaceErrorPage(err)
        else:
            logging.info("Client failed a CAPTCHA; redirecting to %s"
                         % request.uri)
            rendered = redirectTo(request.uri, request)

        try:
            request.write(rendered)
            request.finish()
        except Exception as err:  # pragma: no cover
            logging.exception(err)

        return request
Esempio n. 23
0
 def test_headersAndCode(self):
     """
     L{redirectTo} will set the C{Location} and C{Content-Type} headers on
     its request, and set the response code to C{FOUND}, so the browser will
     be redirected.
     """
     request = Request(DummyChannel(), True)
     request.method = b'GET'
     targetURL = b"http://target.example.com/4321"
     redirectTo(targetURL, request)
     self.assertEqual(request.code, FOUND)
     self.assertEqual(
         request.responseHeaders.getRawHeaders(b'location'), [targetURL])
     self.assertEqual(
         request.responseHeaders.getRawHeaders(b'content-type'),
         [b'text/html; charset=utf-8'])
Esempio n. 24
0
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).getSessionUser()

        if session_user['id'] == 0:
            return redirectTo('../', request)

        sessionResponse = SessionManager(request).getSessionResponse()
        sessionProperty = SessionManager(request).getSessionProperty()

        try:
            status = request.args.get('status')[0]
        except:
            status = 'pending'

        Page = pages.Orders('Orders', 'orders', status)
        Page.session_user = session_user

        print "%ssession_user: %s%s" % (config.color.BLUE, session_user, config.color.ENDC)
        print "%ssessionProperty: %s%s" % (config.color.BLUE, sessionProperty, config.color.ENDC)
        print "%ssessionResponse: %s%s" % (config.color.BLUE, sessionResponse, config.color.ENDC)
        SessionManager(request).clearSessionResponse()

        request.write('<!DOCTYPE html>\n')
        return renderElement(request, Page)
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).get_session_user()
        session_user['page'] = 'transactions'

        if session_user['id'] == 0:
            return redirectTo('../', request)

        session_response = SessionManager(request).get_session_response()

        filters = {}
        try:
            filters['status'] = request.args.get('status')[0]
        except:
            filters['status'] = 'open'

        try:
            filters['kind'] = request.args.get('kind')[0]
        except:
            filters['kind'] = 'promoter'

        Page = pages.Transactions('%s Transactions' % config.company_name, 'transactions', filters)
        Page.session_user = session_user

        print "%ssession_user: %s%s" % (config.color.BLUE, session_user, config.color.ENDC)
        print "%ssession_response: %s%s" % (config.color.BLUE, session_response, config.color.ENDC)

        SessionManager(request).clearSessionResponse()

        request.write('<!DOCTYPE html>\n')
        return renderElement(request, Page)
Esempio n. 26
0
	def renderHTTP(self, ctx):
		request = inevow.IRequest(ctx)

		def handle_user_token(result):
			if result[0] == 0:
				self.user_token = str(result[1]['user_token'])
				return self.send_to_qoop(request)
			else:
				return redirectTo("/not_found/", request)

		if request.args.has_key("bonus"):
			self.bonus = request.args['bonus'][0]
			auth_hash = request.getCookie("auth_hash")
			auth_username = self._get_auth_username(ctx)
			auth_userid = self._get_auth_userid(ctx)
			if auth_username:
				d = self.app.api.users.get_user_token(auth_userid, True)
				d.addCallback(handle_user_token)
				return d
			else:
				if request.args.has_key("user_token"):
					self.user_token = request.args['user_token'][0]
					return self.send_to_qoop(request)
				else:
					return zoto_base_page.renderHTTP(self, ctx)
		else:
			return redirectTo("/not_found/", request)
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).getSessionUser()

        if session_user['id'] == 0:
            return redirectTo('../', request)

        sessionResponse = SessionManager(request).getSessionResponse()

        try:
            status = request.args.get('status')[0]
        except:
            status = 'pending'

        filters = {'status': status}

        Page = pages.SummaryTransactions('Summary Transactions', 'summaryTransactions', filters)
        Page.session_user = session_user
        Page.sessionResponse = sessionResponse

        print "%ssession_user: %s%s" % (config.color.BLUE, session_user, config.color.ENDC)
        print "%ssessionResponse: %s%s" % (config.color.BLUE, sessionResponse, config.color.ENDC)
        SessionManager(request).clearSessionResponse()

        request.write('<!DOCTYPE html>\n')
        return renderElement(request, Page)
    def render(self, request):
        print '%srequest.args: %s%s' % (config.color.RED, request.args, config.color.ENDC)

        session_user = SessionManager(request).get_session_user()
        session_user['action'] = 'summary_bids'

        if session_user['level'] != 0:
            return redirectTo('../', request)

        session_response = SessionManager(request).get_session_response()

        filters = {}
        try:
            filters['status'] = request.args.get('status')[0]
        except:
            filters['status'] = 'active'

        Page = pages.SummaryBids('%s Summary Bids' % config.company_name, 'summary_bids', filters)
        Page.session_user = session_user

        print "%ssession_user: %s%s" % (config.color.BLUE, session_user, config.color.ENDC)
        print "%ssession_response: %s%s" % (config.color.BLUE, session_response, config.color.ENDC)

        SessionManager(request).clearSessionResponse()

        request.write('<!DOCTYPE html>\n')
        return renderElement(request, Page)
    def render_POST(self, request):
        session = request.getSession()
        tsession = ILoginGate(session)
        location = "/dynamic/error"

        try:
            if request.path not in ["/dynamic/nonce-login", "/dynamic/login"]:
                raise Exception('unsupported login type')

            if request.path == "/dynamic/nonce-login":
                nonce = request.args.get('nonce', [''])[0]

                if tsession.nonce != nonce:
                    session.expire()
                    raise Exception('invalid nonce')

            if (request.args.get('user', [''])[0] != 'user' or
                    request.args.get('pass', [''])[0] != 'pass'):
                if session:
                    session.expire()
                raise Exception('invalid user/pass')

            tsession.logged_in = True
            location = "/dynamic/gated"

        except:
            pass

        return redirectTo(location, request)
Esempio n. 30
0
    def render_POST(self, request):
        """Process a client's CAPTCHA solution.

        If the client's CAPTCHA solution is valid (according to
        :meth:`checkSolution`), process and serve their original
        request. Otherwise, redirect them back to a new CAPTCHA page.

        :type request: :api:`twisted.web.http.Request`
        :param request: A ``Request`` object, including POST arguments which
            should include two key/value pairs: one key being
            ``'captcha_challenge_field'``, and the other,
            ``'captcha_response_field'``. These POST arguments should be
            obtained from :meth:`render_GET`.
        :rtype: str
        :returns: A rendered HTML page containing a ReCaptcha challenge image
            for the client to solve.
        """
        request.setHeader("Content-Type", "text/html; charset=utf-8")

        if self.checkSolution(request) is True:
            try:
                rendered = self.resource.render(request)
            except Exception as err:
                rendered = replaceErrorPage(err)
            return rendered

        logging.debug("Client failed a CAPTCHA; returning redirect to %s"
                      % request.uri)
        return redirectTo(request.uri, request)
Esempio n. 31
0
 def redirect(self, args, request):
     print "Redirect: %(ip)s" % args
     return redirectTo(config['redirect'], request)
Esempio n. 32
0
 def redirect(self, url):
     '''redirect url'''
     return redirectTo(url, self.request)
Esempio n. 33
0
    def render_GET(self, request):
        user = session.get_user(request)
        if not user:
            return redirectTo("/", request)
        model = Model()
        output = cli.run_command('sip show peers')
        lines = output.split("\n")
        res = ""
        formatted = {
            "local":
            "<tr><th>Nombre</th><th>Ext</th><th>Estado</th><th>Latencia</th><tr>\n",
            "channels":
            "<tr><th>Nombre</th><th>Estado</th><th>Latencia</th><tr>\n",
            "end":
            "<tr><th>Nombre</th><th>Ext</th><th>Estado</th><th>Latencia</th><tr>\n"
        }
        for line in lines[1:]:
            line = line.replace(" D ", "")
            line = line.replace(" N ", "")
            line = line.replace(" a ", "")
            line = line.replace(" A ", "")
            line = line.replace("Cached RT", "")
            parts = line.split()
            parts = map(lambda s: s.strip("()"), parts)
            if len(parts) > 8 or len(parts) <= 3:
                continue
            peer_name = parts[0].split("/")[0]
            ext = None
            peer = model.query(SipPeer).filter_by(name=peer_name).first()
            if peer:
                ext = peer.regexten

            if ("OK" in line
                    or "LAGGED" in line) and ext:  # and "192.168." in line:
                # line = self.add_ip_href(line)
                dest = 'local'
            elif ext:
                dest = 'end'
            else:
                dest = 'channels'
            if len(parts) > 4:
                # connected
                if dest == 'channels':
                    output = "<tr><td>%s</td><td>%s</td><td>%sms</td><tr>" % (
                        peer_name, parts[3], parts[4])
                else:
                    output = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%sms</td><tr>" % (
                        peer_name, ext, parts[3], parts[4])
            elif len(parts) > 3:
                if dest == 'channels':
                    output = "<tr><td>%s</td><td>%s</td><td></td>" % (
                        peer_name, parts[3])
                else:
                    output = "<tr><td>%s</td><td>%s</td><td>%s</td><td></td>" % (
                        peer_name, ext, parts[3])
            else:
                print "not enough parts", parts
                continue
            formatted[dest] += output + "\n"
        res += "<h2>Local</h2>"
        res += "<table>"
        res += formatted['local']
        res += "</table>"
        if user.admin:
            res += "<h2>Channels</h2><table>"
            res += formatted['channels']
            res += "</table>"
        res += "<h2>Other</h2><table>"
        res += formatted['end']
        res += "</table><pre>"
        res += "<h2>Calls</h2>"
        res += cli.run_command('core show calls')
        res += "</pre><pre>"
        res += cli.run_command('core show uptime')
        res += "</pre>"
        return print_template('content-pbx-lorea', {'content': res})
Esempio n. 34
0
    def render_GET(self, request):
#return "<html><body>Welcome to the calendar server!</body></html>"
        return redirectTo(datetime.now().year, request)
Esempio n. 35
0
 def render_GET(self, request):
     params = get_unicode_params(request)
     action = params.get(u"action", [u"login"])[0]
     
     if action == u"login":
         # client wants to login
         # first of, prepare request
         r = yield self._request_dispatcher.post(
             self._auth_url,
             params={
                 u"action": u"prepare",
                 u"token": self._token,
                 u"secret": self._secret,
             }
         )
         response = yield r.json()
         status = response.get(u"status", u"error")
         if status == u"error":
             # preparation failed
             reason = response.get("reason", "Unknown")
             request.setResponseCode(500)
             defer.returnValue(u"Error: {}".format(reason))
         elif status == u"success":
             # preparations succeeded
             ctoken = response.get("client_token", None)
             if ctoken is None:
                 # no ctoken aquired, this is an error
                 request.setResponseCode(500)
                 defer.returnValue(u"Error: authentication server did not send a client token.")
             # continued below
         else:
             # invalid response
             request.setResponseCode(500)
             defer.returnValue(u"Error: authentication server send invalid response.")
         
         # we now have a client token, time to redirect the client
         # to the auth server
         defer.returnValue(
             redirectTo("{}?action=check&ctoken={}".format(
                 self._auth_url,
                 ctoken,
                 ).encode(_URL_ENCODING),
             request,
             )
         )
                      
     elif action == u"callback":
         # client is back from auth server
         ctoken = params.get(u"ctoken", [None])[0]
         r = yield self._request_dispatcher.get(
             self._auth_url,
             params={
                 u"action": u"validate",
                 u"token": self._token,
                 u"secret": self._secret,
                 u"ctoken": ctoken,
             }
         )
         response = yield r.json()
         if response.get(u"status", u"error") == u"success":
             userdata = response.get(u"userdata", None)
             result = yield self.on_login(request, userdata)
             defer.returnValue(result)
         else:
             # login invalid, attempt another login
             defer.returnValue(
                 redirectTo(
                     b"?action=login",
                     request,
                 )
             )
     else:
         request.setResponseCode(404)
         defer.returnValue(u"Error: Invalid action specified.")
Esempio n. 36
0
 def redirect(self, request):
     return redirectTo(_addSlash(request), request)
Esempio n. 37
0
 def render_GET(self, request):
     params = get_unicode_params(request)
     action = params.get(u"action", [None])[0]
     
     if action == u"login":
         # client wants to login
         result = yield self._login_resource.render_loginpage(request)
         defer.returnValue(result)
     elif action == u"check":
         # check if client is already logged in
         # first, check for ctoken
         ctoken = params.get(u"ctoken", [None])[0]
         if ctoken not in self._tokens:
             # invalid ctoken
             html = yield self._login_resource.render_invalid_login(request)
             defer.returnValue(html or u"Error: invalid ctoken!")
         
         session = request.getSession()
         cookie = ILoginCookie(session)
         
         if cookie.userdata is not None:
             # client is logged in
             state, perm, _ = self._tokens[ctoken]
             self._tokens[ctoken] = (self._TOKEN_STATE_CB, perm, cookie.userdata)
             defer.returnValue(
                 redirectTo(
                     u"{}?action=callback&ctoken={}".format(
                         perm.callback_url,
                         ctoken,
                     ).encode(_URL_ENCODING),
                     request,
                 )
             )
         else:
             # client is not already logged in, redirect to login
             defer.returnValue(
                 redirectTo(
                     u"{}?action=login&ctoken={}".format(
                         self._url,
                         ctoken,
                         ).encode(
                         _URL_ENCODING,
                         ),
                     request,
                 )
             )
     elif action == u"validate":
         # website wants to validate login information
         ctoken = params.get(u"ctoken", [None])[0]
         if (ctoken is None) or (ctoken not in self._tokens):
             defer.returnValue(u'{"status": "error", "reason": "ctoken invalid!"}')
         else:
             state, perm, userdata = self._tokens[ctoken]
             if (state != self._TOKEN_STATE_CB):
                 defer.returnValue(u'{"status": "error", "reason": "ctoken did not complete login!"}')
             elif perm is None:
                 defer.returnValue(u'{"status": "error", "reason": "site does not have permission for login!"}')
             else:
                 cleaned = yield perm.userdata_to_dict(userdata)
                 defer.returnValue(
                     json.dumps(
                         {
                             u"status": u"success",
                             u"userdata": cleaned,
                         },
                     )
                 )
     else:
         # unknown action
         request.setResponseCode(404)
         defer.returnValue(u"Error: Invalid action specified.")
Esempio n. 38
0
 def view(allowed):
     if allowed or path_always_viewable(request):
         return defer.maybeDeferred(lambda: self.content(request, ctx))
     else:
         return redirectTo(path_to_root(request), request)
Esempio n. 39
0
 def render_POST(self, request):
     params = get_unicode_params(request)
     action = params.get(u"action", [u"login"])[0]
     
     if action == u"prepare":
         # prepare client token
         token = params.get(u"token", [None])[0]
         secret = params.get(u"secret", [None])[0]
         
         if (token is None) and (secret is None):
             # anonymous website
             credentials = Anonymous()
         elif (token is None) or (secret is None):
             # one value is missing, invalid request
             defer.returnValue(u'{"status": "error", "reason": "token OR secret missing"}')
         else:
             # token / secret provided
             credentials = UnicodeUsernamePassword(token, secret)
         
         try:
             _, perm, logout = yield self._token_portal.login(credentials, None, IWebAuthPermission)
         except (Unauthorized, LoginFailed):
             defer.returnValue(u'{"status": "error", "reason": "token/secret invalid"}')
         else:
             # this is not an interactive season, so call logout immediately
             logout()
         
         ctoken = self._new_ctoken()
         self._tokens[ctoken] = (self._TOKEN_STATE_LOGIN, perm, None)
         defer.returnValue(u'{"status": "success", "client_token": "' + ctoken + '"}')
     elif action == u"login":
         # login credentials
         params = get_unicode_params(request)
         ctoken = params.get("ctoken", [None])[0]
         
         if ctoken not in self._tokens:
             # invalid client token
             html = (yield self._login_resource.render_invalid_login(request)) or u"Error: Invalid ctoken"
             defer.returnValue(html)
         
         credentials = self._login_resource.handle_login_response(params)
         
         # attempt login
         try:
             _, userdata, logout = yield self._user_portal.login(credentials, None, IUserData)
         except (Unauthorized, LoginFailed):
             # invalid login
             response = (yield self._login_resource.render_login_failed(request)) or u"Login failed"
             defer.returnValue(response)
         else:
             # login successfull
             # first off, call logout as twisted cred wants
             logout()
             # secondly, set the client login cookie
             session = request.getSession()
             cookie = ILoginCookie(session)
             cookie.userdata = userdata
             # thirdly, prepare the userdata
             _, perm, _2 = self._tokens[ctoken]
             self._tokens[ctoken] = (self._TOKEN_STATE_CB, perm, userdata)
             # finally, redirect to callback
             defer.returnValue(
                 redirectTo(
                     u"{}?action=callback&ctoken={}".format(
                         perm.callback_url,
                         ctoken,
                     ).encode(_URL_ENCODING),
                     request,
                 )
             )
     else:
         # unknown action
         request.setResponseCode(404)
         defer.returnValue(u"Error: Invalid action specified.")
Esempio n. 40
0
 def render_GET(self, request):
     return redirectTo(self.url.encode("ascii"), request)
Esempio n. 41
0
 def render(self, request):
     return redirectTo(addSlash(request), request)
Esempio n. 42
0
 def render_GET(self,request):
     return redirectTo('success',request)
Esempio n. 43
0
	def render(self, request):
		if request.path[-1:] != '/':
			return util.redirectTo(request.path + '/', request)
		return static.File.render(self, request)
Esempio n. 44
0
    def render_GET(self, request):
        request.getSession().expire()

        return redirectTo("login", request)
Esempio n. 45
0
 def render_GET(self, request):
     return redirectTo("/", request)
Esempio n. 46
0
 def render(self, request):
     url_path = request.URLPath()
     url_path.scheme = 'https'
     return redirectTo(bytes(str(url_path), 'utf-8'), request)
Esempio n. 47
0
 def render_GET(self, request):  # for home page redirect
     return redirectTo(str(datetime.now().year), request)
Esempio n. 48
0
 def render_GET(self, request):
     request.addCookie(S4_SIGNUP_STYLE_COOKIE,
                       request.args.get(b"style", [b"email"])[0])
     return redirectTo(b"/s4-subscription-form", request)
Esempio n. 49
0
    def render(self, req):
        extraMeta = ''
        MenuStatusMSG = ''
        req.setHeader('Content-type', 'text/html')
        req.setHeader('charset', 'UTF-8')
        """ rendering server response """
        if len(req.args.keys()) > 0:
            key = req.args.keys()[0]
            arg = req.args.get(key, None)[0]
            print 'Received: ', key, '=', arg

            try:
                if key is None or arg is None:
                    pass
                elif key == 'cmd' and arg[:3] == 'ON:':
                    exec(
                        'config.plugins.iptvplayer.%s.setValue(True)\nconfig.plugins.iptvplayer.%s.save()'
                        % (arg[3:], arg[3:]))
                    settings.configsHTML = {}
                    settings.activeHostsHTML = {}
                    return util.redirectTo("/iptvplayer/settings", req)
                elif key == 'cmd' and arg[:4] == 'OFF:':
                    print(
                        'config.plugins.iptvplayer.%s.setValue(False)\nconfig.plugins.iptvplayer.%s.save()'
                        % (arg[4:], arg[4:]))
                    exec(
                        'config.plugins.iptvplayer.%s.setValue(False)\nconfig.plugins.iptvplayer.%s.save()'
                        % (arg[4:], arg[4:]))
                    settings.activeHostsHTML.pop(arg[4:], None)
                    settings.activeHostsHTML.pop(arg[8:], None)
                    settings.configsHTML = {}
                    return util.redirectTo("/iptvplayer/settings", req)
                elif key[:4] == "CFG:":
                    exec(
                        'config.plugins.iptvplayer.%s.setValue("%s")\nconfig.plugins.iptvplayer.%s.save()'
                        % (key[4:], arg, key[4:]))
                    settings.configsHTML = {}
                    return util.redirectTo("/iptvplayer/settings", req)
                elif key[:4] == "INT:":
                    exec(
                        'config.plugins.iptvplayer.%s.setValue("%s")\nconfig.plugins.iptvplayer.%s.save()'
                        % (key[4:], arg, key[4:]))
                    settings.configsHTML = {}
                    return util.redirectTo("/iptvplayer/settings", req)
                configfile.save()
            except Exception:
                printDBG(
                    "[webSite.py:settingsPage] EXCEPTION for updating value '%s' for key '%s'"
                    % (arg, key))

        if isConfigsHTMLempty() and not isThreadRunning('buildConfigsHTML'):
            webThreads.buildConfigsHTML().start()
            extraMeta = '<meta http-equiv="refresh" content="1">'
            MenuStatusMSG = _('Initiating data, please wait')
        elif isThreadRunning('buildConfigsHTML'):
            extraMeta = '<meta http-equiv="refresh" content="1">'
            MenuStatusMSG = _('Loading data, please wait')
        else:
            extraMeta = ''
            MenuStatusMSG = ''

        reloadScripts()
        html = '<html lang="%s">' % language.getLanguage()[:2]
        html += webParts.IncludeHEADER(extraMeta)
        html += webParts.Body().settingsPageContent(MenuStatusMSG)

        return html
Esempio n. 50
0
    def render(self, req):
        reloadScripts()
        
        """ rendering server response """
        self.key = None
        self.arg = None
        self.searchType = None
        html= ''
        extraMeta = ''
        MenuStatusMSG = ''
        
        if len(req.args.keys()) > 0:
            self.key = req.args.keys()[0]
            self.arg = req.args.get(self.key,None)[0]
            if len(req.args.keys()) > 1:
                self.searchType = req.args.keys()[1]
                print "useHostPage received: '%s'='%s' searchType='%s'" % (self.key, str(self.arg), self.searchType)
            else:
                print "useHostPage received: '%s'='%s'" % (self.key, str(self.arg))
        
        if self.key is None and isActiveHostInitiated() == False:
            return util.redirectTo("/iptvplayer/hosts", req)
        elif self.key == 'cmd' and self.arg == 'hosts':
            initActiveHost(None)
            return util.redirectTo("/iptvplayer/hosts", req)
        elif self.key == 'cmd' and self.arg == 'stopThread':
            stopRunningThread('doUseHostAction')
            initActiveHost(None)
            setNewHostListShown(False)
            return util.redirectTo("/iptvplayer/hosts", req)
        elif self.key == 'cmd' and self.arg == 'InitList':
            settings.retObj = settings.activeHost['Obj'].getInitList()
            settings.activeHost['PathLevel'] = 1
            settings.activeHost['ListType'] = 'ListForItem'
            settings.activeHost['Status'] =  ''
            settings.currItem = {}
            setNewHostListShown(False)
        elif self.key == 'cmd' and self.arg == 'PreviousList':
            settings.retObj = settings.activeHost['Obj'].getPrevList()
            settings.activeHost['PathLevel'] -= 1
            settings.activeHost['ListType'] = 'ListForItem'
            settings.currItem = {}
            settings.activeHost['Status'] = settings.activeHost['Status'].rpartition('>')[0]
            setNewHostListShown(False)
        #long running commands
        elif isNewHostListShown() and not isThreadRunning('doUseHostAction'):
            self.Counter = 0
            setNewHostListShown(False)
            webThreads.doUseHostAction(self.key, self.arg, self.searchType).start()
            extraMeta = '<meta http-equiv="refresh" content="1">'
            MenuStatusMSG = _('Initiating data, please wait')
        elif isThreadRunning('doUseHostAction'):
            self.Counter += 1
            extraMeta = '<meta http-equiv="refresh" content="1">'
            MenuStatusMSG = _('Loading data, please wait (%d)') % self.Counter

        req.setHeader('Content-type', 'text/html')
        req.setHeader('charset', 'UTF-8')

        html += '<html lang="%s">' % language.getLanguage()[:2]
        html += webParts.IncludeHEADER(extraMeta)
        html += webParts.Body().useHostPageContent( MenuStatusMSG, True )
        return html
Esempio n. 51
0
    def render(self, req):
        req.setHeader('Content-type', 'text/html')
        req.setHeader('charset', 'UTF-8')

        if len(req.args.keys()) > 0:
            key = req.args.keys()[0]
            arg = req.args.get(key,None)[0]
            if len(req.args.keys()) > 1:
                if req.args.keys()[1] == 'type':
                    if req.args.get(req.args.keys()[1],'ALL')[0] == '':
                        settings.GlobalSearchTypes = ["VIDEO","AUDIO"]
                    elif req.args.get(req.args.keys()[1],'ALL')[0] == '':
                        settings.GlobalSearchTypes = ["AUDIO"]
                    else:
                        settings.GlobalSearchTypes = ["VIDEO"]
                arg = req.args.get(key,None)[0]
            #print 'searchPage received: ', key, '=' , arg
        else:
            key = None
            arg = None
            
        """ rendering server response """
        reloadScripts()
        
        if key is None or arg is None or arg == '':
            if isThreadRunning('doGlobalSearch'):
                stopRunningThread('doGlobalSearch')
                self.Counter += 1
                extraMeta = '<meta http-equiv="refresh" content="1">'
                MenuStatusMSG = _('Waiting search thread to stop, please wait (%d)') % (self.Counter)
            else:
                MenuStatusMSG = ''
                extraMeta = ''
                settings.GlobalSearchListShown = True
            ShowCancelButton = False
        elif key == 'cmd' and arg == 'stopThread':
            stopRunningThread('doGlobalSearch')
            self.Counter = 0
            return util.redirectTo("/iptvplayer/search", req)
        elif not isThreadRunning('doGlobalSearch') and key == 'GlobalSearch' and settings.GlobalSearchListShown == True:
            settings.GlobalSearchListShown = False
            settings.GlobalSearchQuery = arg
            webThreads.doGlobalSearch().start()
            self.Counter = 0
            extraMeta = '<meta http-equiv="refresh" content="1">'
            MenuStatusMSG = _('Initiating data, please wait')
            ShowCancelButton = False
            return util.redirectTo("/iptvplayer/search?doGlobalSearch=1", req)
        elif isThreadRunning('doGlobalSearch'):
            self.Counter += 1
            extraMeta = '<meta http-equiv="refresh" content="1">'
            if settings.searchingInHost is None:
                MenuStatusMSG = _('Searching, please wait (%d)') % (self.Counter)
            else:
                MenuStatusMSG = _('Searching in %s, please wait (%d)') % (settings.searchingInHost, self.Counter)
            ShowCancelButton = True
        elif not isThreadRunning('doGlobalSearch') and key == 'doGlobalSearch':
            return util.redirectTo("/iptvplayer/search", req)
        else:
            ShowCancelButton = False
            MenuStatusMSG = ''
            extraMeta = ''
            settings.GlobalSearchListShown = False
          
        html = '<html lang="%s">' % language.getLanguage()[:2]
        html += webParts.IncludeHEADER(extraMeta)
        html += webParts.Body().SearchPageContent(MenuStatusMSG, ShowCancelButton)
        return html 
Esempio n. 52
0
    def render_GET(self, request):
        #A GET request to a token URL can trigger one of a few responses:
        # 1. Check if link has been clicked on (rather than loaded from an
        #    <img>) by looking at the Accept header, then:
        #  1a. If browser security if enabled, serve that page and stop.
        #  1b. If fortune in enabled, serve a fortune and stop.
        # 2. Otherwise we'll serve an image:
        #  2a. If a custom image is attached to the canarydrop, serve that and stop.
        #  2b. Serve our default 1x1 gif

        request.setHeader("Server", "Apache")
        try:
            token = Canarytoken(value=request.path)
            canarydrop = Canarydrop(**get_canarydrop(
                canarytoken=token.value()))
            if request.args.get('ts_key', [None])[0]:
                canarydrop._drop['hit_time'] = request.args.get(
                    'ts_key', [None])[0]
            else:
                canarydrop._drop['hit_time'] = datetime.datetime.utcnow(
                ).strftime("%s.%f")
            useragent = request.getHeader('User-Agent')
            src_ip = request.getHeader('x-forwarded-for')

            #location and refere are for cloned sites
            location = request.args.get('l', [None])[0]
            referer = request.args.get('r', [None])[0]
            self.dispatch(canarydrop=canarydrop,
                          src_ip=src_ip,
                          useragent=useragent,
                          location=location,
                          referer=referer)

            print dir(canarydrop)
            print vars(canarydrop)
            if 'redirect_url' in canarydrop._drop and canarydrop._drop[
                    'redirect_url']:
                # if fast redirect
                if canarydrop._drop['type'] == 'fast_redirect':
                    return redirectTo(canarydrop._drop['redirect_url'],
                                      request)
                    #template = env.get_template('browser_scanner.html')
                    #return template.render(key=canarydrop._drop['hit_time'],
                    #                       canarytoken=token.value()).encode('utf8')
                elif canarydrop._drop['type'] == 'slow_redirect':
                    template = env.get_template('browser_scanner.html')
                    return template.render(
                        key=canarydrop._drop['hit_time'],
                        canarytoken=token.value(),
                        redirect_url=canarydrop._drop['redirect_url']).encode(
                            'utf8')

            if request.getHeader(
                    'Accept') and "text/html" in request.getHeader('Accept'):
                if canarydrop['browser_scanner_enabled']:
                    template = env.get_template('browser_scanner.html')
                    return template.render(key=canarydrop._drop['hit_time'],
                                           canarytoken=token.value(),
                                           redirect_url='').encode('utf8')

                elif TOKEN_RETURN == 'fortune':
                    try:
                        fortune = subprocess.check_output('/usr/games/fortune')
                        template = env.get_template('fortune.html')
                        return template.render(fortune=fortune).encode('utf8')
                    except Exception as e:
                        log.err('Could not get a fortune: {e}'.format(e=e))
            if canarydrop['web_image_enabled'] and os.path.exists(
                    canarydrop['web_image_path']):
                mimetype = "image/" + canarydrop['web_image_path'][-3:]
                with open(canarydrop['web_image_path'], "r") as f:
                    contents = f.read()
                request.setHeader("Content-Type", mimetype)
                return contents

        except Exception as e:
            log.err('Error in render GET: {error}'.format(error=e))

        request.setHeader("Content-Type", "image/gif")
        return self.GIF
Esempio n. 53
0
 def render_GET(self, request):
     return redirectTo("feed.rss", request)
Esempio n. 54
0
    def render(self, req):
        req.setHeader('Content-type', 'text/html')
        req.setHeader('charset', 'UTF-8')

        """ rendering server response """
        extraMeta = '<meta http-equiv="refresh" content="5">'
        key = None
        arg = None
        arg2 = None
        arg3 = None
        DMlist = []
        if len(req.args.keys()) >= 1:
            key = req.args.keys()[0]
            arg = req.args.get(key,None)[0]
            try: arg2 = req.args.get(key,None)[1]
            except Exception: pass
            try: arg3 = req.args.get(key,None)[2]
            except Exception: pass
            print 'Received: "%s"="%s","%s","%s"' % ( key,arg,arg2,arg3)

        if key is None or arg is None:
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
        elif key == 'cmd' and arg == 'initDM':
            if None == Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                printDBG('============WebSite.py Initialize Download Manager============')
                Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager = IPTVDMApi(2, int(config.plugins.iptvplayer.IPTVDMMaxDownloadItem.value))
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
        elif key == 'cmd' and arg == 'runDM':
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.runWorkThread() 
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
        elif key == 'cmd' and arg == 'stopDM':
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.stopWorkThread()
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
                extraMeta = '<meta http-equiv="refresh" content="10">'
        elif key == 'cmd' and arg == 'downloadsDM':
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
        elif key == 'watchMovie' and os.path.exists(arg):
            return util.redirectTo("/file?action=download&file=%s" % urllib.quote(arg.decode('utf8', 'ignore').encode('utf-8')) , req)
        elif key == 'stopDownload' and arg.isdigit():
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.stopDownloadItem(int(arg))
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
        elif key == 'downloadAgain' and arg.isdigit():
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.continueDownloadItem(int(arg))
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()
        elif key == 'removeMovie' and arg.isdigit():
            if None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.removeDownloadItem(int(arg))
                DMlist = Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList()

        elif key == 'cmd' and arg == 'arvchiveDM':
            if arg2 == 'deleteMovie' and os.path.exists(arg3):
                os.remove(arg3)
            elif arg2 == 'watchMovie' and os.path.exists(arg3):
                return util.redirectTo("/file?action=download&file=%s" % urllib.quote(arg3.decode('utf8', 'ignore').encode('utf-8')) , req)
            if os.path.exists(config.plugins.iptvplayer.NaszaSciezka.value) and None != Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager:
                files = os.listdir(config.plugins.iptvplayer.NaszaSciezka.value)
                files.sort(key=lambda x: x.lower())
                for item in files:
                    if item.startswith('.'): continue # do not list hidden items
                    if item[-4:].lower() not in ['.flv', '.mp4']: continue
                    fileName = os.path.join(config.plugins.iptvplayer.NaszaSciezka.value, item)
                    skip = False
                    for item2 in Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager.getList():
                        if fileName == item2.fileName.replace('//', '/'):
                            skip = True
                            break
                    if skip: continue
                    listItem = DMItemBase(url=fileName, fileName=fileName)
                    try: listItem.downloadedSize = os.path.getsize(fileName)
                    except Exception: listItem.downloadedSize = 0
                    listItem.status      = DMHelper.STS.DOWNLOADED
                    listItem.downloadIdx = -1
                    DMlist.append( listItem )
                if len(DMlist) == 0:
                    listItem = DMItemBase(_('Nothing has been downloaded yet.'), '')
                    listItem.status = 'INFO'
                    DMlist.append( listItem )
            
        if len(DMlist) == 0 and arg != 'arvchiveDM':
            listItem = DMItemBase(_('No materials waiting in the downloader queue'), '')
            listItem.status      = 'INFO'
            DMlist.append( listItem )
            extraMeta = ''
        elif len(DMlist) == 0 and arg in ['arvchiveDM','stopDM'] :
            extraMeta = ''
            
        reloadScripts()
        html = '<html lang="%s">' % language.getLanguage()[:2]
        html += webParts.IncludeHEADER(extraMeta)
        html += webParts.Body().downloaderPageContent(Plugins.Extensions.IPTVPlayer.components.iptvplayerwidget.gDownloadManager, DMlist)
        return html
Esempio n. 55
0
 def render(self, request):
     goto = getarg(request, b'goto', b'/')
     # we force the body content, otherwise Twisted redirectTo()
     # returns HTML with <meta http-equiv="refresh"
     redirectTo(goto, request)
     return b'redirecting...'
Esempio n. 56
0
 def _redirect_to_login(_):
     content = util.redirectTo("/%s" % LoginResource.BASE_URL, request)
     request.write(content)
     request.finish()
Esempio n. 57
0
 def render_GET(self, request):
     return redirectTo("/tournaments", request)
Esempio n. 58
0
 def render(self, request):
     return redirectTo(self.url, request)
Esempio n. 59
0
 def _onLicenseActivateSuccess(self, res, request):
     ## reload admin UI
     ##
     log.msg("\n\n!!! LICENSE ACTIVATED !!!\n\n")
     request.write(redirectTo("/", request))
     request.finish()
Esempio n. 60
0
def _finish(result, render, request):
    """
    Try to finish rendering the response to a request.

    This implements extra convenience functionality not provided by Twisted
    Web.  Various resources in Tahoe-LAFS made use of this functionality when
    it was provided by Nevow.  Rather than making that application code do the
    more tedious thing itself, we duplicate the functionality here.

    :param result: Something returned by a render method which we can turn
        into a response.

    :param render: The original render method which produced the result.

    :param request: The request being responded to.

    :return: ``None``
    """
    if isinstance(result, Failure):
        if result.check(CancelledError):
            return
        Message.log(
            message_type=u"allmydata:web:common-render:failure",
            message=result.getErrorMessage(),
        )
        _finish(
            _renderHTTP_exception(request, result),
            render,
            request,
        )
    elif IResource.providedBy(result):
        # If result is also using @render_exception then we don't want to
        # double-apply the logic.  This leads to an attempt to double-finish
        # the request.  If it isn't using @render_exception then you should
        # fix it so it is.
        Message.log(
            message_type=u"allmydata:web:common-render:resource",
            resource=fullyQualifiedName(type(result)),
        )
        result.render(request)
    elif isinstance(result, str):
        Message.log(message_type=u"allmydata:web:common-render:unicode", )
        request.write(result.encode("utf-8"))
        request.finish()
    elif isinstance(result, bytes):
        Message.log(message_type=u"allmydata:web:common-render:bytes", )
        request.write(result)
        request.finish()
    elif isinstance(result, DecodedURL):
        Message.log(message_type=u"allmydata:web:common-render:DecodedURL", )
        _finish(redirectTo(result.to_text().encode("utf-8"), request), render,
                request)
    elif result is None:
        Message.log(message_type=u"allmydata:web:common-render:None", )
        request.finish()
    elif result == NOT_DONE_YET:
        Message.log(message_type=u"allmydata:web:common-render:NOT_DONE_YET", )
        pass
    else:
        Message.log(message_type=u"allmydata:web:common-render:unknown", )
        log.err(
            "Request for {!r} handled by {!r} returned unusable {!r}".format(
                request.uri,
                fullyQualifiedName(render),
                result,
            ))
        request.setResponseCode(http.INTERNAL_SERVER_ERROR)
        _finish(b"Internal Server Error", render, request)