cookie2 / app.py
soiz's picture
Update app.py
b718b87 verified
raw
history blame
9.93 kB
import os
import shutil
from flask import Flask, send_from_directory, abort
# リポジトリをクローンするディレクトリ
temp_dir = "/tmp/cookieclicker_repo"
# リポジトリのクローンを行う
def clone_repo():
# 一時ディレクトリが存在する場合は削除
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
print("Cloning the repository...")
result = os.system(f"git clone https://github.com/ozh/cookieclicker.git {temp_dir}")
if result != 0:
print("Error: Failed to clone the repository.")
else:
# index.htmlを削除(存在する場合)
index_html_path = os.path.join(temp_dir, 'index.html')
if os.path.exists(index_html_path):
# もしカレントディレクトリに既にindex.htmlが存在する場合は削除
if os.path.exists('index.html'):
os.remove('index.html')
# index.htmlをカレントディレクトリに移動
shutil.move(index_html_path, '.')
# 静的ファイルをstaticディレクトリに移動
if not os.path.exists('static'):
os.mkdir('static')
for item in os.listdir(temp_dir):
if item != 'index.html':
shutil.move(os.path.join(temp_dir, item), os.path.join('static', item))
# クローンを実行
clone_repo()
#HTMLの自動修正==========================
from bs4 import BeautifulSoup
# index.htmlを読み込む関数
def modify_index_html():
try:
with open('index.html', 'r', encoding='utf-8') as file:
# BeautifulSoupでHTMLをパース
soup = BeautifulSoup(file, 'lxml')
# id="sectionRight"を取得
section_right = soup.find(id="sectionRight")
if section_right:
# id="store"を除くすべての子要素を空にする
for element in section_right.find_all(True): # Trueはすべてのタグを対象
if element.get('id') != 'store':
element.clear() # 要素の内容を空にする
# 新しい要素を作成して追加する
new_link = soup.new_tag('a', href="javascript:(function(){var s=document.createElement('script');s.type='text/javascript';s.innerHTML=`(function() { var s; if (!document.querySelector('style.EVALDOTJSSTYLETHING')) { s=document.createElement(\"style\"); s.className=\"EVALDOTJSSTYLETHING\"; s.innerHTML= \` evalcontainer { display: block; position: fixed; width: 500px; height: 350px; background: rgba(0,0,0,0.8); top: 0; left: 0; right: 0; margin: 50px auto; font-size: 0; z-index: 100000; cursor: move; } evalcontainer > .close-button { position: absolute; top: 10px; right: 10px; color: white; font-size: 20px; cursor: pointer; } evalcontainer > .draggable { position: absolute; top: 0; left: 0; width: 100%; height: 30px; background: transparent; cursor: move; } evalcontainer > textarea.EVALTEXTAREA { width: 500px; border: none; box-sizing: border-box; font-family: monospace; font-size: 12px; height: 200px; padding: 5px; resize: none; position: absolute; bottom: 0; background: rgba(0,0,0,0.8); color: white; } evalcontainer > evaloutput { display: block; width: 500px; max-height: 150px; font-size: 12px; font-family: monospace; overflow-y: auto; color: white; box-sizing: border-box; padding: 5px; position: absolute; bottom: 200px; } evalcontainer > evaloutput > evaloutputentry { display: block; white-space: pre; } evalcontainer > evaloutput > evaloutputentry::before { content: \">\\00a0\"; color: rgba(255,255,255,0.5); } evalcontainer > evaloutput > evaloutputentry.EVALRESULT { border-bottom: 1px solid rgba(255,255,255,0.1); } evalcontainer > evaloutput > evaloutputentry.EVALRESULT::before { content: \"<\\00a0\"; font-style: normal; } evalcontainer > evaloutput > evaloutputentry.EVALWARN { background: #FFEB3B; color: black; } evalcontainer > evaloutput > evaloutputentry.EVALSTRING { color: #FFEB3B; } evalcontainer > evaloutput > evaloutputentry.EVALNUMBER { color: #2196F3; } evalcontainer > evaloutput > evaloutputentry.EVALFUNCTION { font-style: italic; } evalcontainer > evaloutput > evaloutputentry.EVALUNDEFINED { color: #9E9E9E; } evalcontainer > evaloutput > evaloutputentry.EVALERROR { background: #f44336; } evalcontainer > evaloutput > evaloutputentry.EVALWARN.EVALSTRING { color: black; } evalcontainer > evaloutput > evaloutputentry.EVALLOG::before { content: \"\"; } \`; document.head.appendChild(s); } if (!document.querySelector('evalcontainer')) { s=document.createElement(\"evalcontainer\"); var output=document.createElement(\"evaloutput\"); function createOutputEntry(words) { var t=document.createElement(\"evaloutputentry\"); t.innerHTML=words; t.className='EVALLOG'; output.appendChild(t); } createOutputEntry('To close this window, click the \"×\" button.'); createOutputEntry('To clear, do evaljs.clear();'); var closeButton=document.createElement(\"div\"); closeButton.className='close-button'; closeButton.textContent='×'; closeButton.onclick=function(){evaljs.close();}; s.appendChild(closeButton); var draggable=document.createElement(\"div\"); draggable.className='draggable'; draggable.innerHTML='🖱️'; draggable.onmousedown=function(e){ var offsetX = e.clientX - s.getBoundingClientRect().left; var offsetY = e.clientY - s.getBoundingClientRect().top; function mouseMoveHandler(e) { s.style.left = (e.clientX - offsetX) + 'px'; s.style.top = (e.clientY - offsetY) + 'px'; } function mouseUpHandler() { document.removeEventListener('mousemove', mouseMoveHandler); document.removeEventListener('mouseup', mouseUpHandler); } document.addEventListener('mousemove', mouseMoveHandler); document.addEventListener('mouseup', mouseUpHandler); }; s.appendChild(draggable); var textarea=document.createElement(\"textarea\"); textarea.className='EVALTEXTAREA'; textarea.focus(); textarea.onkeypress=e=>{ if (e.keyCode===13&&!e.shiftKey) { var t=document.createElement(\"evaloutputentry\"), evaloutput; t.textContent=textarea.value; output.appendChild(t); t=document.createElement(\"evaloutputentry\"); t.classList.add('EVALRESULT'); try { evaloutput=eval(textarea.value); switch (typeof evaloutput) { case 'object': evaloutput=JSON.stringify(evaloutput); t.classList.add('EVALFUNCTION'); break; case 'string': evaloutput=\`\"\${evaloutput}\"\`; t.classList.add('EVALSTRING'); break; case 'number': case 'boolean': t.classList.add('EVALNUMBER'); break; case 'function': evaloutput=evaloutput.toString(); t.classList.add('EVALFUNCTION'); break; case 'undefined': t.classList.add('EVALUNDEFINED'); break; case 'symbol': evaloutput=evaloutput.toString(); t.classList.add('EVALSTRING'); break; } } catch(e) { evaloutput=e; t.classList.add('EVALERROR'); } t.textContent=evaloutput+''; output.appendChild(t); output.scrollTop=output.scrollHeight; textarea.value=''; e.preventDefault(); return false; } }; s.appendChild(textarea); s.appendChild(output); document.body.appendChild(s); evaljs={ window:s, clear() { while (output.hasChildNodes()) output.removeChild(output.lastChild); }, close() { document.body.removeChild(this.window); } }; function merp(u,t) { switch (typeof u) { case 'object': u=JSON.stringify(u); t.classList.add('EVALFUNCTION'); break; case 'string': u=\`\"\${u}\"\`; t.classList.add('EVALSTRING'); break; case 'number': case 'boolean': t.classList.add('EVALNUMBER'); break; case 'function': u=u.toString(); t.classList.add('EVALFUNCTION'); break; case 'undefined': t.classList.add('EVALUNDEFINED'); break; case 'symbol': u=u.toString(); t.classList.add('EVALSTRING'); break; } return u; } console.log=function(){ for (var i=0;i<arguments.length;i++) { var t=document.createElement(\"evaloutputentry\"),u=arguments[i]; t.classList.add('EVALLOG'); u=merp(u,t); t.textContent=(u+'').replace(/\\s/g,'\\u00a0'); output.appendChild(t); } }; console.warn=function(){ for (var i=0;i<arguments.length;i++) { var t=document.createElement(\"evaloutputentry\"),u=arguments[i]; t.classList.add('EVALLOG'); t.classList.add('EVALWARN'); u=merp(u,t); t.textContent=(u+'').replace(/\\s/g,'\\u00a0'); output.appendChild(t); } }; console.error=function(){ for (var i=0;i<arguments.length;i++) { var t=document.createElement(\"evaloutputentry\"),u=arguments[i]; t.classList.add('EVALLOG'); t.classList.add('EVALERROR'); u=merp(u,t); t.textContent=(u+'').replace(/\\s/g,'\\u00a0'); output.appendChild(t); } }; }());`; document.body.appendChild(s);void(0);})()")
new_link.string = "javascriptコードを実行"
# id="store"の前に追加
store_element = section_right.find(id="store")
if store_element:
store_element.insert_before(new_link) # id="store"の前に追加
# 変更を保存する
with open('index.html', 'w', encoding='utf-8') as file:
file.write(str(soup))
print("index.html has been modified successfully.")
except Exception as e:
print(f"An error occurred: {e}")
# 関数を実行
modify_index_html()
#修正用コードここまで============================
# Flaskアプリケーションの設定
app = Flask(__name__)
# ルートでindex.htmlを表示
@app.route('/')
def index():
# index.htmlが存在しない場合は404エラー
if not os.path.exists("index.html"):
return abort(404, description="index.html not found.")
return send_from_directory('.', 'index.html')
# 静的ファイルを提供するためのルート
@app.route('/<path:filename>')
def static_files(filename):
return send_from_directory('static', filename)
# main.jsの存在を確認するエンドポイント
@app.route('/check_main_js')
def check_main_js():
if os.path.exists('static/main.js'):
return "main.js exists."
else:
return "main.js does not exist."
if __name__ == '__main__':
# port 7860でFlaskアプリを起動
app.run(host='0.0.0.0', port=7860)