Пример #1
0
def main(web, build):
	# --------------------------------------------------------------------------
	#
	# POST
	#
	if web.environ('REQUEST_METHOD')=='POST':
		mailaddr = web.post('mailaddr')
		params = {
			'mailaddr':mailaddr
		}
		sql = """
			SELECT `uno`,`admin`,`ano`
			FROM `user`
			WHERE `mailaddr` = %(mailaddr)s
			AND `deleted` = 0;"""
		row = web.db.exe(sql, params=params, key=True)
		uno = row['uno']

		#
		# userが存在しない場合、メールを送信しない
		#
		if not row:
			return web.redirect('/signin?message=userNotFound')

		#
		# unoのhass化
		#
		uno16 = blossom.md5(row['uno'], 16)
		hash = str(uno16) + '.' + str(uno)
		#
		# パスワード再設定ページのメールを送信
		#
		txt = blossom.read('../template/eml/open.passremind.eml')
		txt = txt % {
		'mailaddr' :'*****@*****.**',
		'HTTP_HOST':web._environ['HTTP_HOST'],
		'hash'     :hash
		}
		result = blossom.Mail.send(txt)

		
	local = {
	}
	#return build(web, local, '/open/open.passremind.html')
	return build(web, local,'/open/' \
	 	+ web.path.replace('/', '.')[1:] + '.html')
Пример #2
0
def main(web, build):
    # --------------------------------------------------------------------------
    #
    # userの取得
    #
    # 画像の有無を確かめる
    sql = """
		SELECT `uno`
		FROM `icon`
		WHERE `uno` = %(uno)s
		"""
    params = {
        'uno': web.uno,
    }
    uno_image = web.db.exe(sql, params=params)

    #
    # 有無に応じてクエリを変更
    #
    if uno_image:
        sql = """
			SELECT *
			FROM `user`
			INNER JOIN `icon`
			ON `icon`.`uno` = `user`.`uno`
			WHERE `user`.`uno` = %(uno)s;"""
        params = {
            'uno': web.uno,
        }
        user = web.db.exe(sql, params=params, key=True)
        #
        # 画像はbool型に変換
        #
        user = {
            'uno': user['uno'],
            'name0': user['name0'],
            'name1': user['name1'],
            'name2': user['name2'],
            'name3': user['name3'],
            'mailaddr': user['mailaddr'],
            'has_icon': bool(user['uno']),
        }
    else:
        sql = """
			SELECT *
			FROM `user`
			WHERE `uno` = %(uno)s;"""
        params = {
            'uno': web.uno,
        }
        user = web.db.exe(sql, params=params, key=True)

    local = {'user': user}

    #
    # 内容を変更した場合
    #
    if web.environ('REQUEST_METHOD') == 'POST':
        #
        # パスワードの変更(メール送信)
        #
        if web.post('passreset'):
            web.setcookie_secure('user', str(web.uno), maxage=1800)
            hash = web.cookie('user')
            web.log(web.cookie('user'), "RED")
            txt = blossom.read('../template/eml/open.passremind.eml')
            txt = txt % {
                'mailaddr': '*****@*****.**',
                'HTTP_HOST': web._environ['HTTP_HOST'],
                'uno': web.uno,
                'hash': hash
            }
            web.log(txt, 'purple')
            result = blossom.Mail.send(txt)
            web.log(result, "blue")
            return build(web, local,'/user/' \
              + web.path.replace('/', '.')[1:] + '.html')

        name0 = web.post('name0')
        name1 = web.post('name1')
        name2 = web.post('name2')
        name3 = web.post('name3')
        password1 = web.post('password1')
        password2 = web.post('password2')
        mailaddr = web.post('mailaddr')

        sql = """
		UPDATE `user`
		SET `name0` = %(name0)s ,`name1` = %(name1)s ,`name2` = %(name2)s,
		`name3` = %(name3)s ,`mailaddr` = %(mailaddr)s ,
		WHERE `uno` = %(uno)s;"""

        params = {
            'name0': name0,
            'name1': name1,
            'name2': name2,
            'name3': name3,
            'mailaddr': mailaddr,
            'uno': web.uno,
        }
        web.db.exe(sql, params=params)

        #
        # 画像の更新
        image = web.post('image')
        web.log(image, "RED")
        if not image['filename'] == None:
            icon = image['body']
            icon = icon.hex()
            if uno_image:
                sql = """
				UPDATE `icon`
				SET `img` =  0x""" + icon + """
				WHERE `uno` = %(uno)s;"""
                params = {
                    'uno': uno,
                }
                web.db.exe(sql, params=params)
            else:
                sql = """
				INSERT INTO `icon` (`uno`,`img`)
				VALUES (%(uno)s, 0x""" + icon + ");" ""
                params = {
                    'uno': uno,
                }
                web.db.exe(sql, params=params, key=True)

    return build(web, local, '/user/user.index.html')
Пример #3
0
	def set_express_checkout(self, web, amount, tax, itemcode, itemname, email, return_url, cancel_url):
		#
		# [1/3] SetExpressCheckout
		#
		# 自由な使用が許可された PAYMENTREQUEST_0_CUSTOM に商品コードを格納し
		# 後の GetExpressCheckoutDetails にてその値を得る。
		#
		nvp = {
			'METHOD'   :'SetExpressCheckout',
			'VERSION'  :93,
			'USER'     :self._username,
			'PWD'      :self._password,
			'SIGNATURE':self._signature,
			'RETURNURL':return_url,
			'CANCELURL':cancel_url,
			'EMAIL'    :email,
			'L_PAYMENTREQUEST_0_AMT0'         :amount,
			'L_PAYMENTREQUEST_0_NAME0'        :itemname,
			'L_PAYMENTREQUEST_0_QTY0'         :1,
			'L_PAYMENTREQUEST_0_TAXAMT0'      :0,
			'L_PAYMENTREQUEST_0_ITEMCATEGORY0':'Physical',
			'PAYMENTREQUEST_0_PAYMENTACTION'  :'Sale',
			'PAYMENTREQUEST_0_CURRENCYCODE'   :'JPY',
			'PAYMENTREQUEST_0_AMT'            :amount + tax,
			'PAYMENTREQUEST_0_ITEMAMT'        :amount,
			'PAYMENTREQUEST_0_TAXAMT'         :tax,
			'PAYMENTREQUEST_0_CUSTOM'         :itemcode,
			'NOSHIPPING':1,
			'LOCALECODE':'ja_JP',
		}
		web.log(nvp, 'purple')
		#
		# 送信
		#
		req = requests.post(url=self._endpoint, data=nvp)
		#
		#	TOKEN=EC-XXXXXXXXXX
		#	TIMESTAMP=2014-10-10T11:12:42Z
		#	CORRELATIONID=b2220b38a5117
		#	ACK=Success
		#	VERSION=93
		#	BUILD=13637230
		#
		text = req.text
		web.log(text, 'purple')
		try:
			nvp = urllib.parse.parse_qs(text)
			nvp = {k: v[0] for k, v in nvp.items()}
		except:
			nvp = {}
		web.log(nvp, 'purple')
		#
		# 評価
		#
		if nvp.get('ACK')=='Success':
			#
			# (成功)
			#
			return web.redirect(self._webscr + nvp.get('TOKEN'))
		else:
			#
			# メール通知
			#
			txt = blossom.read('../resource/eml/paypal.err1.eml')
			txt = txt % {
				'text':text,
			}
			web.log(txt, 'purple')
			lossom.Mail.send(txt)
			#
			# (失敗)
			#
			return web.redirect(cancel_url)
Пример #4
0
	def get_express_checkout_details(self, web):
		#
		# 現在のURLに付与された ?token= の値を得る
		#
		token = web.get('token')
		# ----------------------------------------------------------------------
		#
		# [2/3] GetExpressCheckoutDetails
		#
		nvp = {
			'METHOD'   :'GetExpressCheckoutDetails',
			'VERSION'  :93,
			'USER'     :self._username,
			'PWD'      :self._password,
			'SIGNATURE':self._signature,
			'TOKEN'    :token,
		}
		web.log(nvp, 'purple')
		#
		# 送信
		#
		req = requests.post(url=self._endpoint, data=nvp)
		#
		#	TOKEN=EC-XXXXXXXXXX
		#	BILLINGAGREEMENTACCEPTEDSTATUS=0
		#	CHECKOUTSTATUS=PaymentActionNotInitiated
		#	TIMESTAMP=2014-10-10T11:13:50Z
		#	CORRELATIONID=b2220b38a5117
		#	ACK=Success
		#	VERSION=93
		#	BUILD=13630372
		#	[email protected]
		#	PAYERID=XXXXXXXXXX
		#	PAYERSTATUS=verified
		#	FIRSTNAME=Taro
		#	LASTNAME=Yamada
		#	COUNTRYCODE=JP
		#	CURRENCYCODE=JPY
		#	AMT=108
		#	ITEMAMT=100
		#	SHIPPINGAMT=0
		#	HANDLINGAMT=0
		#	TAXAMT=8
		#	INSURANCEAMT=0
		#	SHIPDISCAMT=0
		#	L_NAME0=バナナ
		#	L_QTY0=1
		#	L_TAXAMT0=8
		#	L_AMT0=100
		#	L_ITEMWEIGHTVALUE0=0.00000
		#	L_ITEMLENGTHVALUE0=0.00000
		#	L_ITEMWIDTHVALUE0=0.00000
		#	L_ITEMHEIGHTVALUE0=0.00000
		#	L_ITEMCATEGORY0=Digital
		#	PAYMENTREQUEST_0_CURRENCYCODE=JPY
		#	PAYMENTREQUEST_0_AMT=108
		#	PAYMENTREQUEST_0_ITEMAMT=100
		#	PAYMENTREQUEST_0_SHIPPINGAMT=0
		#	PAYMENTREQUEST_0_HANDLINGAMT=0
		#	PAYMENTREQUEST_0_TAXAMT=8
		#	PAYMENTREQUEST_0_INSURANCEAMT=0
		#	PAYMENTREQUEST_0_SHIPDISCAMT=0
		#	PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED=false
		#	L_PAYMENTREQUEST_0_NAME0=バナナ
		#	L_PAYMENTREQUEST_0_QTY0=1
		#	L_PAYMENTREQUEST_0_TAXAMT0=8
		#	L_PAYMENTREQUEST_0_AMT0=100
		#	L_PAYMENTREQUEST_0_ITEMWEIGHTVALUE0=0.00000
		#	L_PAYMENTREQUEST_0_ITEMLENGTHVALUE0=0.00000
		#	L_PAYMENTREQUEST_0_ITEMWIDTHVALUE0=0.00000
		#	L_PAYMENTREQUEST_0_ITEMHEIGHTVALUE0=0.00000
		#	L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital
		#	PAYMENTREQUESTINFO_0_ERRORCODE=0
		#
		text = req.text
		web.log(text, 'purple')
		try:
			nvp = urllib.parse.parse_qs(text)
			nvp = {k: v[0] for k, v in nvp.items()}
		except:
			nvp = {}
		web.log(nvp, 'purple')
		#
		# 本来は PAYERSTATUS=verfied だが実際は unverified が頻発する。
		# しかし続く支払い処理は問題なく行われる傾向にあるため続行する。
		#
		if nvp.get('PAYERSTATUS')!='verfied':
			web.log('[PAYERSTATUS] = ' + nvp.get('PAYERSTATUS'), 'red')
		#
		# 商品コード
		#
		itemcode = nvp.get('PAYMENTREQUEST_0_CUSTOM')
		# ----------------------------------------------------------------------
		#
		# [3/3] DoExpressCheckoutPayment
		#
		nvp = {
			'METHOD'   :'DoExpressCheckoutPayment',
			'VERSION'  :93,
			'USER'     :self._username,
			'PWD'      :self._password,
			'SIGNATURE':self._signature,
			'TOKEN'    :token,
			'PAYERID'  :nvp.get('PAYERID'),
			'PAYMENTREQUEST_0_ITEMAMT'      :nvp.get('PAYMENTREQUEST_0_ITEMAMT'),
			'PAYMENTREQUEST_0_TAXAMT'       :nvp.get('PAYMENTREQUEST_0_TAXAMT'),
			'PAYMENTREQUEST_0_AMT'          :nvp.get('PAYMENTREQUEST_0_AMT'),
			'PAYMENTREQUEST_0_PAYMENTACTION':'Sale',
			'PAYMENTREQUEST_0_CURRENCYCODE' :'JPY',
		}
		web.log(nvp, 'purple')
		#
		# 送信
		#
		req = requests.post(url=self._endpoint, data=nvp)
		#
		# 成功例:
		#	TOKEN=EC-XXXXXXXXXX
		#	SUCCESSPAGEREDIRECTREQUESTED=false
		#	TIMESTAMP=2014-10-10T11:15:08Z
		#	CORRELATIONID=b2220b38a5117
		#	ACK=Success
		#	VERSION=93
		#	BUILD=13630372
		#	INSURANCEOPTIONSELECTED=false
		#	SHIPPINGOPTIONISDEFAULT=false
		#	PAYMENTINFO_0_TRANSACTIONID=XXXXXXXXXX
		#	PAYMENTINFO_0_TRANSACTIONTYPE=expresscheckout
		#	PAYMENTINFO_0_PAYMENTTYPE=instant
		#	PAYMENTINFO_0_ORDERTIME=2014-10-10T11:15:08Z
		#	PAYMENTINFO_0_AMT=108
		#	PAYMENTINFO_0_FEEAMT=44
		#	PAYMENTINFO_0_TAXAMT=8
		#	PAYMENTINFO_0_CURRENCYCODE=JPY
		#	PAYMENTINFO_0_PAYMENTSTATUS=Completed
		#	PAYMENTINFO_0_PENDINGREASON=None
		#	PAYMENTINFO_0_REASONCODE=None
		#	PAYMENTINFO_0_PROTECTIONELIGIBILITY=Ineligible
		#	PAYMENTINFO_0_PROTECTIONELIGIBILITYTYPE=None
		#	PAYMENTINFO_0_SECUREMERCHANTACCOUNTID=XXXXXXXXXX
		#	PAYMENTINFO_0_ERRORCODE=0
		#	PAYMENTINFO_0_ACK=Success
		#
		# 失敗例:
		#	TIMESTAMP=2016-02-20T09:56:33Z
		#	CORRELATIONID=fe96b084db538
		#	ACK=Failure
		#	VERSION=93
		#	BUILD=18316154
		#	L_ERRORCODE0=10445
		#	L_SHORTMESSAGE0=
		#	  This transaction cannot be processed at this time.
		#	  Please try again later.
		#	L_LONGMESSAGE0=
		#	  This transaction cannot be processed at this time.
		#	  Please try again later.
		#	L_SEVERITYCODE0=Error
		#
		text = req.text
		web.log(text, 'purple')
		try:
			nvp = urllib.parse.parse_qs(text)
			nvp = {k: v[0] for k, v in nvp.items()}
		except:
			nvp = {}
		web.log(nvp, 'purple')
		#
		# 評価
		#
		if nvp.get('ACK')=='Success':
			#
			# (成功)
			#
			return itemcode
		else:
			#
			# メール通知
			#
			txt = blossom.read('../resource/eml/paypal.err3.eml')
			txt = txt % {
				'text':text,
			}
			web.log(txt, 'purple')
			blossom.Mail.send(txt)
			#
			# 2017.8 以降 L_ERRORCODE0=10486 が返されるエラーがが頻発した。原因は不明のままだが、支払い手続きを何度か繰り返すことで成功することがあることがわかった。そこで管理ページ上に「もう一度お試しください」とのメッセージを出した上で、利用者にお支払い手続きを再度行わせる。ここではそのリンク先のURLを返す。
			#
			if nvp.get('L_ERRORCODE0')=='10486':
				#
				# (リトライ)
				#
				return web._webscr + token
			else:
				#
				# (失敗)
				#
				return False
Пример #5
0
def main(web, build):
    # --------------------------------------------------------------------------
    get_uno = web.get('uno')
    #
    # ログイン中のユーザーの画像を取得
    #
    login_user_icon = matsuoka_func.get_icon(web, web.uno)

    #
    # エラー時の送信メッセージを準備
    #
    message = '?uno=' + str(get_uno) + '&mode=show'

    #
    # userの更新
    #
    if web.environ('REQUEST_METHOD') == 'POST':
        #
        #パスワードの再設定
        #
        if web.post('passreset'):
            web.setcookie_secure('user', str(get_uno), maxage=1800)
            hash = web.cookie('user')
            web.log(web.cookie('user'), "RED")
            txt = blossom.read('../template/eml/open.passremind.eml')
            txt = txt % {
                'mailaddr': '*****@*****.**',
                'HTTP_HOST': web._environ['HTTP_HOST'],
                'uno': get_uno,
                'hash': hash
            }
            web.log(txt, 'purple')
            result = blossom.Mail.send(txt)
            web.log(result, "blue")

            return web.redirect('/admin/users?message12=passreset')

        #
        # 登録内容の変更
        #
        asno = web.post('assign')
        name0 = web.post('name0')
        name1 = web.post('name1')
        #
        # カタカナ以外が入力されているとFalseが帰ってくる
        #
        name2 = matsuoka_func.katakana_validator(web.post('name2'))
        name3 = matsuoka_func.katakana_validator(web.post('name3'))

        #
        # その結果メッセージが送信される
        #
        if name2 == False or name3 == False:
            message += "&message1=name_notkatakana"

        admin = web.post('admin', 0)
        mailaddr = web.post('mailaddr')
        gender = web.post('gender', 0)

        #
        # 8桁の数字か確認する、違うならメッセージ送信
        #
        if len(web.post('birthday')) != 8:
            message += "&message2=birthday_notlen8"
        if not re.match(r'[0-9]+', web.post('birthday')):
            message += "&message3=birthday_notnumeric"

        ba = web.post('birthday')
        bayear = ba[0:4]
        bamonth = ba[4:6]
        baday = ba[6:8]
        months = re.match('0([0-9])', bamonth)
        days = re.match('0([0-9])', baday)
        if months:
            bamonth = months.group(1)
        if days:
            baday = days.group(1)
        ba = web.post('joinday')
        jyear = ba[0:4]
        jmonth = ba[4:6]
        jday = ba[6:8]
        jmonths = re.match('0([0-9])', jmonth)
        jdays = re.match('0([0-9])', jday)
        birthday = datetime.datetime(int(bayear), int(bamonth), int(baday), 0,
                                     0).strftime('%s')
        joinday = datetime.datetime(int(jyear), int(jmonth), int(jday), 0,
                                    0).strftime('%s')

        #
        # 画像
        #
        icon = web.post('icon')
        #
        # エラーがあればまとめて送信
        #
        if re.match('.+&message.+', message):
            return web.redirect('/admin/user' + str(message))

        sql = """
		UPDATE `user`
		SET `name0` = %(name0)s ,`name1` = %(name1)s , `name2` = %(name2)s ,
			`name3` = %(name3)s ,`admin` = %(admin)s , `asno` = %(asno)s, `mailaddr` = %(mailaddr)s,
			`gender` = %(gender)s ,`birthday` = %(birthday)s ,`joinday` = %(joinday)s
		WHERE `uno` = %(uno)s;
		"""
        params = {
            'uno': get_uno,
            'name0': name0,
            'name1': name1,
            'name2': name2,
            'name3': name3,
            'asno': asno,
            'admin': admin,
            'mailaddr': mailaddr,
            'gender': gender,
            'birthday': birthday,
            'joinday': joinday,
        }
        web.db.exe(sql, params=params, key=False)

        sql = """
		INSERT INTO `icon`
		SET `name0` = %(name0)s ,`name1` = %(name1)s , `name2` = %(name2)s ,
			`name3` = %(name3)s ,`admin` = %(admin)s , `asno` = %(asno)s, `mailaddr` = %(mailaddr)s,
			`gender` = %(gender)s ,`birthday` = %(birthday)s ,`joinday` = %(joinday)s
		WHERE `uno` = %(uno)s;
		"""

        return web.redirect('/admin/user?mode=show&uno=' + str(get_uno) +
                            '&message4=change_user')

    #
    # admin.usersで名前をクリックした場合
    #
    if web.get('mode') == 'show':
        #
        # 画面の仕様が固まり切るまで [*] にしておく
        #
        sql = """
		SELECT *
		FROM `user`
		LEFT JOIN `assign` USING (`asno`)
		WHERE `uno` = %(uno)s
		"""
        params = {
            'uno': get_uno,
        }
        user = web.db.exe(sql, params=params, key=True)
        user['birthday'] = datetime.datetime.fromtimestamp(
            int(user['birthday'])).strftime("%Y%m%d")
        user['joinday'] = datetime.datetime.fromtimestamp(int(
            user['joinday'])).strftime("%Y%m%d")

        sql = """
		SELECT `asno`,`asname`
		FROM `assign`
		WHERE `ano` = %(ano)s
		AND NOT `asno` = %(asno)s
		"""
        params = {'ano': user['ano'], 'asno': user['asno']}
        assign = web.db.exe(sql, params=params, key=False)

        #
        # 選択したuserのアイコン
        #
        user_icon = matsuoka_func.get_icon(web, get_uno)

        local = {
            'user': user,
            'assign': assign,
            'user_icon': user_icon,
            'login_user_icon': login_user_icon,
        }

        return build(web, local,'/admin/' \
          + web.path.replace('/', '.')[1:] + '.html')

    #
    # 削除ボタンを押した場合
    #
    if web.get('mode') == 'delete':
        if web.uno == int(get_uno):
            return web.redirect('/admin/users?message11=thisuser')
        sql = """
		UPDATE `user`
		SET `deleted` = '1'
		WHERE `uno` = %(uno)s;
		"""
        params = {
            'uno': get_uno,
        }
        #
        # 削除を実行
        #
        web.db.exe(sql, params=params, key=False)
        return web.redirect('/admin/users?message7=delete_user')

    #
    # 復帰ボタンを押した場合
    #
    if web.get('mode') == 'revive':
        if web.uno == int(get_uno):
            return web.redirect('/admin/users?message11=thisuser')
        sql = """
		UPDATE `user`
		SET `deleted` = '0'
		WHERE `uno` = %(uno)s;
		"""
        params = {
            'uno': get_uno,
        }

        #
        # 復帰を実行
        #
        web.db.exe(sql, params=params, key=False)
        return web.redirect('/admin/users?message8=rivive_user')

    return web.redirect('/admin/users')
Пример #6
0
def compile(web, ext, files, option):
    #
    # src, dst, wch
    #
    timehash = blossom.md5(str(time.time()).encode(), 16)
    path_src = '../gulpd.workspace/src/' + timehash
    path_dst = '../gulpd.workspace/dst/' + timehash
    path_wch = '../gulpd.workspace/wch/' + timehash + '.' + ext
    #
    # ソースコード配置
    #
    for cid, body in files.items():
        blossom.write(path_src + cid, body)
    #
    # 削除のための所有権を得るために出力先ディレクトリを自前で作成しておく
    #
    os.mkdir(path_dst)
    os.chmod(path_dst, 0o777)
    #
    # コンパイル開始
    #
    blossom.write(path_wch, blossom.json(option))
    time.sleep(.3)
    #
    # コンパイル終了
    #
    body = None
    c = .0
    while c < 4.0:
        time.sleep(.1)
        body = blossom.read(path_dst + '/gulp.' + ext)
        if body:
            break
        else:
            c += .1
    else:
        body = '@Error\nCompile Timeout.'
    #
    # @Error|not
    #
    if body.startswith('@Error\n'):
        #
        # エラーメッセージ整形
        #
        # 内容に含まれるファイルのフルパスが一般利用者に知られるのは
        # セキュリティ上の理由から好ましくないため、パスの接頭部分を削除して
        # ユーザのファイルシステム上のパスに変換する。
        #
        body = body[7:]
        body = re.sub(r'[./\w]+' + timehash, '', body)
        if body == 'undefined':
            body = 'Unknown Error'
    else:
        #
        # ソースマップ
        #
        # ファイル末尾の表記を削除する
        # //# sourceMappingURL=gulp.scss.map
        #
        body = re.sub(r'\s*//# sourceMappingURL=.+\s*', '', body)
        #
        # 外部ファイルへ書き出されているマップを追記する。
        #
        if option.get('sourcemaps'):
            filename = path_dst + '/gulp.' + ext + '.map'
            sourcemap = blossom.read(filename, raw=True)
            if sourcemap:
                import base64
                body += ('\n' +
                         '/*# sourceMappingURL=data:application/json;base64,' +
                         base64.b64encode(sourcemap).decode() + ' */')
            else:
                web.log('Not Found: ' + filename, 'red')
    #
    # 掃除
    #
    try:
        shutil.rmtree(path_src, ignore_errors=True)
    except:
        pass
    try:
        shutil.rmtree(path_dst, ignore_errors=True)
    except:
        pass
    try:
        os.remove(path_wch)
    except:
        pass
    #
    # 以上の処理で使用済みの作業ディレクトリは削除されているはずだが、
    # それ以前の処理にて削除されず残っているディレクトリがある場合は、
    # 60秒経過を基準にして削除する。
    #
    for dir0 in ('../gulpd.workspace/src', '../gulpd.workspace/dst'):
        for dir1 in os.listdir(dir0):
            abs_path = dir0 + '/' + dir1
            if os.stat(abs_path).st_mtime < web.now4 - 60:
                #
                # log
                #
                web.log('shutil.rmtree(' + abs_path + ')', 'red')
                #
                # 削除
                #
                shutil.rmtree(abs_path, ignore_errors=True)
    #
    # return
    #
    return body
Пример #7
0
def main(web, build):
    # --------------------------------------------------------------------------
    #
    # エラー時の送信メッセージを準備
    #
    message = '/admin/user.import' + '?'
    #
    # userの新規登録
    #
    if web.environ('REQUEST_METHOD') == 'POST':
        asno = web.post('assign')
        admin = web.post('admin')
        name0 = web.post('name0')
        name1 = web.post('name1')
        #
        # フルネールを生成
        #
        fullname = str(name0 + name1)
        #
        # カタカナ以外が入力されているとFalseが帰ってくる
        #
        name2 = matsuoka_func.katakana_validator(web.post('name2'))
        name3 = matsuoka_func.katakana_validator(web.post('name3'))
        #
        # その結果メッセージが送信される
        #
        if name2 == False or name3 == False:
            message += "&message1=name_notkatakana"
        #
        # 誕生日のバリテーションチェック
        #
        if len(web.post('birthday')) != 8:
            message += "&message2=birthday_notlen8"
        if not re.match(r'[0-9]+', web.post('birthday')):
            message += "&message3=birthday_notnumeric"
        #
        # エラーが存在していればリダイレクト
        #
        if re.match('.+&message.+', message):
            return web.redirect(str(message))

        mailaddr = web.post('mailaddr')
        letters = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        password = ''.join(
            random.choices(string.ascii_letters + string.digits, k=8))
        gender = web.post('gender', 0)
        ba = web.post('birthday')
        bayear = ba[0:4]
        bamonth = ba[4:6]
        baday = ba[6:8]
        months = re.match('0([0-9])', bamonth)
        days = re.match('0([0-9])', baday)
        if months:
            bamonth = months.group(1)
        if days:
            baday = days.group(1)
        ba = web.post('joinday')
        jyear = ba[0:4]
        jmonth = ba[4:6]
        jday = ba[6:8]
        jmonths = re.match('0([0-9])', jmonth)
        jdays = re.match('0([0-9])', jday)
        if jmonths:
            jmonth = jmonths.group(1)
        if jdays:
            jday = jdays.group(1)

        birthday = datetime.datetime(int(bayear), int(bamonth), int(baday), 0,
                                     0).strftime('%s')
        joinday = datetime.datetime(int(jyear), int(jmonth), int(jday), 0,
                                    0).strftime('%s')
        created4 = web.now4
        #
        # passwordをハッシュ化
        #
        passhash16 = blossom.md5(password, 16)
        #
        # userテーブルに登録
        #
        sql = """
		INSERT INTO
		`user` (`uno`, `ano`, `asno`, `admin`, `name0`, `name1`, `name2`,
		`name3`, `mailaddr`, `passhash`, `gender`, `birthday`, `joinday`, `created4`)
		VALUES
 		(NULL, %(ano)s, '%(asno)s', %(admin)s, %(name0)s, %(name1)s, %(name2)s,
 		%(name3)s, %(mailaddr)s, 0x""" + passhash16 + """, %(gender)s,
		%(birthday)s, %(joinday)s, %(created4)s);"""
        params = {
            'ano': int(web.ano),
            'asno': int(asno),
            'admin': int(admin),
            'name0': str(name0),
            'name1': str(name1),
            'name2': str(name2),
            'name3': str(name3),
            'mailaddr': str(mailaddr),
            'gender': int(gender),
            'birthday': int(birthday),
            'joinday': int(joinday),
            'created4': int(created4),
        }
        web.db.exe(sql, params=params, key=True)
        #
        # 登録したユーザーにメールを送信
        #
        sql = """
		SELECT `uno`
		FROM `user`
		WHERE 1
		ORDER BY `uno` ASC
		LIMIT 1
		"""
        appuseruno = web.db.exe(sql, key=True)
        uno16 = blossom.md5(appuseruno, 16)
        hash = str(uno16) + '.' + str(web.uno)
        txt = blossom.read('../template/eml/admin.import_user.eml')
        txt = txt % {
            'fullname': fullname,
            'mailaddr': mailaddr,
            'password': password,
            'HTTP_HOST': web._environ['HTTP_HOST'],
            'hash': hash
        }
        #
        # メールが送信できなかった時の処理(demonは除く)
        #
        try:
            result = blossom.Mail.send(txt)
        except:
            sql = """
			DELETE `uno`
			FROM `user`
			WHERE `uno` = %(uno)s
			"""
            params = {
                'uno': user['uno'],
            }
            web.db.exe(sql, params=params, key=True)
            message += "&message10=mail_notsend"
            return web.redirect(str(message))

        #
        # 空のroleを作成
        # ここで作っておかないと/growth/role内で処理するのが面倒になる
        #
        sql = """
		SELECT *
		FROM `user`
		WHERE `ano` = %(ano)s"""
        params = {
            'ano': web.ano,
        }
        users = web.db.exe(sql, params=params)

        sql = """
		SELECT * FROM `user`
		ORDER BY `user`.`created4` DESC
		LIMIT 1
		"""
        user = web.db.exe(sql, key=True)

        for i, v in enumerate(users):
            #
            # 登録したばかりのユーザーをvunoとして、
            # 全てのunoに対してjsonが入っていないレコードを作成
            #
            # sql = """
            # INSERT INTO `role`
            # (`uno`, `vuno`, `time4`, `deleted`)
            # VALUES
            # (%(uno)s, %(vuno)s, %(time4)s, %(deleted)s);"""
            # params = {
            # 	'uno'    :user['uno'],
            # 	'vuno'   :users[i]['uno'],
            # 	'time4'  :web.now4,
            # 	'deleted':0,
            # }
            # web.db.exe(sql,params=params)
            # #
            # # ↑の処理だけだと、既存unoに対してのvunoは作成できるが、
            # #  逆は存在しないので改めて作る
            # #
            # sql = """
            # INSERT INTO `role`
            # (`uno`, `vuno`,`time4`,`deleted`)
            # VALUES
            # (%(vuno)s, %(uno)s, %(time4)s, %(deleted)s)
            # """
            # params = {
            # 	'uno'    :user['uno'],
            # 	'vuno'   :users[i]['uno'],
            # 	'time4'  :web.now4,
            # 	'deleted':1,
            # 	}
            # web.db.exe(sql,params=params)
            #
            # invlovmentoも同様に生成する
            #
            sql = """
			INSERT INTO `involvement`
			(`uno`, `vuno`, `time4`, `depth`, `deleted`)
			VALUES
			(%(uno)s, %(vuno)s, %(time4)s, `depth` ,%(deleted)s);"""
            params = {
                'uno': user['uno'],
                'vuno': users[i]['uno'],
                'time4': web.now4,
                'depth': 0,
                'deleted': 0,
            }
            web.db.exe(sql, params=params)
            if users[i]['uno'] == user['uno']:
                continue
            sql = """
			INSERT INTO `involvement`
			(`uno`, `vuno`, `time4`, `depth`, `deleted`)
			VALUES
			(%(vuno)s, %(uno)s, %(time4)s, `depth` ,%(deleted)s);"""
            params = {
                'uno': user['uno'],
                'vuno': users[i]['uno'],
                'time4': web.now4,
                'depth': 0,
                'deleted': 0,
            }
            web.db.exe(sql, params=params)
        #
        # 登録が成功したメッセージ
        #
        return web.redirect('/admin/users?message1=appuser')

    #
    # 部署一覧を取得して新規登録画面へ遷移
    #
    sql = """
	SELECT `asname`,`asno`
	FROM `assign`
	WHERE `ano` = %(ano)s"""
    params = {
        'ano': web.ano,
    }
    assign = web.db.exe(sql, params=params, key=False)

    local = {
        'item': assign,
        'user_icon': web.user_icon,
    }
    return build(web, local,'/admin/' \
      + web.path.replace('/', '.')[1:] + '.html')
Пример #8
0
def main(web, basedir, rebuild, maxage=1800):
    path_info = web.environ('PATH_INFO')
    #
    # css|js
    #
    src = basedir + path_info
    dst = basedir + path_info + '/_cache'
    ext = path_info.split('.')[-1]
    #
    # 304|cache|rebuild
    #
    if rebuild:
        #
        # 304 Not Modified
        #
        mtime = scan_mtime(src)
        if not web.if_modified_since(mtime):
            return web.echo(b'')
        #
        # rebuild
        #
        if ext == 'css':
            #
            # .css
            #
            files = blossom.glob(src, ['css', 'scss'])
            option = {
                'type': 'scss',
                'autoprefixer': 'on',
                'sourcemaps': '',
                'merge_media_queries': 'on',
                'csscomb': 'on',
                'clean_css': 'on',
            }
            body = gulp.compile(web, ext='scss', files=files, option=option)
        else:
            #
            # .js
            #
            files = {
                '/body.js': blossom.assemble(path_info, basedir=src),
            }
            option = {}
            body = gulp.compile(web, ext='js', files=files, option=option)
        #
        # write
        #
        blossom.write(dst, body)
        #
        # web.if_modified_since() の処理の過程で指定される最終更新日は
        # 前回の古いキャッシュの日時なので、今回の日時をここで指定する。
        #
        web.last_modified = os.stat(dst).st_mtime
        #
        # Cache-Control: max-age=900
        # Expires: Thu, 01 May 2018 23:59:59 GMT
        #
        web.maxage = maxage
    else:
        #
        # 304 Not Modified
        #
        mtime = os.stat(dst).st_mtime
        if not web.if_modified_since(mtime):
            return web.echo(b'')
        #
        # reuse
        #
        body = blossom.read(dst)
    #
    # output
    #
    ext = ext if ext == 'css' else 'javascript'
    web.setheader('Content-Type: text/' + ext + '; charset=UTF-8')
    return web.echo(body)